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 "MCTargetDesc/ARMAddressingModes.h"
12 #include "MCTargetDesc/ARMBaseInfo.h"
13 #include "MCTargetDesc/ARMMCExpr.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/MC/MCAssembler.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
24 #include "llvm/MC/MCELFStreamer.h"
25 #include "llvm/MC/MCExpr.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCInstrDesc.h"
28 #include "llvm/MC/MCInstrInfo.h"
29 #include "llvm/MC/MCObjectFileInfo.h"
30 #include "llvm/MC/MCParser/MCAsmLexer.h"
31 #include "llvm/MC/MCParser/MCAsmParser.h"
32 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
33 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
34 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
35 #include "llvm/MC/MCRegisterInfo.h"
36 #include "llvm/MC/MCSection.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSubtargetInfo.h"
39 #include "llvm/MC/MCSymbol.h"
40 #include "llvm/Support/ARMBuildAttributes.h"
41 #include "llvm/Support/ARMEHABI.h"
42 #include "llvm/Support/COFF.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ELF.h"
46 #include "llvm/Support/MathExtras.h"
47 #include "llvm/Support/SourceMgr.h"
48 #include "llvm/Support/TargetParser.h"
49 #include "llvm/Support/TargetRegistry.h"
50 #include "llvm/Support/raw_ostream.h"
51 
52 using namespace llvm;
53 
54 namespace {
55 
56 enum class ImplicitItModeTy { Always, Never, ARMOnly, ThumbOnly };
57 
58 static cl::opt<ImplicitItModeTy> ImplicitItMode(
59     "arm-implicit-it", cl::init(ImplicitItModeTy::ARMOnly),
60     cl::desc("Allow conditional instructions outdside of an IT block"),
61     cl::values(clEnumValN(ImplicitItModeTy::Always, "always",
62                           "Accept in both ISAs, emit implicit ITs in Thumb"),
63                clEnumValN(ImplicitItModeTy::Never, "never",
64                           "Warn in ARM, reject in Thumb"),
65                clEnumValN(ImplicitItModeTy::ARMOnly, "arm",
66                           "Accept in ARM, reject in Thumb"),
67                clEnumValN(ImplicitItModeTy::ThumbOnly, "thumb",
68                           "Warn in ARM, emit implicit ITs in Thumb")));
69 
70 class ARMOperand;
71 
72 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
73 
74 class UnwindContext {
75   MCAsmParser &Parser;
76 
77   typedef SmallVector<SMLoc, 4> Locs;
78 
79   Locs FnStartLocs;
80   Locs CantUnwindLocs;
81   Locs PersonalityLocs;
82   Locs PersonalityIndexLocs;
83   Locs HandlerDataLocs;
84   int FPReg;
85 
86 public:
87   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
88 
89   bool hasFnStart() const { return !FnStartLocs.empty(); }
90   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
91   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
92   bool hasPersonality() const {
93     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
94   }
95 
96   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
97   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
98   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
99   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
100   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
101 
102   void saveFPReg(int Reg) { FPReg = Reg; }
103   int getFPReg() const { return FPReg; }
104 
105   void emitFnStartLocNotes() const {
106     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
107          FI != FE; ++FI)
108       Parser.Note(*FI, ".fnstart was specified here");
109   }
110   void emitCantUnwindLocNotes() const {
111     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
112                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
113       Parser.Note(*UI, ".cantunwind was specified here");
114   }
115   void emitHandlerDataLocNotes() const {
116     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
117                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
118       Parser.Note(*HI, ".handlerdata was specified here");
119   }
120   void emitPersonalityLocNotes() const {
121     for (Locs::const_iterator PI = PersonalityLocs.begin(),
122                               PE = PersonalityLocs.end(),
123                               PII = PersonalityIndexLocs.begin(),
124                               PIE = PersonalityIndexLocs.end();
125          PI != PE || PII != PIE;) {
126       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
127         Parser.Note(*PI++, ".personality was specified here");
128       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
129         Parser.Note(*PII++, ".personalityindex was specified here");
130       else
131         llvm_unreachable(".personality and .personalityindex cannot be "
132                          "at the same location");
133     }
134   }
135 
136   void reset() {
137     FnStartLocs = Locs();
138     CantUnwindLocs = Locs();
139     PersonalityLocs = Locs();
140     HandlerDataLocs = Locs();
141     PersonalityIndexLocs = Locs();
142     FPReg = ARM::SP;
143   }
144 };
145 
146 class ARMAsmParser : public MCTargetAsmParser {
147   const MCInstrInfo &MII;
148   const MCRegisterInfo *MRI;
149   UnwindContext UC;
150 
151   ARMTargetStreamer &getTargetStreamer() {
152     assert(getParser().getStreamer().getTargetStreamer() &&
153            "do not have a target streamer");
154     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
155     return static_cast<ARMTargetStreamer &>(TS);
156   }
157 
158   // Map of register aliases registers via the .req directive.
159   StringMap<unsigned> RegisterReqs;
160 
161   bool NextSymbolIsThumb;
162 
163   bool useImplicitITThumb() const {
164     return ImplicitItMode == ImplicitItModeTy::Always ||
165            ImplicitItMode == ImplicitItModeTy::ThumbOnly;
166   }
167 
168   bool useImplicitITARM() const {
169     return ImplicitItMode == ImplicitItModeTy::Always ||
170            ImplicitItMode == ImplicitItModeTy::ARMOnly;
171   }
172 
173   struct {
174     ARMCC::CondCodes Cond;    // Condition for IT block.
175     unsigned Mask:4;          // Condition mask for instructions.
176                               // Starting at first 1 (from lsb).
177                               //   '1'  condition as indicated in IT.
178                               //   '0'  inverse of condition (else).
179                               // Count of instructions in IT block is
180                               // 4 - trailingzeroes(mask)
181                               // Note that this does not have the same encoding
182                               // as in the IT instruction, which also depends
183                               // on the low bit of the condition code.
184 
185     unsigned CurPosition;     // Current position in parsing of IT
186                               // block. In range [0,4], with 0 being the IT
187                               // instruction itself. Initialized according to
188                               // count of instructions in block.  ~0U if no
189                               // active IT block.
190 
191     bool IsExplicit;          // true  - The IT instruction was present in the
192                               //         input, we should not modify it.
193                               // false - The IT instruction was added
194                               //         implicitly, we can extend it if that
195                               //         would be legal.
196   } ITState;
197 
198   llvm::SmallVector<MCInst, 4> PendingConditionalInsts;
199 
200   void flushPendingInstructions(MCStreamer &Out) override {
201     if (!inImplicitITBlock()) {
202       assert(PendingConditionalInsts.size() == 0);
203       return;
204     }
205 
206     // Emit the IT instruction
207     unsigned Mask = getITMaskEncoding();
208     MCInst ITInst;
209     ITInst.setOpcode(ARM::t2IT);
210     ITInst.addOperand(MCOperand::createImm(ITState.Cond));
211     ITInst.addOperand(MCOperand::createImm(Mask));
212     Out.EmitInstruction(ITInst, getSTI());
213 
214     // Emit the conditonal instructions
215     assert(PendingConditionalInsts.size() <= 4);
216     for (const MCInst &Inst : PendingConditionalInsts) {
217       Out.EmitInstruction(Inst, getSTI());
218     }
219     PendingConditionalInsts.clear();
220 
221     // Clear the IT state
222     ITState.Mask = 0;
223     ITState.CurPosition = ~0U;
224   }
225 
226   bool inITBlock() { return ITState.CurPosition != ~0U; }
227   bool inExplicitITBlock() { return inITBlock() && ITState.IsExplicit; }
228   bool inImplicitITBlock() { return inITBlock() && !ITState.IsExplicit; }
229   bool lastInITBlock() {
230     return ITState.CurPosition == 4 - countTrailingZeros(ITState.Mask);
231   }
232   void forwardITPosition() {
233     if (!inITBlock()) return;
234     // Move to the next instruction in the IT block, if there is one. If not,
235     // mark the block as done, except for implicit IT blocks, which we leave
236     // open until we find an instruction that can't be added to it.
237     unsigned TZ = countTrailingZeros(ITState.Mask);
238     if (++ITState.CurPosition == 5 - TZ && ITState.IsExplicit)
239       ITState.CurPosition = ~0U; // Done with the IT block after this.
240   }
241 
242   // Rewind the state of the current IT block, removing the last slot from it.
243   void rewindImplicitITPosition() {
244     assert(inImplicitITBlock());
245     assert(ITState.CurPosition > 1);
246     ITState.CurPosition--;
247     unsigned TZ = countTrailingZeros(ITState.Mask);
248     unsigned NewMask = 0;
249     NewMask |= ITState.Mask & (0xC << TZ);
250     NewMask |= 0x2 << TZ;
251     ITState.Mask = NewMask;
252   }
253 
254   // Rewind the state of the current IT block, removing the last slot from it.
255   // If we were at the first slot, this closes the IT block.
256   void discardImplicitITBlock() {
257     assert(inImplicitITBlock());
258     assert(ITState.CurPosition == 1);
259     ITState.CurPosition = ~0U;
260     return;
261   }
262 
263   // Get the encoding of the IT mask, as it will appear in an IT instruction.
264   unsigned getITMaskEncoding() {
265     assert(inITBlock());
266     unsigned Mask = ITState.Mask;
267     unsigned TZ = countTrailingZeros(Mask);
268     if ((ITState.Cond & 1) == 0) {
269       assert(Mask && TZ <= 3 && "illegal IT mask value!");
270       Mask ^= (0xE << TZ) & 0xF;
271     }
272     return Mask;
273   }
274 
275   // Get the condition code corresponding to the current IT block slot.
276   ARMCC::CondCodes currentITCond() {
277     unsigned MaskBit;
278     if (ITState.CurPosition == 1)
279       MaskBit = 1;
280     else
281       MaskBit = (ITState.Mask >> (5 - ITState.CurPosition)) & 1;
282 
283     return MaskBit ? ITState.Cond : ARMCC::getOppositeCondition(ITState.Cond);
284   }
285 
286   // Invert the condition of the current IT block slot without changing any
287   // other slots in the same block.
288   void invertCurrentITCondition() {
289     if (ITState.CurPosition == 1) {
290       ITState.Cond = ARMCC::getOppositeCondition(ITState.Cond);
291     } else {
292       ITState.Mask ^= 1 << (5 - ITState.CurPosition);
293     }
294   }
295 
296   // Returns true if the current IT block is full (all 4 slots used).
297   bool isITBlockFull() {
298     return inITBlock() && (ITState.Mask & 1);
299   }
300 
301   // Extend the current implicit IT block to have one more slot with the given
302   // condition code.
303   void extendImplicitITBlock(ARMCC::CondCodes Cond) {
304     assert(inImplicitITBlock());
305     assert(!isITBlockFull());
306     assert(Cond == ITState.Cond ||
307            Cond == ARMCC::getOppositeCondition(ITState.Cond));
308     unsigned TZ = countTrailingZeros(ITState.Mask);
309     unsigned NewMask = 0;
310     // Keep any existing condition bits.
311     NewMask |= ITState.Mask & (0xE << TZ);
312     // Insert the new condition bit.
313     NewMask |= (Cond == ITState.Cond) << TZ;
314     // Move the trailing 1 down one bit.
315     NewMask |= 1 << (TZ - 1);
316     ITState.Mask = NewMask;
317   }
318 
319   // Create a new implicit IT block with a dummy condition code.
320   void startImplicitITBlock() {
321     assert(!inITBlock());
322     ITState.Cond = ARMCC::AL;
323     ITState.Mask = 8;
324     ITState.CurPosition = 1;
325     ITState.IsExplicit = false;
326     return;
327   }
328 
329   // Create a new explicit IT block with the given condition and mask. The mask
330   // should be in the parsed format, with a 1 implying 't', regardless of the
331   // low bit of the condition.
332   void startExplicitITBlock(ARMCC::CondCodes Cond, unsigned Mask) {
333     assert(!inITBlock());
334     ITState.Cond = Cond;
335     ITState.Mask = Mask;
336     ITState.CurPosition = 0;
337     ITState.IsExplicit = true;
338     return;
339   }
340 
341   void Note(SMLoc L, const Twine &Msg, SMRange Range = None) {
342     return getParser().Note(L, Msg, Range);
343   }
344   bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) {
345     return getParser().Warning(L, Msg, Range);
346   }
347   bool Error(SMLoc L, const Twine &Msg, SMRange Range = None) {
348     return getParser().Error(L, Msg, Range);
349   }
350 
351   bool validatetLDMRegList(const MCInst &Inst, const OperandVector &Operands,
352                            unsigned ListNo, bool IsARPop = false);
353   bool validatetSTMRegList(const MCInst &Inst, const OperandVector &Operands,
354                            unsigned ListNo);
355 
356   int tryParseRegister();
357   bool tryParseRegisterWithWriteBack(OperandVector &);
358   int tryParseShiftRegister(OperandVector &);
359   bool parseRegisterList(OperandVector &);
360   bool parseMemory(OperandVector &);
361   bool parseOperand(OperandVector &, StringRef Mnemonic);
362   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
363   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
364                               unsigned &ShiftAmount);
365   bool parseLiteralValues(unsigned Size, SMLoc L);
366   bool parseDirectiveThumb(SMLoc L);
367   bool parseDirectiveARM(SMLoc L);
368   bool parseDirectiveThumbFunc(SMLoc L);
369   bool parseDirectiveCode(SMLoc L);
370   bool parseDirectiveSyntax(SMLoc L);
371   bool parseDirectiveReq(StringRef Name, SMLoc L);
372   bool parseDirectiveUnreq(SMLoc L);
373   bool parseDirectiveArch(SMLoc L);
374   bool parseDirectiveEabiAttr(SMLoc L);
375   bool parseDirectiveCPU(SMLoc L);
376   bool parseDirectiveFPU(SMLoc L);
377   bool parseDirectiveFnStart(SMLoc L);
378   bool parseDirectiveFnEnd(SMLoc L);
379   bool parseDirectiveCantUnwind(SMLoc L);
380   bool parseDirectivePersonality(SMLoc L);
381   bool parseDirectiveHandlerData(SMLoc L);
382   bool parseDirectiveSetFP(SMLoc L);
383   bool parseDirectivePad(SMLoc L);
384   bool parseDirectiveRegSave(SMLoc L, bool IsVector);
385   bool parseDirectiveInst(SMLoc L, char Suffix = '\0');
386   bool parseDirectiveLtorg(SMLoc L);
387   bool parseDirectiveEven(SMLoc L);
388   bool parseDirectivePersonalityIndex(SMLoc L);
389   bool parseDirectiveUnwindRaw(SMLoc L);
390   bool parseDirectiveTLSDescSeq(SMLoc L);
391   bool parseDirectiveMovSP(SMLoc L);
392   bool parseDirectiveObjectArch(SMLoc L);
393   bool parseDirectiveArchExtension(SMLoc L);
394   bool parseDirectiveAlign(SMLoc L);
395   bool parseDirectiveThumbSet(SMLoc L);
396 
397   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
398                           bool &CarrySetting, unsigned &ProcessorIMod,
399                           StringRef &ITMask);
400   void getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
401                              bool &CanAcceptCarrySet,
402                              bool &CanAcceptPredicationCode);
403 
404   void tryConvertingToTwoOperandForm(StringRef Mnemonic, bool CarrySetting,
405                                      OperandVector &Operands);
406   bool isThumb() const {
407     // FIXME: Can tablegen auto-generate this?
408     return getSTI().getFeatureBits()[ARM::ModeThumb];
409   }
410   bool isThumbOne() const {
411     return isThumb() && !getSTI().getFeatureBits()[ARM::FeatureThumb2];
412   }
413   bool isThumbTwo() const {
414     return isThumb() && getSTI().getFeatureBits()[ARM::FeatureThumb2];
415   }
416   bool hasThumb() const {
417     return getSTI().getFeatureBits()[ARM::HasV4TOps];
418   }
419   bool hasThumb2() const {
420     return getSTI().getFeatureBits()[ARM::FeatureThumb2];
421   }
422   bool hasV6Ops() const {
423     return getSTI().getFeatureBits()[ARM::HasV6Ops];
424   }
425   bool hasV6T2Ops() const {
426     return getSTI().getFeatureBits()[ARM::HasV6T2Ops];
427   }
428   bool hasV6MOps() const {
429     return getSTI().getFeatureBits()[ARM::HasV6MOps];
430   }
431   bool hasV7Ops() const {
432     return getSTI().getFeatureBits()[ARM::HasV7Ops];
433   }
434   bool hasV8Ops() const {
435     return getSTI().getFeatureBits()[ARM::HasV8Ops];
436   }
437   bool hasV8MBaseline() const {
438     return getSTI().getFeatureBits()[ARM::HasV8MBaselineOps];
439   }
440   bool hasV8MMainline() const {
441     return getSTI().getFeatureBits()[ARM::HasV8MMainlineOps];
442   }
443   bool has8MSecExt() const {
444     return getSTI().getFeatureBits()[ARM::Feature8MSecExt];
445   }
446   bool hasARM() const {
447     return !getSTI().getFeatureBits()[ARM::FeatureNoARM];
448   }
449   bool hasDSP() const {
450     return getSTI().getFeatureBits()[ARM::FeatureDSP];
451   }
452   bool hasD16() const {
453     return getSTI().getFeatureBits()[ARM::FeatureD16];
454   }
455   bool hasV8_1aOps() const {
456     return getSTI().getFeatureBits()[ARM::HasV8_1aOps];
457   }
458   bool hasRAS() const {
459     return getSTI().getFeatureBits()[ARM::FeatureRAS];
460   }
461 
462   void SwitchMode() {
463     MCSubtargetInfo &STI = copySTI();
464     uint64_t FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
465     setAvailableFeatures(FB);
466   }
467   void FixModeAfterArchChange(bool WasThumb, SMLoc Loc);
468   bool isMClass() const {
469     return getSTI().getFeatureBits()[ARM::FeatureMClass];
470   }
471 
472   /// @name Auto-generated Match Functions
473   /// {
474 
475 #define GET_ASSEMBLER_HEADER
476 #include "ARMGenAsmMatcher.inc"
477 
478   /// }
479 
480   OperandMatchResultTy parseITCondCode(OperandVector &);
481   OperandMatchResultTy parseCoprocNumOperand(OperandVector &);
482   OperandMatchResultTy parseCoprocRegOperand(OperandVector &);
483   OperandMatchResultTy parseCoprocOptionOperand(OperandVector &);
484   OperandMatchResultTy parseMemBarrierOptOperand(OperandVector &);
485   OperandMatchResultTy parseInstSyncBarrierOptOperand(OperandVector &);
486   OperandMatchResultTy parseProcIFlagsOperand(OperandVector &);
487   OperandMatchResultTy parseMSRMaskOperand(OperandVector &);
488   OperandMatchResultTy parseBankedRegOperand(OperandVector &);
489   OperandMatchResultTy parsePKHImm(OperandVector &O, StringRef Op, int Low,
490                                    int High);
491   OperandMatchResultTy parsePKHLSLImm(OperandVector &O) {
492     return parsePKHImm(O, "lsl", 0, 31);
493   }
494   OperandMatchResultTy parsePKHASRImm(OperandVector &O) {
495     return parsePKHImm(O, "asr", 1, 32);
496   }
497   OperandMatchResultTy parseSetEndImm(OperandVector &);
498   OperandMatchResultTy parseShifterImm(OperandVector &);
499   OperandMatchResultTy parseRotImm(OperandVector &);
500   OperandMatchResultTy parseModImm(OperandVector &);
501   OperandMatchResultTy parseBitfield(OperandVector &);
502   OperandMatchResultTy parsePostIdxReg(OperandVector &);
503   OperandMatchResultTy parseAM3Offset(OperandVector &);
504   OperandMatchResultTy parseFPImm(OperandVector &);
505   OperandMatchResultTy parseVectorList(OperandVector &);
506   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index,
507                                        SMLoc &EndLoc);
508 
509   // Asm Match Converter Methods
510   void cvtThumbMultiply(MCInst &Inst, const OperandVector &);
511   void cvtThumbBranches(MCInst &Inst, const OperandVector &);
512 
513   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
514   bool processInstruction(MCInst &Inst, const OperandVector &Ops, MCStreamer &Out);
515   bool shouldOmitCCOutOperand(StringRef Mnemonic, OperandVector &Operands);
516   bool shouldOmitPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
517   bool isITBlockTerminator(MCInst &Inst) const;
518 
519 public:
520   enum ARMMatchResultTy {
521     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
522     Match_RequiresNotITBlock,
523     Match_RequiresV6,
524     Match_RequiresThumb2,
525     Match_RequiresV8,
526     Match_RequiresFlagSetting,
527 #define GET_OPERAND_DIAGNOSTIC_TYPES
528 #include "ARMGenAsmMatcher.inc"
529 
530   };
531 
532   ARMAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
533                const MCInstrInfo &MII, const MCTargetOptions &Options)
534     : MCTargetAsmParser(Options, STI), MII(MII), UC(Parser) {
535     MCAsmParserExtension::Initialize(Parser);
536 
537     // Cache the MCRegisterInfo.
538     MRI = getContext().getRegisterInfo();
539 
540     // Initialize the set of available features.
541     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
542 
543     // Not in an ITBlock to start with.
544     ITState.CurPosition = ~0U;
545 
546     NextSymbolIsThumb = false;
547   }
548 
549   // Implementation of the MCTargetAsmParser interface:
550   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
551   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
552                         SMLoc NameLoc, OperandVector &Operands) override;
553   bool ParseDirective(AsmToken DirectiveID) override;
554 
555   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
556                                       unsigned Kind) override;
557   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
558 
559   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
560                                OperandVector &Operands, MCStreamer &Out,
561                                uint64_t &ErrorInfo,
562                                bool MatchingInlineAsm) override;
563   unsigned MatchInstruction(OperandVector &Operands, MCInst &Inst,
564                             uint64_t &ErrorInfo, bool MatchingInlineAsm,
565                             bool &EmitInITBlock, MCStreamer &Out);
566   void onLabelParsed(MCSymbol *Symbol) override;
567 };
568 } // end anonymous namespace
569 
570 namespace {
571 
572 /// ARMOperand - Instances of this class represent a parsed ARM machine
573 /// operand.
574 class ARMOperand : public MCParsedAsmOperand {
575   enum KindTy {
576     k_CondCode,
577     k_CCOut,
578     k_ITCondMask,
579     k_CoprocNum,
580     k_CoprocReg,
581     k_CoprocOption,
582     k_Immediate,
583     k_MemBarrierOpt,
584     k_InstSyncBarrierOpt,
585     k_Memory,
586     k_PostIndexRegister,
587     k_MSRMask,
588     k_BankedReg,
589     k_ProcIFlags,
590     k_VectorIndex,
591     k_Register,
592     k_RegisterList,
593     k_DPRRegisterList,
594     k_SPRRegisterList,
595     k_VectorList,
596     k_VectorListAllLanes,
597     k_VectorListIndexed,
598     k_ShiftedRegister,
599     k_ShiftedImmediate,
600     k_ShifterImmediate,
601     k_RotateImmediate,
602     k_ModifiedImmediate,
603     k_ConstantPoolImmediate,
604     k_BitfieldDescriptor,
605     k_Token,
606   } Kind;
607 
608   SMLoc StartLoc, EndLoc, AlignmentLoc;
609   SmallVector<unsigned, 8> Registers;
610 
611   struct CCOp {
612     ARMCC::CondCodes Val;
613   };
614 
615   struct CopOp {
616     unsigned Val;
617   };
618 
619   struct CoprocOptionOp {
620     unsigned Val;
621   };
622 
623   struct ITMaskOp {
624     unsigned Mask:4;
625   };
626 
627   struct MBOptOp {
628     ARM_MB::MemBOpt Val;
629   };
630 
631   struct ISBOptOp {
632     ARM_ISB::InstSyncBOpt Val;
633   };
634 
635   struct IFlagsOp {
636     ARM_PROC::IFlags Val;
637   };
638 
639   struct MMaskOp {
640     unsigned Val;
641   };
642 
643   struct BankedRegOp {
644     unsigned Val;
645   };
646 
647   struct TokOp {
648     const char *Data;
649     unsigned Length;
650   };
651 
652   struct RegOp {
653     unsigned RegNum;
654   };
655 
656   // A vector register list is a sequential list of 1 to 4 registers.
657   struct VectorListOp {
658     unsigned RegNum;
659     unsigned Count;
660     unsigned LaneIndex;
661     bool isDoubleSpaced;
662   };
663 
664   struct VectorIndexOp {
665     unsigned Val;
666   };
667 
668   struct ImmOp {
669     const MCExpr *Val;
670   };
671 
672   /// Combined record for all forms of ARM address expressions.
673   struct MemoryOp {
674     unsigned BaseRegNum;
675     // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
676     // was specified.
677     const MCConstantExpr *OffsetImm;  // Offset immediate value
678     unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
679     ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
680     unsigned ShiftImm;        // shift for OffsetReg.
681     unsigned Alignment;       // 0 = no alignment specified
682     // n = alignment in bytes (2, 4, 8, 16, or 32)
683     unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
684   };
685 
686   struct PostIdxRegOp {
687     unsigned RegNum;
688     bool isAdd;
689     ARM_AM::ShiftOpc ShiftTy;
690     unsigned ShiftImm;
691   };
692 
693   struct ShifterImmOp {
694     bool isASR;
695     unsigned Imm;
696   };
697 
698   struct RegShiftedRegOp {
699     ARM_AM::ShiftOpc ShiftTy;
700     unsigned SrcReg;
701     unsigned ShiftReg;
702     unsigned ShiftImm;
703   };
704 
705   struct RegShiftedImmOp {
706     ARM_AM::ShiftOpc ShiftTy;
707     unsigned SrcReg;
708     unsigned ShiftImm;
709   };
710 
711   struct RotImmOp {
712     unsigned Imm;
713   };
714 
715   struct ModImmOp {
716     unsigned Bits;
717     unsigned Rot;
718   };
719 
720   struct BitfieldOp {
721     unsigned LSB;
722     unsigned Width;
723   };
724 
725   union {
726     struct CCOp CC;
727     struct CopOp Cop;
728     struct CoprocOptionOp CoprocOption;
729     struct MBOptOp MBOpt;
730     struct ISBOptOp ISBOpt;
731     struct ITMaskOp ITMask;
732     struct IFlagsOp IFlags;
733     struct MMaskOp MMask;
734     struct BankedRegOp BankedReg;
735     struct TokOp Tok;
736     struct RegOp Reg;
737     struct VectorListOp VectorList;
738     struct VectorIndexOp VectorIndex;
739     struct ImmOp Imm;
740     struct MemoryOp Memory;
741     struct PostIdxRegOp PostIdxReg;
742     struct ShifterImmOp ShifterImm;
743     struct RegShiftedRegOp RegShiftedReg;
744     struct RegShiftedImmOp RegShiftedImm;
745     struct RotImmOp RotImm;
746     struct ModImmOp ModImm;
747     struct BitfieldOp Bitfield;
748   };
749 
750 public:
751   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
752 
753   /// getStartLoc - Get the location of the first token of this operand.
754   SMLoc getStartLoc() const override { return StartLoc; }
755   /// getEndLoc - Get the location of the last token of this operand.
756   SMLoc getEndLoc() const override { return EndLoc; }
757   /// getLocRange - Get the range between the first and last token of this
758   /// operand.
759   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
760 
761   /// getAlignmentLoc - Get the location of the Alignment token of this operand.
762   SMLoc getAlignmentLoc() const {
763     assert(Kind == k_Memory && "Invalid access!");
764     return AlignmentLoc;
765   }
766 
767   ARMCC::CondCodes getCondCode() const {
768     assert(Kind == k_CondCode && "Invalid access!");
769     return CC.Val;
770   }
771 
772   unsigned getCoproc() const {
773     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
774     return Cop.Val;
775   }
776 
777   StringRef getToken() const {
778     assert(Kind == k_Token && "Invalid access!");
779     return StringRef(Tok.Data, Tok.Length);
780   }
781 
782   unsigned getReg() const override {
783     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
784     return Reg.RegNum;
785   }
786 
787   const SmallVectorImpl<unsigned> &getRegList() const {
788     assert((Kind == k_RegisterList || Kind == k_DPRRegisterList ||
789             Kind == k_SPRRegisterList) && "Invalid access!");
790     return Registers;
791   }
792 
793   const MCExpr *getImm() const {
794     assert(isImm() && "Invalid access!");
795     return Imm.Val;
796   }
797 
798   const MCExpr *getConstantPoolImm() const {
799     assert(isConstantPoolImm() && "Invalid access!");
800     return Imm.Val;
801   }
802 
803   unsigned getVectorIndex() const {
804     assert(Kind == k_VectorIndex && "Invalid access!");
805     return VectorIndex.Val;
806   }
807 
808   ARM_MB::MemBOpt getMemBarrierOpt() const {
809     assert(Kind == k_MemBarrierOpt && "Invalid access!");
810     return MBOpt.Val;
811   }
812 
813   ARM_ISB::InstSyncBOpt getInstSyncBarrierOpt() const {
814     assert(Kind == k_InstSyncBarrierOpt && "Invalid access!");
815     return ISBOpt.Val;
816   }
817 
818   ARM_PROC::IFlags getProcIFlags() const {
819     assert(Kind == k_ProcIFlags && "Invalid access!");
820     return IFlags.Val;
821   }
822 
823   unsigned getMSRMask() const {
824     assert(Kind == k_MSRMask && "Invalid access!");
825     return MMask.Val;
826   }
827 
828   unsigned getBankedReg() const {
829     assert(Kind == k_BankedReg && "Invalid access!");
830     return BankedReg.Val;
831   }
832 
833   bool isCoprocNum() const { return Kind == k_CoprocNum; }
834   bool isCoprocReg() const { return Kind == k_CoprocReg; }
835   bool isCoprocOption() const { return Kind == k_CoprocOption; }
836   bool isCondCode() const { return Kind == k_CondCode; }
837   bool isCCOut() const { return Kind == k_CCOut; }
838   bool isITMask() const { return Kind == k_ITCondMask; }
839   bool isITCondCode() const { return Kind == k_CondCode; }
840   bool isImm() const override {
841     return Kind == k_Immediate;
842   }
843 
844   bool isARMBranchTarget() const {
845     if (!isImm()) return false;
846 
847     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
848       return CE->getValue() % 4 == 0;
849     return true;
850   }
851 
852 
853   bool isThumbBranchTarget() const {
854     if (!isImm()) return false;
855 
856     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
857       return CE->getValue() % 2 == 0;
858     return true;
859   }
860 
861   // checks whether this operand is an unsigned offset which fits is a field
862   // of specified width and scaled by a specific number of bits
863   template<unsigned width, unsigned scale>
864   bool isUnsignedOffset() const {
865     if (!isImm()) return false;
866     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
867     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
868       int64_t Val = CE->getValue();
869       int64_t Align = 1LL << scale;
870       int64_t Max = Align * ((1LL << width) - 1);
871       return ((Val % Align) == 0) && (Val >= 0) && (Val <= Max);
872     }
873     return false;
874   }
875   // checks whether this operand is an signed offset which fits is a field
876   // of specified width and scaled by a specific number of bits
877   template<unsigned width, unsigned scale>
878   bool isSignedOffset() const {
879     if (!isImm()) return false;
880     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
881     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
882       int64_t Val = CE->getValue();
883       int64_t Align = 1LL << scale;
884       int64_t Max = Align * ((1LL << (width-1)) - 1);
885       int64_t Min = -Align * (1LL << (width-1));
886       return ((Val % Align) == 0) && (Val >= Min) && (Val <= Max);
887     }
888     return false;
889   }
890 
891   // checks whether this operand is a memory operand computed as an offset
892   // applied to PC. the offset may have 8 bits of magnitude and is represented
893   // with two bits of shift. textually it may be either [pc, #imm], #imm or
894   // relocable expression...
895   bool isThumbMemPC() const {
896     int64_t Val = 0;
897     if (isImm()) {
898       if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
899       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
900       if (!CE) return false;
901       Val = CE->getValue();
902     }
903     else if (isMem()) {
904       if(!Memory.OffsetImm || Memory.OffsetRegNum) return false;
905       if(Memory.BaseRegNum != ARM::PC) return false;
906       Val = Memory.OffsetImm->getValue();
907     }
908     else return false;
909     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
910   }
911   bool isFPImm() const {
912     if (!isImm()) return false;
913     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
914     if (!CE) return false;
915     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
916     return Val != -1;
917   }
918   bool isFBits16() const {
919     if (!isImm()) return false;
920     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
921     if (!CE) return false;
922     int64_t Value = CE->getValue();
923     return Value >= 0 && Value <= 16;
924   }
925   bool isFBits32() const {
926     if (!isImm()) return false;
927     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
928     if (!CE) return false;
929     int64_t Value = CE->getValue();
930     return Value >= 1 && Value <= 32;
931   }
932   bool isImm8s4() const {
933     if (!isImm()) return false;
934     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
935     if (!CE) return false;
936     int64_t Value = CE->getValue();
937     return ((Value & 3) == 0) && Value >= -1020 && Value <= 1020;
938   }
939   bool isImm0_1020s4() const {
940     if (!isImm()) return false;
941     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
942     if (!CE) return false;
943     int64_t Value = CE->getValue();
944     return ((Value & 3) == 0) && Value >= 0 && Value <= 1020;
945   }
946   bool isImm0_508s4() const {
947     if (!isImm()) return false;
948     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
949     if (!CE) return false;
950     int64_t Value = CE->getValue();
951     return ((Value & 3) == 0) && Value >= 0 && Value <= 508;
952   }
953   bool isImm0_508s4Neg() const {
954     if (!isImm()) return false;
955     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
956     if (!CE) return false;
957     int64_t Value = -CE->getValue();
958     // explicitly exclude zero. we want that to use the normal 0_508 version.
959     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
960   }
961   bool isImm0_239() const {
962     if (!isImm()) return false;
963     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
964     if (!CE) return false;
965     int64_t Value = CE->getValue();
966     return Value >= 0 && Value < 240;
967   }
968   bool isImm0_255() 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 >= 0 && Value < 256;
974   }
975   bool isImm0_4095() const {
976     if (!isImm()) return false;
977     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
978     if (!CE) return false;
979     int64_t Value = CE->getValue();
980     return Value >= 0 && Value < 4096;
981   }
982   bool isImm0_4095Neg() const {
983     if (!isImm()) return false;
984     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
985     if (!CE) return false;
986     int64_t Value = -CE->getValue();
987     return Value > 0 && Value < 4096;
988   }
989   bool isImm0_1() const {
990     if (!isImm()) return false;
991     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
992     if (!CE) return false;
993     int64_t Value = CE->getValue();
994     return Value >= 0 && Value < 2;
995   }
996   bool isImm0_3() const {
997     if (!isImm()) return false;
998     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
999     if (!CE) return false;
1000     int64_t Value = CE->getValue();
1001     return Value >= 0 && Value < 4;
1002   }
1003   bool isImm0_7() const {
1004     if (!isImm()) return false;
1005     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1006     if (!CE) return false;
1007     int64_t Value = CE->getValue();
1008     return Value >= 0 && Value < 8;
1009   }
1010   bool isImm0_15() const {
1011     if (!isImm()) return false;
1012     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1013     if (!CE) return false;
1014     int64_t Value = CE->getValue();
1015     return Value >= 0 && Value < 16;
1016   }
1017   bool isImm0_31() const {
1018     if (!isImm()) return false;
1019     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1020     if (!CE) return false;
1021     int64_t Value = CE->getValue();
1022     return Value >= 0 && Value < 32;
1023   }
1024   bool isImm0_63() const {
1025     if (!isImm()) return false;
1026     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1027     if (!CE) return false;
1028     int64_t Value = CE->getValue();
1029     return Value >= 0 && Value < 64;
1030   }
1031   bool isImm8() const {
1032     if (!isImm()) return false;
1033     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1034     if (!CE) return false;
1035     int64_t Value = CE->getValue();
1036     return Value == 8;
1037   }
1038   bool isImm16() const {
1039     if (!isImm()) return false;
1040     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1041     if (!CE) return false;
1042     int64_t Value = CE->getValue();
1043     return Value == 16;
1044   }
1045   bool isImm32() const {
1046     if (!isImm()) return false;
1047     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1048     if (!CE) return false;
1049     int64_t Value = CE->getValue();
1050     return Value == 32;
1051   }
1052   bool isShrImm8() const {
1053     if (!isImm()) return false;
1054     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1055     if (!CE) return false;
1056     int64_t Value = CE->getValue();
1057     return Value > 0 && Value <= 8;
1058   }
1059   bool isShrImm16() const {
1060     if (!isImm()) return false;
1061     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1062     if (!CE) return false;
1063     int64_t Value = CE->getValue();
1064     return Value > 0 && Value <= 16;
1065   }
1066   bool isShrImm32() const {
1067     if (!isImm()) return false;
1068     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1069     if (!CE) return false;
1070     int64_t Value = CE->getValue();
1071     return Value > 0 && Value <= 32;
1072   }
1073   bool isShrImm64() const {
1074     if (!isImm()) return false;
1075     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1076     if (!CE) return false;
1077     int64_t Value = CE->getValue();
1078     return Value > 0 && Value <= 64;
1079   }
1080   bool isImm1_7() const {
1081     if (!isImm()) return false;
1082     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1083     if (!CE) return false;
1084     int64_t Value = CE->getValue();
1085     return Value > 0 && Value < 8;
1086   }
1087   bool isImm1_15() const {
1088     if (!isImm()) return false;
1089     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1090     if (!CE) return false;
1091     int64_t Value = CE->getValue();
1092     return Value > 0 && Value < 16;
1093   }
1094   bool isImm1_31() const {
1095     if (!isImm()) return false;
1096     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1097     if (!CE) return false;
1098     int64_t Value = CE->getValue();
1099     return Value > 0 && Value < 32;
1100   }
1101   bool isImm1_16() 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 Value > 0 && Value < 17;
1107   }
1108   bool isImm1_32() const {
1109     if (!isImm()) return false;
1110     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1111     if (!CE) return false;
1112     int64_t Value = CE->getValue();
1113     return Value > 0 && Value < 33;
1114   }
1115   bool isImm0_32() const {
1116     if (!isImm()) return false;
1117     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1118     if (!CE) return false;
1119     int64_t Value = CE->getValue();
1120     return Value >= 0 && Value < 33;
1121   }
1122   bool isImm0_65535() const {
1123     if (!isImm()) return false;
1124     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1125     if (!CE) return false;
1126     int64_t Value = CE->getValue();
1127     return Value >= 0 && Value < 65536;
1128   }
1129   bool isImm256_65535Expr() const {
1130     if (!isImm()) return false;
1131     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1132     // If it's not a constant expression, it'll generate a fixup and be
1133     // handled later.
1134     if (!CE) return true;
1135     int64_t Value = CE->getValue();
1136     return Value >= 256 && Value < 65536;
1137   }
1138   bool isImm0_65535Expr() const {
1139     if (!isImm()) return false;
1140     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1141     // If it's not a constant expression, it'll generate a fixup and be
1142     // handled later.
1143     if (!CE) return true;
1144     int64_t Value = CE->getValue();
1145     return Value >= 0 && Value < 65536;
1146   }
1147   bool isImm24bit() const {
1148     if (!isImm()) return false;
1149     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1150     if (!CE) return false;
1151     int64_t Value = CE->getValue();
1152     return Value >= 0 && Value <= 0xffffff;
1153   }
1154   bool isImmThumbSR() const {
1155     if (!isImm()) return false;
1156     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1157     if (!CE) return false;
1158     int64_t Value = CE->getValue();
1159     return Value > 0 && Value < 33;
1160   }
1161   bool isPKHLSLImm() const {
1162     if (!isImm()) return false;
1163     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1164     if (!CE) return false;
1165     int64_t Value = CE->getValue();
1166     return Value >= 0 && Value < 32;
1167   }
1168   bool isPKHASRImm() const {
1169     if (!isImm()) return false;
1170     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1171     if (!CE) return false;
1172     int64_t Value = CE->getValue();
1173     return Value > 0 && Value <= 32;
1174   }
1175   bool isAdrLabel() const {
1176     // If we have an immediate that's not a constant, treat it as a label
1177     // reference needing a fixup.
1178     if (isImm() && !isa<MCConstantExpr>(getImm()))
1179       return true;
1180 
1181     // If it is a constant, it must fit into a modified immediate encoding.
1182     if (!isImm()) return false;
1183     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1184     if (!CE) return false;
1185     int64_t Value = CE->getValue();
1186     return (ARM_AM::getSOImmVal(Value) != -1 ||
1187             ARM_AM::getSOImmVal(-Value) != -1);
1188   }
1189   bool isT2SOImm() const {
1190     if (!isImm()) return false;
1191     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1192     if (!CE) return false;
1193     int64_t Value = CE->getValue();
1194     return ARM_AM::getT2SOImmVal(Value) != -1;
1195   }
1196   bool isT2SOImmNot() const {
1197     if (!isImm()) return false;
1198     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1199     if (!CE) return false;
1200     int64_t Value = CE->getValue();
1201     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1202       ARM_AM::getT2SOImmVal(~Value) != -1;
1203   }
1204   bool isT2SOImmNeg() const {
1205     if (!isImm()) return false;
1206     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1207     if (!CE) return false;
1208     int64_t Value = CE->getValue();
1209     // Only use this when not representable as a plain so_imm.
1210     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1211       ARM_AM::getT2SOImmVal(-Value) != -1;
1212   }
1213   bool isSetEndImm() const {
1214     if (!isImm()) return false;
1215     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1216     if (!CE) return false;
1217     int64_t Value = CE->getValue();
1218     return Value == 1 || Value == 0;
1219   }
1220   bool isReg() const override { return Kind == k_Register; }
1221   bool isRegList() const { return Kind == k_RegisterList; }
1222   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
1223   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
1224   bool isToken() const override { return Kind == k_Token; }
1225   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
1226   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
1227   bool isMem() const override { return Kind == k_Memory; }
1228   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
1229   bool isRegShiftedReg() const { return Kind == k_ShiftedRegister; }
1230   bool isRegShiftedImm() const { return Kind == k_ShiftedImmediate; }
1231   bool isRotImm() const { return Kind == k_RotateImmediate; }
1232   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1233   bool isModImmNot() const {
1234     if (!isImm()) return false;
1235     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1236     if (!CE) return false;
1237     int64_t Value = CE->getValue();
1238     return ARM_AM::getSOImmVal(~Value) != -1;
1239   }
1240   bool isModImmNeg() const {
1241     if (!isImm()) return false;
1242     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1243     if (!CE) return false;
1244     int64_t Value = CE->getValue();
1245     return ARM_AM::getSOImmVal(Value) == -1 &&
1246       ARM_AM::getSOImmVal(-Value) != -1;
1247   }
1248   bool isConstantPoolImm() const { return Kind == k_ConstantPoolImmediate; }
1249   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
1250   bool isPostIdxRegShifted() const { return Kind == k_PostIndexRegister; }
1251   bool isPostIdxReg() const {
1252     return Kind == k_PostIndexRegister && PostIdxReg.ShiftTy ==ARM_AM::no_shift;
1253   }
1254   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1255     if (!isMem())
1256       return false;
1257     // No offset of any kind.
1258     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1259      (alignOK || Memory.Alignment == Alignment);
1260   }
1261   bool isMemPCRelImm12() const {
1262     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1263       return false;
1264     // Base register must be PC.
1265     if (Memory.BaseRegNum != ARM::PC)
1266       return false;
1267     // Immediate offset in range [-4095, 4095].
1268     if (!Memory.OffsetImm) return true;
1269     int64_t Val = Memory.OffsetImm->getValue();
1270     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
1271   }
1272   bool isAlignedMemory() const {
1273     return isMemNoOffset(true);
1274   }
1275   bool isAlignedMemoryNone() const {
1276     return isMemNoOffset(false, 0);
1277   }
1278   bool isDupAlignedMemoryNone() const {
1279     return isMemNoOffset(false, 0);
1280   }
1281   bool isAlignedMemory16() const {
1282     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1283       return true;
1284     return isMemNoOffset(false, 0);
1285   }
1286   bool isDupAlignedMemory16() const {
1287     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1288       return true;
1289     return isMemNoOffset(false, 0);
1290   }
1291   bool isAlignedMemory32() const {
1292     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1293       return true;
1294     return isMemNoOffset(false, 0);
1295   }
1296   bool isDupAlignedMemory32() const {
1297     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1298       return true;
1299     return isMemNoOffset(false, 0);
1300   }
1301   bool isAlignedMemory64() const {
1302     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1303       return true;
1304     return isMemNoOffset(false, 0);
1305   }
1306   bool isDupAlignedMemory64() const {
1307     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1308       return true;
1309     return isMemNoOffset(false, 0);
1310   }
1311   bool isAlignedMemory64or128() const {
1312     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1313       return true;
1314     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1315       return true;
1316     return isMemNoOffset(false, 0);
1317   }
1318   bool isDupAlignedMemory64or128() const {
1319     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1320       return true;
1321     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1322       return true;
1323     return isMemNoOffset(false, 0);
1324   }
1325   bool isAlignedMemory64or128or256() const {
1326     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1327       return true;
1328     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1329       return true;
1330     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1331       return true;
1332     return isMemNoOffset(false, 0);
1333   }
1334   bool isAddrMode2() const {
1335     if (!isMem() || Memory.Alignment != 0) return false;
1336     // Check for register offset.
1337     if (Memory.OffsetRegNum) return true;
1338     // Immediate offset in range [-4095, 4095].
1339     if (!Memory.OffsetImm) return true;
1340     int64_t Val = Memory.OffsetImm->getValue();
1341     return Val > -4096 && Val < 4096;
1342   }
1343   bool isAM2OffsetImm() const {
1344     if (!isImm()) return false;
1345     // Immediate offset in range [-4095, 4095].
1346     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1347     if (!CE) return false;
1348     int64_t Val = CE->getValue();
1349     return (Val == INT32_MIN) || (Val > -4096 && Val < 4096);
1350   }
1351   bool isAddrMode3() const {
1352     // If we have an immediate that's not a constant, treat it as a label
1353     // reference needing a fixup. If it is a constant, it's something else
1354     // and we reject it.
1355     if (isImm() && !isa<MCConstantExpr>(getImm()))
1356       return true;
1357     if (!isMem() || Memory.Alignment != 0) return false;
1358     // No shifts are legal for AM3.
1359     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1360     // Check for register offset.
1361     if (Memory.OffsetRegNum) return true;
1362     // Immediate offset in range [-255, 255].
1363     if (!Memory.OffsetImm) return true;
1364     int64_t Val = Memory.OffsetImm->getValue();
1365     // The #-0 offset is encoded as INT32_MIN, and we have to check
1366     // for this too.
1367     return (Val > -256 && Val < 256) || Val == INT32_MIN;
1368   }
1369   bool isAM3Offset() const {
1370     if (Kind != k_Immediate && Kind != k_PostIndexRegister)
1371       return false;
1372     if (Kind == k_PostIndexRegister)
1373       return PostIdxReg.ShiftTy == ARM_AM::no_shift;
1374     // Immediate offset in range [-255, 255].
1375     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1376     if (!CE) return false;
1377     int64_t Val = CE->getValue();
1378     // Special case, #-0 is INT32_MIN.
1379     return (Val > -256 && Val < 256) || Val == INT32_MIN;
1380   }
1381   bool isAddrMode5() const {
1382     // If we have an immediate that's not a constant, treat it as a label
1383     // reference needing a fixup. If it is a constant, it's something else
1384     // and we reject it.
1385     if (isImm() && !isa<MCConstantExpr>(getImm()))
1386       return true;
1387     if (!isMem() || Memory.Alignment != 0) return false;
1388     // Check for register offset.
1389     if (Memory.OffsetRegNum) return false;
1390     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1391     if (!Memory.OffsetImm) return true;
1392     int64_t Val = Memory.OffsetImm->getValue();
1393     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1394       Val == INT32_MIN;
1395   }
1396   bool isAddrMode5FP16() const {
1397     // If we have an immediate that's not a constant, treat it as a label
1398     // reference needing a fixup. If it is a constant, it's something else
1399     // and we reject it.
1400     if (isImm() && !isa<MCConstantExpr>(getImm()))
1401       return true;
1402     if (!isMem() || Memory.Alignment != 0) return false;
1403     // Check for register offset.
1404     if (Memory.OffsetRegNum) return false;
1405     // Immediate offset in range [-510, 510] and a multiple of 2.
1406     if (!Memory.OffsetImm) return true;
1407     int64_t Val = Memory.OffsetImm->getValue();
1408     return (Val >= -510 && Val <= 510 && ((Val & 1) == 0)) || Val == INT32_MIN;
1409   }
1410   bool isMemTBB() const {
1411     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1412         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1413       return false;
1414     return true;
1415   }
1416   bool isMemTBH() const {
1417     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1418         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1419         Memory.Alignment != 0 )
1420       return false;
1421     return true;
1422   }
1423   bool isMemRegOffset() const {
1424     if (!isMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1425       return false;
1426     return true;
1427   }
1428   bool isT2MemRegOffset() const {
1429     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1430         Memory.Alignment != 0 || Memory.BaseRegNum == ARM::PC)
1431       return false;
1432     // Only lsl #{0, 1, 2, 3} allowed.
1433     if (Memory.ShiftType == ARM_AM::no_shift)
1434       return true;
1435     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1436       return false;
1437     return true;
1438   }
1439   bool isMemThumbRR() const {
1440     // Thumb reg+reg addressing is simple. Just two registers, a base and
1441     // an offset. No shifts, negations or any other complicating factors.
1442     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1443         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1444       return false;
1445     return isARMLowRegister(Memory.BaseRegNum) &&
1446       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1447   }
1448   bool isMemThumbRIs4() const {
1449     if (!isMem() || Memory.OffsetRegNum != 0 ||
1450         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1451       return false;
1452     // Immediate offset, multiple of 4 in range [0, 124].
1453     if (!Memory.OffsetImm) return true;
1454     int64_t Val = Memory.OffsetImm->getValue();
1455     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1456   }
1457   bool isMemThumbRIs2() const {
1458     if (!isMem() || Memory.OffsetRegNum != 0 ||
1459         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1460       return false;
1461     // Immediate offset, multiple of 4 in range [0, 62].
1462     if (!Memory.OffsetImm) return true;
1463     int64_t Val = Memory.OffsetImm->getValue();
1464     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1465   }
1466   bool isMemThumbRIs1() const {
1467     if (!isMem() || Memory.OffsetRegNum != 0 ||
1468         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1469       return false;
1470     // Immediate offset in range [0, 31].
1471     if (!Memory.OffsetImm) return true;
1472     int64_t Val = Memory.OffsetImm->getValue();
1473     return Val >= 0 && Val <= 31;
1474   }
1475   bool isMemThumbSPI() const {
1476     if (!isMem() || Memory.OffsetRegNum != 0 ||
1477         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1478       return false;
1479     // Immediate offset, multiple of 4 in range [0, 1020].
1480     if (!Memory.OffsetImm) return true;
1481     int64_t Val = Memory.OffsetImm->getValue();
1482     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1483   }
1484   bool isMemImm8s4Offset() const {
1485     // If we have an immediate that's not a constant, treat it as a label
1486     // reference needing a fixup. If it is a constant, it's something else
1487     // and we reject it.
1488     if (isImm() && !isa<MCConstantExpr>(getImm()))
1489       return true;
1490     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1491       return false;
1492     // Immediate offset a multiple of 4 in range [-1020, 1020].
1493     if (!Memory.OffsetImm) return true;
1494     int64_t Val = Memory.OffsetImm->getValue();
1495     // Special case, #-0 is INT32_MIN.
1496     return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) || Val == INT32_MIN;
1497   }
1498   bool isMemImm0_1020s4Offset() const {
1499     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1500       return false;
1501     // Immediate offset a multiple of 4 in range [0, 1020].
1502     if (!Memory.OffsetImm) return true;
1503     int64_t Val = Memory.OffsetImm->getValue();
1504     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1505   }
1506   bool isMemImm8Offset() const {
1507     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1508       return false;
1509     // Base reg of PC isn't allowed for these encodings.
1510     if (Memory.BaseRegNum == ARM::PC) return false;
1511     // Immediate offset in range [-255, 255].
1512     if (!Memory.OffsetImm) return true;
1513     int64_t Val = Memory.OffsetImm->getValue();
1514     return (Val == INT32_MIN) || (Val > -256 && Val < 256);
1515   }
1516   bool isMemPosImm8Offset() const {
1517     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1518       return false;
1519     // Immediate offset in range [0, 255].
1520     if (!Memory.OffsetImm) return true;
1521     int64_t Val = Memory.OffsetImm->getValue();
1522     return Val >= 0 && Val < 256;
1523   }
1524   bool isMemNegImm8Offset() const {
1525     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1526       return false;
1527     // Base reg of PC isn't allowed for these encodings.
1528     if (Memory.BaseRegNum == ARM::PC) return false;
1529     // Immediate offset in range [-255, -1].
1530     if (!Memory.OffsetImm) return false;
1531     int64_t Val = Memory.OffsetImm->getValue();
1532     return (Val == INT32_MIN) || (Val > -256 && Val < 0);
1533   }
1534   bool isMemUImm12Offset() const {
1535     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1536       return false;
1537     // Immediate offset in range [0, 4095].
1538     if (!Memory.OffsetImm) return true;
1539     int64_t Val = Memory.OffsetImm->getValue();
1540     return (Val >= 0 && Val < 4096);
1541   }
1542   bool isMemImm12Offset() const {
1543     // If we have an immediate that's not a constant, treat it as a label
1544     // reference needing a fixup. If it is a constant, it's something else
1545     // and we reject it.
1546 
1547     if (isImm() && !isa<MCConstantExpr>(getImm()))
1548       return true;
1549 
1550     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1551       return false;
1552     // Immediate offset in range [-4095, 4095].
1553     if (!Memory.OffsetImm) return true;
1554     int64_t Val = Memory.OffsetImm->getValue();
1555     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
1556   }
1557   bool isConstPoolAsmImm() const {
1558     // Delay processing of Constant Pool Immediate, this will turn into
1559     // a constant. Match no other operand
1560     return (isConstantPoolImm());
1561   }
1562   bool isPostIdxImm8() const {
1563     if (!isImm()) return false;
1564     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1565     if (!CE) return false;
1566     int64_t Val = CE->getValue();
1567     return (Val > -256 && Val < 256) || (Val == INT32_MIN);
1568   }
1569   bool isPostIdxImm8s4() const {
1570     if (!isImm()) return false;
1571     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1572     if (!CE) return false;
1573     int64_t Val = CE->getValue();
1574     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
1575       (Val == INT32_MIN);
1576   }
1577 
1578   bool isMSRMask() const { return Kind == k_MSRMask; }
1579   bool isBankedReg() const { return Kind == k_BankedReg; }
1580   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
1581 
1582   // NEON operands.
1583   bool isSingleSpacedVectorList() const {
1584     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
1585   }
1586   bool isDoubleSpacedVectorList() const {
1587     return Kind == k_VectorList && VectorList.isDoubleSpaced;
1588   }
1589   bool isVecListOneD() const {
1590     if (!isSingleSpacedVectorList()) return false;
1591     return VectorList.Count == 1;
1592   }
1593 
1594   bool isVecListDPair() const {
1595     if (!isSingleSpacedVectorList()) return false;
1596     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1597               .contains(VectorList.RegNum));
1598   }
1599 
1600   bool isVecListThreeD() const {
1601     if (!isSingleSpacedVectorList()) return false;
1602     return VectorList.Count == 3;
1603   }
1604 
1605   bool isVecListFourD() const {
1606     if (!isSingleSpacedVectorList()) return false;
1607     return VectorList.Count == 4;
1608   }
1609 
1610   bool isVecListDPairSpaced() const {
1611     if (Kind != k_VectorList) return false;
1612     if (isSingleSpacedVectorList()) return false;
1613     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
1614               .contains(VectorList.RegNum));
1615   }
1616 
1617   bool isVecListThreeQ() const {
1618     if (!isDoubleSpacedVectorList()) return false;
1619     return VectorList.Count == 3;
1620   }
1621 
1622   bool isVecListFourQ() const {
1623     if (!isDoubleSpacedVectorList()) return false;
1624     return VectorList.Count == 4;
1625   }
1626 
1627   bool isSingleSpacedVectorAllLanes() const {
1628     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
1629   }
1630   bool isDoubleSpacedVectorAllLanes() const {
1631     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
1632   }
1633   bool isVecListOneDAllLanes() const {
1634     if (!isSingleSpacedVectorAllLanes()) return false;
1635     return VectorList.Count == 1;
1636   }
1637 
1638   bool isVecListDPairAllLanes() const {
1639     if (!isSingleSpacedVectorAllLanes()) return false;
1640     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1641               .contains(VectorList.RegNum));
1642   }
1643 
1644   bool isVecListDPairSpacedAllLanes() const {
1645     if (!isDoubleSpacedVectorAllLanes()) return false;
1646     return VectorList.Count == 2;
1647   }
1648 
1649   bool isVecListThreeDAllLanes() const {
1650     if (!isSingleSpacedVectorAllLanes()) return false;
1651     return VectorList.Count == 3;
1652   }
1653 
1654   bool isVecListThreeQAllLanes() const {
1655     if (!isDoubleSpacedVectorAllLanes()) return false;
1656     return VectorList.Count == 3;
1657   }
1658 
1659   bool isVecListFourDAllLanes() const {
1660     if (!isSingleSpacedVectorAllLanes()) return false;
1661     return VectorList.Count == 4;
1662   }
1663 
1664   bool isVecListFourQAllLanes() const {
1665     if (!isDoubleSpacedVectorAllLanes()) return false;
1666     return VectorList.Count == 4;
1667   }
1668 
1669   bool isSingleSpacedVectorIndexed() const {
1670     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
1671   }
1672   bool isDoubleSpacedVectorIndexed() const {
1673     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
1674   }
1675   bool isVecListOneDByteIndexed() const {
1676     if (!isSingleSpacedVectorIndexed()) return false;
1677     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
1678   }
1679 
1680   bool isVecListOneDHWordIndexed() const {
1681     if (!isSingleSpacedVectorIndexed()) return false;
1682     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
1683   }
1684 
1685   bool isVecListOneDWordIndexed() const {
1686     if (!isSingleSpacedVectorIndexed()) return false;
1687     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
1688   }
1689 
1690   bool isVecListTwoDByteIndexed() const {
1691     if (!isSingleSpacedVectorIndexed()) return false;
1692     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
1693   }
1694 
1695   bool isVecListTwoDHWordIndexed() const {
1696     if (!isSingleSpacedVectorIndexed()) return false;
1697     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1698   }
1699 
1700   bool isVecListTwoQWordIndexed() const {
1701     if (!isDoubleSpacedVectorIndexed()) return false;
1702     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1703   }
1704 
1705   bool isVecListTwoQHWordIndexed() const {
1706     if (!isDoubleSpacedVectorIndexed()) return false;
1707     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1708   }
1709 
1710   bool isVecListTwoDWordIndexed() const {
1711     if (!isSingleSpacedVectorIndexed()) return false;
1712     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1713   }
1714 
1715   bool isVecListThreeDByteIndexed() const {
1716     if (!isSingleSpacedVectorIndexed()) return false;
1717     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
1718   }
1719 
1720   bool isVecListThreeDHWordIndexed() const {
1721     if (!isSingleSpacedVectorIndexed()) return false;
1722     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1723   }
1724 
1725   bool isVecListThreeQWordIndexed() const {
1726     if (!isDoubleSpacedVectorIndexed()) return false;
1727     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1728   }
1729 
1730   bool isVecListThreeQHWordIndexed() const {
1731     if (!isDoubleSpacedVectorIndexed()) return false;
1732     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1733   }
1734 
1735   bool isVecListThreeDWordIndexed() const {
1736     if (!isSingleSpacedVectorIndexed()) return false;
1737     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1738   }
1739 
1740   bool isVecListFourDByteIndexed() const {
1741     if (!isSingleSpacedVectorIndexed()) return false;
1742     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
1743   }
1744 
1745   bool isVecListFourDHWordIndexed() const {
1746     if (!isSingleSpacedVectorIndexed()) return false;
1747     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1748   }
1749 
1750   bool isVecListFourQWordIndexed() const {
1751     if (!isDoubleSpacedVectorIndexed()) return false;
1752     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1753   }
1754 
1755   bool isVecListFourQHWordIndexed() const {
1756     if (!isDoubleSpacedVectorIndexed()) return false;
1757     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1758   }
1759 
1760   bool isVecListFourDWordIndexed() const {
1761     if (!isSingleSpacedVectorIndexed()) return false;
1762     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1763   }
1764 
1765   bool isVectorIndex8() const {
1766     if (Kind != k_VectorIndex) return false;
1767     return VectorIndex.Val < 8;
1768   }
1769   bool isVectorIndex16() const {
1770     if (Kind != k_VectorIndex) return false;
1771     return VectorIndex.Val < 4;
1772   }
1773   bool isVectorIndex32() const {
1774     if (Kind != k_VectorIndex) return false;
1775     return VectorIndex.Val < 2;
1776   }
1777 
1778   bool isNEONi8splat() const {
1779     if (!isImm()) return false;
1780     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1781     // Must be a constant.
1782     if (!CE) return false;
1783     int64_t Value = CE->getValue();
1784     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
1785     // value.
1786     return Value >= 0 && Value < 256;
1787   }
1788 
1789   bool isNEONi16splat() const {
1790     if (isNEONByteReplicate(2))
1791       return false; // Leave that for bytes replication and forbid by default.
1792     if (!isImm())
1793       return false;
1794     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1795     // Must be a constant.
1796     if (!CE) return false;
1797     unsigned Value = CE->getValue();
1798     return ARM_AM::isNEONi16splat(Value);
1799   }
1800 
1801   bool isNEONi16splatNot() const {
1802     if (!isImm())
1803       return false;
1804     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1805     // Must be a constant.
1806     if (!CE) return false;
1807     unsigned Value = CE->getValue();
1808     return ARM_AM::isNEONi16splat(~Value & 0xffff);
1809   }
1810 
1811   bool isNEONi32splat() const {
1812     if (isNEONByteReplicate(4))
1813       return false; // Leave that for bytes replication and forbid by default.
1814     if (!isImm())
1815       return false;
1816     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1817     // Must be a constant.
1818     if (!CE) return false;
1819     unsigned Value = CE->getValue();
1820     return ARM_AM::isNEONi32splat(Value);
1821   }
1822 
1823   bool isNEONi32splatNot() const {
1824     if (!isImm())
1825       return false;
1826     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1827     // Must be a constant.
1828     if (!CE) return false;
1829     unsigned Value = CE->getValue();
1830     return ARM_AM::isNEONi32splat(~Value);
1831   }
1832 
1833   bool isNEONByteReplicate(unsigned NumBytes) const {
1834     if (!isImm())
1835       return false;
1836     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1837     // Must be a constant.
1838     if (!CE)
1839       return false;
1840     int64_t Value = CE->getValue();
1841     if (!Value)
1842       return false; // Don't bother with zero.
1843 
1844     unsigned char B = Value & 0xff;
1845     for (unsigned i = 1; i < NumBytes; ++i) {
1846       Value >>= 8;
1847       if ((Value & 0xff) != B)
1848         return false;
1849     }
1850     return true;
1851   }
1852   bool isNEONi16ByteReplicate() const { return isNEONByteReplicate(2); }
1853   bool isNEONi32ByteReplicate() const { return isNEONByteReplicate(4); }
1854   bool isNEONi32vmov() const {
1855     if (isNEONByteReplicate(4))
1856       return false; // Let it to be classified as byte-replicate case.
1857     if (!isImm())
1858       return false;
1859     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1860     // Must be a constant.
1861     if (!CE)
1862       return false;
1863     int64_t Value = CE->getValue();
1864     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1865     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1866     // FIXME: This is probably wrong and a copy and paste from previous example
1867     return (Value >= 0 && Value < 256) ||
1868       (Value >= 0x0100 && Value <= 0xff00) ||
1869       (Value >= 0x010000 && Value <= 0xff0000) ||
1870       (Value >= 0x01000000 && Value <= 0xff000000) ||
1871       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1872       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1873   }
1874   bool isNEONi32vmovNeg() const {
1875     if (!isImm()) return false;
1876     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1877     // Must be a constant.
1878     if (!CE) return false;
1879     int64_t Value = ~CE->getValue();
1880     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1881     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1882     // FIXME: This is probably wrong and a copy and paste from previous example
1883     return (Value >= 0 && Value < 256) ||
1884       (Value >= 0x0100 && Value <= 0xff00) ||
1885       (Value >= 0x010000 && Value <= 0xff0000) ||
1886       (Value >= 0x01000000 && Value <= 0xff000000) ||
1887       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1888       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1889   }
1890 
1891   bool isNEONi64splat() const {
1892     if (!isImm()) return false;
1893     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1894     // Must be a constant.
1895     if (!CE) return false;
1896     uint64_t Value = CE->getValue();
1897     // i64 value with each byte being either 0 or 0xff.
1898     for (unsigned i = 0; i < 8; ++i, Value >>= 8)
1899       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
1900     return true;
1901   }
1902 
1903   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
1904     // Add as immediates when possible.  Null MCExpr = 0.
1905     if (!Expr)
1906       Inst.addOperand(MCOperand::createImm(0));
1907     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
1908       Inst.addOperand(MCOperand::createImm(CE->getValue()));
1909     else
1910       Inst.addOperand(MCOperand::createExpr(Expr));
1911   }
1912 
1913   void addARMBranchTargetOperands(MCInst &Inst, unsigned N) const {
1914     assert(N == 1 && "Invalid number of operands!");
1915     addExpr(Inst, getImm());
1916   }
1917 
1918   void addThumbBranchTargetOperands(MCInst &Inst, unsigned N) const {
1919     assert(N == 1 && "Invalid number of operands!");
1920     addExpr(Inst, getImm());
1921   }
1922 
1923   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
1924     assert(N == 2 && "Invalid number of operands!");
1925     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1926     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
1927     Inst.addOperand(MCOperand::createReg(RegNum));
1928   }
1929 
1930   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
1931     assert(N == 1 && "Invalid number of operands!");
1932     Inst.addOperand(MCOperand::createImm(getCoproc()));
1933   }
1934 
1935   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
1936     assert(N == 1 && "Invalid number of operands!");
1937     Inst.addOperand(MCOperand::createImm(getCoproc()));
1938   }
1939 
1940   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
1941     assert(N == 1 && "Invalid number of operands!");
1942     Inst.addOperand(MCOperand::createImm(CoprocOption.Val));
1943   }
1944 
1945   void addITMaskOperands(MCInst &Inst, unsigned N) const {
1946     assert(N == 1 && "Invalid number of operands!");
1947     Inst.addOperand(MCOperand::createImm(ITMask.Mask));
1948   }
1949 
1950   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
1951     assert(N == 1 && "Invalid number of operands!");
1952     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1953   }
1954 
1955   void addCCOutOperands(MCInst &Inst, unsigned N) const {
1956     assert(N == 1 && "Invalid number of operands!");
1957     Inst.addOperand(MCOperand::createReg(getReg()));
1958   }
1959 
1960   void addRegOperands(MCInst &Inst, unsigned N) const {
1961     assert(N == 1 && "Invalid number of operands!");
1962     Inst.addOperand(MCOperand::createReg(getReg()));
1963   }
1964 
1965   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
1966     assert(N == 3 && "Invalid number of operands!");
1967     assert(isRegShiftedReg() &&
1968            "addRegShiftedRegOperands() on non-RegShiftedReg!");
1969     Inst.addOperand(MCOperand::createReg(RegShiftedReg.SrcReg));
1970     Inst.addOperand(MCOperand::createReg(RegShiftedReg.ShiftReg));
1971     Inst.addOperand(MCOperand::createImm(
1972       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
1973   }
1974 
1975   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
1976     assert(N == 2 && "Invalid number of operands!");
1977     assert(isRegShiftedImm() &&
1978            "addRegShiftedImmOperands() on non-RegShiftedImm!");
1979     Inst.addOperand(MCOperand::createReg(RegShiftedImm.SrcReg));
1980     // Shift of #32 is encoded as 0 where permitted
1981     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
1982     Inst.addOperand(MCOperand::createImm(
1983       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
1984   }
1985 
1986   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
1987     assert(N == 1 && "Invalid number of operands!");
1988     Inst.addOperand(MCOperand::createImm((ShifterImm.isASR << 5) |
1989                                          ShifterImm.Imm));
1990   }
1991 
1992   void addRegListOperands(MCInst &Inst, unsigned N) const {
1993     assert(N == 1 && "Invalid number of operands!");
1994     const SmallVectorImpl<unsigned> &RegList = getRegList();
1995     for (SmallVectorImpl<unsigned>::const_iterator
1996            I = RegList.begin(), E = RegList.end(); I != E; ++I)
1997       Inst.addOperand(MCOperand::createReg(*I));
1998   }
1999 
2000   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
2001     addRegListOperands(Inst, N);
2002   }
2003 
2004   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
2005     addRegListOperands(Inst, N);
2006   }
2007 
2008   void addRotImmOperands(MCInst &Inst, unsigned N) const {
2009     assert(N == 1 && "Invalid number of operands!");
2010     // Encoded as val>>3. The printer handles display as 8, 16, 24.
2011     Inst.addOperand(MCOperand::createImm(RotImm.Imm >> 3));
2012   }
2013 
2014   void addModImmOperands(MCInst &Inst, unsigned N) const {
2015     assert(N == 1 && "Invalid number of operands!");
2016 
2017     // Support for fixups (MCFixup)
2018     if (isImm())
2019       return addImmOperands(Inst, N);
2020 
2021     Inst.addOperand(MCOperand::createImm(ModImm.Bits | (ModImm.Rot << 7)));
2022   }
2023 
2024   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
2025     assert(N == 1 && "Invalid number of operands!");
2026     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2027     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
2028     Inst.addOperand(MCOperand::createImm(Enc));
2029   }
2030 
2031   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
2032     assert(N == 1 && "Invalid number of operands!");
2033     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2034     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
2035     Inst.addOperand(MCOperand::createImm(Enc));
2036   }
2037 
2038   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
2039     assert(N == 1 && "Invalid number of operands!");
2040     // Munge the lsb/width into a bitfield mask.
2041     unsigned lsb = Bitfield.LSB;
2042     unsigned width = Bitfield.Width;
2043     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
2044     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
2045                       (32 - (lsb + width)));
2046     Inst.addOperand(MCOperand::createImm(Mask));
2047   }
2048 
2049   void addImmOperands(MCInst &Inst, unsigned N) const {
2050     assert(N == 1 && "Invalid number of operands!");
2051     addExpr(Inst, getImm());
2052   }
2053 
2054   void addFBits16Operands(MCInst &Inst, unsigned N) const {
2055     assert(N == 1 && "Invalid number of operands!");
2056     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2057     Inst.addOperand(MCOperand::createImm(16 - CE->getValue()));
2058   }
2059 
2060   void addFBits32Operands(MCInst &Inst, unsigned N) const {
2061     assert(N == 1 && "Invalid number of operands!");
2062     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2063     Inst.addOperand(MCOperand::createImm(32 - CE->getValue()));
2064   }
2065 
2066   void addFPImmOperands(MCInst &Inst, unsigned N) const {
2067     assert(N == 1 && "Invalid number of operands!");
2068     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2069     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
2070     Inst.addOperand(MCOperand::createImm(Val));
2071   }
2072 
2073   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
2074     assert(N == 1 && "Invalid number of operands!");
2075     // FIXME: We really want to scale the value here, but the LDRD/STRD
2076     // instruction don't encode operands that way yet.
2077     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2078     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2079   }
2080 
2081   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
2082     assert(N == 1 && "Invalid number of operands!");
2083     // The immediate is scaled by four in the encoding and is stored
2084     // in the MCInst as such. Lop off the low two bits here.
2085     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2086     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2087   }
2088 
2089   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
2090     assert(N == 1 && "Invalid number of operands!");
2091     // The immediate is scaled by four in the encoding and is stored
2092     // in the MCInst as such. Lop off the low two bits here.
2093     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2094     Inst.addOperand(MCOperand::createImm(-(CE->getValue() / 4)));
2095   }
2096 
2097   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
2098     assert(N == 1 && "Invalid number of operands!");
2099     // The immediate is scaled by four in the encoding and is stored
2100     // in the MCInst as such. Lop off the low two bits here.
2101     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2102     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2103   }
2104 
2105   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
2106     assert(N == 1 && "Invalid number of operands!");
2107     // The constant encodes as the immediate-1, and we store in the instruction
2108     // the bits as encoded, so subtract off one here.
2109     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2110     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2111   }
2112 
2113   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
2114     assert(N == 1 && "Invalid number of operands!");
2115     // The constant encodes as the immediate-1, and we store in the instruction
2116     // the bits as encoded, so subtract off one here.
2117     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2118     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2119   }
2120 
2121   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
2122     assert(N == 1 && "Invalid number of operands!");
2123     // The constant encodes as the immediate, except for 32, which encodes as
2124     // zero.
2125     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2126     unsigned Imm = CE->getValue();
2127     Inst.addOperand(MCOperand::createImm((Imm == 32 ? 0 : Imm)));
2128   }
2129 
2130   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
2131     assert(N == 1 && "Invalid number of operands!");
2132     // An ASR value of 32 encodes as 0, so that's how we want to add it to
2133     // the instruction as well.
2134     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2135     int Val = CE->getValue();
2136     Inst.addOperand(MCOperand::createImm(Val == 32 ? 0 : Val));
2137   }
2138 
2139   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
2140     assert(N == 1 && "Invalid number of operands!");
2141     // The operand is actually a t2_so_imm, but we have its bitwise
2142     // negation in the assembly source, so twiddle it here.
2143     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2144     Inst.addOperand(MCOperand::createImm(~CE->getValue()));
2145   }
2146 
2147   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
2148     assert(N == 1 && "Invalid number of operands!");
2149     // The operand is actually a t2_so_imm, but we have its
2150     // negation in the assembly source, so twiddle it here.
2151     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2152     Inst.addOperand(MCOperand::createImm(-CE->getValue()));
2153   }
2154 
2155   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
2156     assert(N == 1 && "Invalid number of operands!");
2157     // The operand is actually an imm0_4095, but we have its
2158     // negation in the assembly source, so twiddle it here.
2159     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2160     Inst.addOperand(MCOperand::createImm(-CE->getValue()));
2161   }
2162 
2163   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
2164     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
2165       Inst.addOperand(MCOperand::createImm(CE->getValue() >> 2));
2166       return;
2167     }
2168 
2169     const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2170     assert(SR && "Unknown value type!");
2171     Inst.addOperand(MCOperand::createExpr(SR));
2172   }
2173 
2174   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
2175     assert(N == 1 && "Invalid number of operands!");
2176     if (isImm()) {
2177       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2178       if (CE) {
2179         Inst.addOperand(MCOperand::createImm(CE->getValue()));
2180         return;
2181       }
2182 
2183       const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2184 
2185       assert(SR && "Unknown value type!");
2186       Inst.addOperand(MCOperand::createExpr(SR));
2187       return;
2188     }
2189 
2190     assert(isMem()  && "Unknown value type!");
2191     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
2192     Inst.addOperand(MCOperand::createImm(Memory.OffsetImm->getValue()));
2193   }
2194 
2195   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
2196     assert(N == 1 && "Invalid number of operands!");
2197     Inst.addOperand(MCOperand::createImm(unsigned(getMemBarrierOpt())));
2198   }
2199 
2200   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2201     assert(N == 1 && "Invalid number of operands!");
2202     Inst.addOperand(MCOperand::createImm(unsigned(getInstSyncBarrierOpt())));
2203   }
2204 
2205   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
2206     assert(N == 1 && "Invalid number of operands!");
2207     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2208   }
2209 
2210   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
2211     assert(N == 1 && "Invalid number of operands!");
2212     int32_t Imm = Memory.OffsetImm->getValue();
2213     Inst.addOperand(MCOperand::createImm(Imm));
2214   }
2215 
2216   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
2217     assert(N == 1 && "Invalid number of operands!");
2218     assert(isImm() && "Not an immediate!");
2219 
2220     // If we have an immediate that's not a constant, treat it as a label
2221     // reference needing a fixup.
2222     if (!isa<MCConstantExpr>(getImm())) {
2223       Inst.addOperand(MCOperand::createExpr(getImm()));
2224       return;
2225     }
2226 
2227     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2228     int Val = CE->getValue();
2229     Inst.addOperand(MCOperand::createImm(Val));
2230   }
2231 
2232   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
2233     assert(N == 2 && "Invalid number of operands!");
2234     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2235     Inst.addOperand(MCOperand::createImm(Memory.Alignment));
2236   }
2237 
2238   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2239     addAlignedMemoryOperands(Inst, N);
2240   }
2241 
2242   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2243     addAlignedMemoryOperands(Inst, N);
2244   }
2245 
2246   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2247     addAlignedMemoryOperands(Inst, N);
2248   }
2249 
2250   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2251     addAlignedMemoryOperands(Inst, N);
2252   }
2253 
2254   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2255     addAlignedMemoryOperands(Inst, N);
2256   }
2257 
2258   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2259     addAlignedMemoryOperands(Inst, N);
2260   }
2261 
2262   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2263     addAlignedMemoryOperands(Inst, N);
2264   }
2265 
2266   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2267     addAlignedMemoryOperands(Inst, N);
2268   }
2269 
2270   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2271     addAlignedMemoryOperands(Inst, N);
2272   }
2273 
2274   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2275     addAlignedMemoryOperands(Inst, N);
2276   }
2277 
2278   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2279     addAlignedMemoryOperands(Inst, N);
2280   }
2281 
2282   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2283     assert(N == 3 && "Invalid number of operands!");
2284     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2285     if (!Memory.OffsetRegNum) {
2286       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2287       // Special case for #-0
2288       if (Val == INT32_MIN) Val = 0;
2289       if (Val < 0) Val = -Val;
2290       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2291     } else {
2292       // For register offset, we encode the shift type and negation flag
2293       // here.
2294       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2295                               Memory.ShiftImm, Memory.ShiftType);
2296     }
2297     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2298     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2299     Inst.addOperand(MCOperand::createImm(Val));
2300   }
2301 
2302   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2303     assert(N == 2 && "Invalid number of operands!");
2304     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2305     assert(CE && "non-constant AM2OffsetImm operand!");
2306     int32_t Val = CE->getValue();
2307     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2308     // Special case for #-0
2309     if (Val == INT32_MIN) Val = 0;
2310     if (Val < 0) Val = -Val;
2311     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2312     Inst.addOperand(MCOperand::createReg(0));
2313     Inst.addOperand(MCOperand::createImm(Val));
2314   }
2315 
2316   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2317     assert(N == 3 && "Invalid number of operands!");
2318     // If we have an immediate that's not a constant, treat it as a label
2319     // reference needing a fixup. If it is a constant, it's something else
2320     // and we reject it.
2321     if (isImm()) {
2322       Inst.addOperand(MCOperand::createExpr(getImm()));
2323       Inst.addOperand(MCOperand::createReg(0));
2324       Inst.addOperand(MCOperand::createImm(0));
2325       return;
2326     }
2327 
2328     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2329     if (!Memory.OffsetRegNum) {
2330       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2331       // Special case for #-0
2332       if (Val == INT32_MIN) Val = 0;
2333       if (Val < 0) Val = -Val;
2334       Val = ARM_AM::getAM3Opc(AddSub, Val);
2335     } else {
2336       // For register offset, we encode the shift type and negation flag
2337       // here.
2338       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
2339     }
2340     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2341     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2342     Inst.addOperand(MCOperand::createImm(Val));
2343   }
2344 
2345   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
2346     assert(N == 2 && "Invalid number of operands!");
2347     if (Kind == k_PostIndexRegister) {
2348       int32_t Val =
2349         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
2350       Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2351       Inst.addOperand(MCOperand::createImm(Val));
2352       return;
2353     }
2354 
2355     // Constant offset.
2356     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
2357     int32_t Val = CE->getValue();
2358     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2359     // Special case for #-0
2360     if (Val == INT32_MIN) Val = 0;
2361     if (Val < 0) Val = -Val;
2362     Val = ARM_AM::getAM3Opc(AddSub, Val);
2363     Inst.addOperand(MCOperand::createReg(0));
2364     Inst.addOperand(MCOperand::createImm(Val));
2365   }
2366 
2367   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
2368     assert(N == 2 && "Invalid number of operands!");
2369     // If we have an immediate that's not a constant, treat it as a label
2370     // reference needing a fixup. If it is a constant, it's something else
2371     // and we reject it.
2372     if (isImm()) {
2373       Inst.addOperand(MCOperand::createExpr(getImm()));
2374       Inst.addOperand(MCOperand::createImm(0));
2375       return;
2376     }
2377 
2378     // The lower two bits are always zero and as such are not encoded.
2379     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2380     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2381     // Special case for #-0
2382     if (Val == INT32_MIN) Val = 0;
2383     if (Val < 0) Val = -Val;
2384     Val = ARM_AM::getAM5Opc(AddSub, Val);
2385     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2386     Inst.addOperand(MCOperand::createImm(Val));
2387   }
2388 
2389   void addAddrMode5FP16Operands(MCInst &Inst, unsigned N) const {
2390     assert(N == 2 && "Invalid number of operands!");
2391     // If we have an immediate that's not a constant, treat it as a label
2392     // reference needing a fixup. If it is a constant, it's something else
2393     // and we reject it.
2394     if (isImm()) {
2395       Inst.addOperand(MCOperand::createExpr(getImm()));
2396       Inst.addOperand(MCOperand::createImm(0));
2397       return;
2398     }
2399 
2400     // The lower bit is always zero and as such is not encoded.
2401     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 2 : 0;
2402     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2403     // Special case for #-0
2404     if (Val == INT32_MIN) Val = 0;
2405     if (Val < 0) Val = -Val;
2406     Val = ARM_AM::getAM5FP16Opc(AddSub, Val);
2407     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2408     Inst.addOperand(MCOperand::createImm(Val));
2409   }
2410 
2411   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
2412     assert(N == 2 && "Invalid number of operands!");
2413     // If we have an immediate that's not a constant, treat it as a label
2414     // reference needing a fixup. If it is a constant, it's something else
2415     // and we reject it.
2416     if (isImm()) {
2417       Inst.addOperand(MCOperand::createExpr(getImm()));
2418       Inst.addOperand(MCOperand::createImm(0));
2419       return;
2420     }
2421 
2422     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2423     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2424     Inst.addOperand(MCOperand::createImm(Val));
2425   }
2426 
2427   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
2428     assert(N == 2 && "Invalid number of operands!");
2429     // The lower two bits are always zero and as such are not encoded.
2430     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2431     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2432     Inst.addOperand(MCOperand::createImm(Val));
2433   }
2434 
2435   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2436     assert(N == 2 && "Invalid number of operands!");
2437     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2438     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2439     Inst.addOperand(MCOperand::createImm(Val));
2440   }
2441 
2442   void addMemPosImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2443     addMemImm8OffsetOperands(Inst, N);
2444   }
2445 
2446   void addMemNegImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2447     addMemImm8OffsetOperands(Inst, N);
2448   }
2449 
2450   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2451     assert(N == 2 && "Invalid number of operands!");
2452     // If this is an immediate, it's a label reference.
2453     if (isImm()) {
2454       addExpr(Inst, getImm());
2455       Inst.addOperand(MCOperand::createImm(0));
2456       return;
2457     }
2458 
2459     // Otherwise, it's a normal memory reg+offset.
2460     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2461     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2462     Inst.addOperand(MCOperand::createImm(Val));
2463   }
2464 
2465   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2466     assert(N == 2 && "Invalid number of operands!");
2467     // If this is an immediate, it's a label reference.
2468     if (isImm()) {
2469       addExpr(Inst, getImm());
2470       Inst.addOperand(MCOperand::createImm(0));
2471       return;
2472     }
2473 
2474     // Otherwise, it's a normal memory reg+offset.
2475     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2476     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2477     Inst.addOperand(MCOperand::createImm(Val));
2478   }
2479 
2480   void addConstPoolAsmImmOperands(MCInst &Inst, unsigned N) const {
2481     assert(N == 1 && "Invalid number of operands!");
2482     // This is container for the immediate that we will create the constant
2483     // pool from
2484     addExpr(Inst, getConstantPoolImm());
2485     return;
2486   }
2487 
2488   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
2489     assert(N == 2 && "Invalid number of operands!");
2490     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2491     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2492   }
2493 
2494   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
2495     assert(N == 2 && "Invalid number of operands!");
2496     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2497     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2498   }
2499 
2500   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2501     assert(N == 3 && "Invalid number of operands!");
2502     unsigned Val =
2503       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2504                         Memory.ShiftImm, Memory.ShiftType);
2505     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2506     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2507     Inst.addOperand(MCOperand::createImm(Val));
2508   }
2509 
2510   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2511     assert(N == 3 && "Invalid number of operands!");
2512     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2513     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2514     Inst.addOperand(MCOperand::createImm(Memory.ShiftImm));
2515   }
2516 
2517   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
2518     assert(N == 2 && "Invalid number of operands!");
2519     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2520     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2521   }
2522 
2523   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
2524     assert(N == 2 && "Invalid number of operands!");
2525     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2526     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2527     Inst.addOperand(MCOperand::createImm(Val));
2528   }
2529 
2530   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
2531     assert(N == 2 && "Invalid number of operands!");
2532     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
2533     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2534     Inst.addOperand(MCOperand::createImm(Val));
2535   }
2536 
2537   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
2538     assert(N == 2 && "Invalid number of operands!");
2539     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
2540     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2541     Inst.addOperand(MCOperand::createImm(Val));
2542   }
2543 
2544   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
2545     assert(N == 2 && "Invalid number of operands!");
2546     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2547     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2548     Inst.addOperand(MCOperand::createImm(Val));
2549   }
2550 
2551   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
2552     assert(N == 1 && "Invalid number of operands!");
2553     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2554     assert(CE && "non-constant post-idx-imm8 operand!");
2555     int Imm = CE->getValue();
2556     bool isAdd = Imm >= 0;
2557     if (Imm == INT32_MIN) Imm = 0;
2558     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
2559     Inst.addOperand(MCOperand::createImm(Imm));
2560   }
2561 
2562   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
2563     assert(N == 1 && "Invalid number of operands!");
2564     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2565     assert(CE && "non-constant post-idx-imm8s4 operand!");
2566     int Imm = CE->getValue();
2567     bool isAdd = Imm >= 0;
2568     if (Imm == INT32_MIN) Imm = 0;
2569     // Immediate is scaled by 4.
2570     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
2571     Inst.addOperand(MCOperand::createImm(Imm));
2572   }
2573 
2574   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
2575     assert(N == 2 && "Invalid number of operands!");
2576     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2577     Inst.addOperand(MCOperand::createImm(PostIdxReg.isAdd));
2578   }
2579 
2580   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
2581     assert(N == 2 && "Invalid number of operands!");
2582     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2583     // The sign, shift type, and shift amount are encoded in a single operand
2584     // using the AM2 encoding helpers.
2585     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
2586     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
2587                                      PostIdxReg.ShiftTy);
2588     Inst.addOperand(MCOperand::createImm(Imm));
2589   }
2590 
2591   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
2592     assert(N == 1 && "Invalid number of operands!");
2593     Inst.addOperand(MCOperand::createImm(unsigned(getMSRMask())));
2594   }
2595 
2596   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
2597     assert(N == 1 && "Invalid number of operands!");
2598     Inst.addOperand(MCOperand::createImm(unsigned(getBankedReg())));
2599   }
2600 
2601   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
2602     assert(N == 1 && "Invalid number of operands!");
2603     Inst.addOperand(MCOperand::createImm(unsigned(getProcIFlags())));
2604   }
2605 
2606   void addVecListOperands(MCInst &Inst, unsigned N) const {
2607     assert(N == 1 && "Invalid number of operands!");
2608     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2609   }
2610 
2611   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
2612     assert(N == 2 && "Invalid number of operands!");
2613     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2614     Inst.addOperand(MCOperand::createImm(VectorList.LaneIndex));
2615   }
2616 
2617   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
2618     assert(N == 1 && "Invalid number of operands!");
2619     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2620   }
2621 
2622   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
2623     assert(N == 1 && "Invalid number of operands!");
2624     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2625   }
2626 
2627   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
2628     assert(N == 1 && "Invalid number of operands!");
2629     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2630   }
2631 
2632   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
2633     assert(N == 1 && "Invalid number of operands!");
2634     // The immediate encodes the type of constant as well as the value.
2635     // Mask in that this is an i8 splat.
2636     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2637     Inst.addOperand(MCOperand::createImm(CE->getValue() | 0xe00));
2638   }
2639 
2640   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
2641     assert(N == 1 && "Invalid number of operands!");
2642     // The immediate encodes the type of constant as well as the value.
2643     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2644     unsigned Value = CE->getValue();
2645     Value = ARM_AM::encodeNEONi16splat(Value);
2646     Inst.addOperand(MCOperand::createImm(Value));
2647   }
2648 
2649   void addNEONi16splatNotOperands(MCInst &Inst, unsigned N) const {
2650     assert(N == 1 && "Invalid number of operands!");
2651     // The immediate encodes the type of constant as well as the value.
2652     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2653     unsigned Value = CE->getValue();
2654     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
2655     Inst.addOperand(MCOperand::createImm(Value));
2656   }
2657 
2658   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
2659     assert(N == 1 && "Invalid number of operands!");
2660     // The immediate encodes the type of constant as well as the value.
2661     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2662     unsigned Value = CE->getValue();
2663     Value = ARM_AM::encodeNEONi32splat(Value);
2664     Inst.addOperand(MCOperand::createImm(Value));
2665   }
2666 
2667   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
2668     assert(N == 1 && "Invalid number of operands!");
2669     // The immediate encodes the type of constant as well as the value.
2670     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2671     unsigned Value = CE->getValue();
2672     Value = ARM_AM::encodeNEONi32splat(~Value);
2673     Inst.addOperand(MCOperand::createImm(Value));
2674   }
2675 
2676   void addNEONinvByteReplicateOperands(MCInst &Inst, unsigned N) const {
2677     assert(N == 1 && "Invalid number of operands!");
2678     // The immediate encodes the type of constant as well as the value.
2679     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2680     unsigned Value = CE->getValue();
2681     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2682             Inst.getOpcode() == ARM::VMOVv16i8) &&
2683            "All vmvn instructions that wants to replicate non-zero byte "
2684            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2685     unsigned B = ((~Value) & 0xff);
2686     B |= 0xe00; // cmode = 0b1110
2687     Inst.addOperand(MCOperand::createImm(B));
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   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
2717     assert(N == 1 && "Invalid number of operands!");
2718     // The immediate encodes the type of constant as well as the value.
2719     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2720     unsigned Value = ~CE->getValue();
2721     if (Value >= 256 && Value <= 0xffff)
2722       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2723     else if (Value > 0xffff && Value <= 0xffffff)
2724       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2725     else if (Value > 0xffffff)
2726       Value = (Value >> 24) | 0x600;
2727     Inst.addOperand(MCOperand::createImm(Value));
2728   }
2729 
2730   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
2731     assert(N == 1 && "Invalid number of operands!");
2732     // The immediate encodes the type of constant as well as the value.
2733     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2734     uint64_t Value = CE->getValue();
2735     unsigned Imm = 0;
2736     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
2737       Imm |= (Value & 1) << i;
2738     }
2739     Inst.addOperand(MCOperand::createImm(Imm | 0x1e00));
2740   }
2741 
2742   void print(raw_ostream &OS) const override;
2743 
2744   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
2745     auto Op = make_unique<ARMOperand>(k_ITCondMask);
2746     Op->ITMask.Mask = Mask;
2747     Op->StartLoc = S;
2748     Op->EndLoc = S;
2749     return Op;
2750   }
2751 
2752   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
2753                                                     SMLoc S) {
2754     auto Op = make_unique<ARMOperand>(k_CondCode);
2755     Op->CC.Val = CC;
2756     Op->StartLoc = S;
2757     Op->EndLoc = S;
2758     return Op;
2759   }
2760 
2761   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
2762     auto Op = make_unique<ARMOperand>(k_CoprocNum);
2763     Op->Cop.Val = CopVal;
2764     Op->StartLoc = S;
2765     Op->EndLoc = S;
2766     return Op;
2767   }
2768 
2769   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
2770     auto Op = make_unique<ARMOperand>(k_CoprocReg);
2771     Op->Cop.Val = CopVal;
2772     Op->StartLoc = S;
2773     Op->EndLoc = S;
2774     return Op;
2775   }
2776 
2777   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
2778                                                         SMLoc E) {
2779     auto Op = make_unique<ARMOperand>(k_CoprocOption);
2780     Op->Cop.Val = Val;
2781     Op->StartLoc = S;
2782     Op->EndLoc = E;
2783     return Op;
2784   }
2785 
2786   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
2787     auto Op = make_unique<ARMOperand>(k_CCOut);
2788     Op->Reg.RegNum = RegNum;
2789     Op->StartLoc = S;
2790     Op->EndLoc = S;
2791     return Op;
2792   }
2793 
2794   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
2795     auto Op = make_unique<ARMOperand>(k_Token);
2796     Op->Tok.Data = Str.data();
2797     Op->Tok.Length = Str.size();
2798     Op->StartLoc = S;
2799     Op->EndLoc = S;
2800     return Op;
2801   }
2802 
2803   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
2804                                                SMLoc E) {
2805     auto Op = make_unique<ARMOperand>(k_Register);
2806     Op->Reg.RegNum = RegNum;
2807     Op->StartLoc = S;
2808     Op->EndLoc = E;
2809     return Op;
2810   }
2811 
2812   static std::unique_ptr<ARMOperand>
2813   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2814                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
2815                         SMLoc E) {
2816     auto Op = make_unique<ARMOperand>(k_ShiftedRegister);
2817     Op->RegShiftedReg.ShiftTy = ShTy;
2818     Op->RegShiftedReg.SrcReg = SrcReg;
2819     Op->RegShiftedReg.ShiftReg = ShiftReg;
2820     Op->RegShiftedReg.ShiftImm = ShiftImm;
2821     Op->StartLoc = S;
2822     Op->EndLoc = E;
2823     return Op;
2824   }
2825 
2826   static std::unique_ptr<ARMOperand>
2827   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2828                          unsigned ShiftImm, SMLoc S, SMLoc E) {
2829     auto Op = make_unique<ARMOperand>(k_ShiftedImmediate);
2830     Op->RegShiftedImm.ShiftTy = ShTy;
2831     Op->RegShiftedImm.SrcReg = SrcReg;
2832     Op->RegShiftedImm.ShiftImm = ShiftImm;
2833     Op->StartLoc = S;
2834     Op->EndLoc = E;
2835     return Op;
2836   }
2837 
2838   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
2839                                                       SMLoc S, SMLoc E) {
2840     auto Op = make_unique<ARMOperand>(k_ShifterImmediate);
2841     Op->ShifterImm.isASR = isASR;
2842     Op->ShifterImm.Imm = Imm;
2843     Op->StartLoc = S;
2844     Op->EndLoc = E;
2845     return Op;
2846   }
2847 
2848   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
2849                                                   SMLoc E) {
2850     auto Op = make_unique<ARMOperand>(k_RotateImmediate);
2851     Op->RotImm.Imm = Imm;
2852     Op->StartLoc = S;
2853     Op->EndLoc = E;
2854     return Op;
2855   }
2856 
2857   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
2858                                                   SMLoc S, SMLoc E) {
2859     auto Op = make_unique<ARMOperand>(k_ModifiedImmediate);
2860     Op->ModImm.Bits = Bits;
2861     Op->ModImm.Rot = Rot;
2862     Op->StartLoc = S;
2863     Op->EndLoc = E;
2864     return Op;
2865   }
2866 
2867   static std::unique_ptr<ARMOperand>
2868   CreateConstantPoolImm(const MCExpr *Val, SMLoc S, SMLoc E) {
2869     auto Op = make_unique<ARMOperand>(k_ConstantPoolImmediate);
2870     Op->Imm.Val = Val;
2871     Op->StartLoc = S;
2872     Op->EndLoc = E;
2873     return Op;
2874   }
2875 
2876   static std::unique_ptr<ARMOperand>
2877   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
2878     auto Op = make_unique<ARMOperand>(k_BitfieldDescriptor);
2879     Op->Bitfield.LSB = LSB;
2880     Op->Bitfield.Width = Width;
2881     Op->StartLoc = S;
2882     Op->EndLoc = E;
2883     return Op;
2884   }
2885 
2886   static std::unique_ptr<ARMOperand>
2887   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
2888                 SMLoc StartLoc, SMLoc EndLoc) {
2889     assert (Regs.size() > 0 && "RegList contains no registers?");
2890     KindTy Kind = k_RegisterList;
2891 
2892     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Regs.front().second))
2893       Kind = k_DPRRegisterList;
2894     else if (ARMMCRegisterClasses[ARM::SPRRegClassID].
2895              contains(Regs.front().second))
2896       Kind = k_SPRRegisterList;
2897 
2898     // Sort based on the register encoding values.
2899     array_pod_sort(Regs.begin(), Regs.end());
2900 
2901     auto Op = make_unique<ARMOperand>(Kind);
2902     for (SmallVectorImpl<std::pair<unsigned, unsigned> >::const_iterator
2903            I = Regs.begin(), E = Regs.end(); I != E; ++I)
2904       Op->Registers.push_back(I->second);
2905     Op->StartLoc = StartLoc;
2906     Op->EndLoc = EndLoc;
2907     return Op;
2908   }
2909 
2910   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
2911                                                       unsigned Count,
2912                                                       bool isDoubleSpaced,
2913                                                       SMLoc S, SMLoc E) {
2914     auto Op = make_unique<ARMOperand>(k_VectorList);
2915     Op->VectorList.RegNum = RegNum;
2916     Op->VectorList.Count = Count;
2917     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2918     Op->StartLoc = S;
2919     Op->EndLoc = E;
2920     return Op;
2921   }
2922 
2923   static std::unique_ptr<ARMOperand>
2924   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
2925                            SMLoc S, SMLoc E) {
2926     auto Op = make_unique<ARMOperand>(k_VectorListAllLanes);
2927     Op->VectorList.RegNum = RegNum;
2928     Op->VectorList.Count = Count;
2929     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2930     Op->StartLoc = S;
2931     Op->EndLoc = E;
2932     return Op;
2933   }
2934 
2935   static std::unique_ptr<ARMOperand>
2936   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
2937                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
2938     auto Op = make_unique<ARMOperand>(k_VectorListIndexed);
2939     Op->VectorList.RegNum = RegNum;
2940     Op->VectorList.Count = Count;
2941     Op->VectorList.LaneIndex = Index;
2942     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2943     Op->StartLoc = S;
2944     Op->EndLoc = E;
2945     return Op;
2946   }
2947 
2948   static std::unique_ptr<ARMOperand>
2949   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
2950     auto Op = make_unique<ARMOperand>(k_VectorIndex);
2951     Op->VectorIndex.Val = Idx;
2952     Op->StartLoc = S;
2953     Op->EndLoc = E;
2954     return Op;
2955   }
2956 
2957   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
2958                                                SMLoc E) {
2959     auto Op = make_unique<ARMOperand>(k_Immediate);
2960     Op->Imm.Val = Val;
2961     Op->StartLoc = S;
2962     Op->EndLoc = E;
2963     return Op;
2964   }
2965 
2966   static std::unique_ptr<ARMOperand>
2967   CreateMem(unsigned BaseRegNum, const MCConstantExpr *OffsetImm,
2968             unsigned OffsetRegNum, ARM_AM::ShiftOpc ShiftType,
2969             unsigned ShiftImm, unsigned Alignment, bool isNegative, SMLoc S,
2970             SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
2971     auto Op = make_unique<ARMOperand>(k_Memory);
2972     Op->Memory.BaseRegNum = BaseRegNum;
2973     Op->Memory.OffsetImm = OffsetImm;
2974     Op->Memory.OffsetRegNum = OffsetRegNum;
2975     Op->Memory.ShiftType = ShiftType;
2976     Op->Memory.ShiftImm = ShiftImm;
2977     Op->Memory.Alignment = Alignment;
2978     Op->Memory.isNegative = isNegative;
2979     Op->StartLoc = S;
2980     Op->EndLoc = E;
2981     Op->AlignmentLoc = AlignmentLoc;
2982     return Op;
2983   }
2984 
2985   static std::unique_ptr<ARMOperand>
2986   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
2987                    unsigned ShiftImm, SMLoc S, SMLoc E) {
2988     auto Op = make_unique<ARMOperand>(k_PostIndexRegister);
2989     Op->PostIdxReg.RegNum = RegNum;
2990     Op->PostIdxReg.isAdd = isAdd;
2991     Op->PostIdxReg.ShiftTy = ShiftTy;
2992     Op->PostIdxReg.ShiftImm = ShiftImm;
2993     Op->StartLoc = S;
2994     Op->EndLoc = E;
2995     return Op;
2996   }
2997 
2998   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
2999                                                          SMLoc S) {
3000     auto Op = make_unique<ARMOperand>(k_MemBarrierOpt);
3001     Op->MBOpt.Val = Opt;
3002     Op->StartLoc = S;
3003     Op->EndLoc = S;
3004     return Op;
3005   }
3006 
3007   static std::unique_ptr<ARMOperand>
3008   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
3009     auto Op = make_unique<ARMOperand>(k_InstSyncBarrierOpt);
3010     Op->ISBOpt.Val = Opt;
3011     Op->StartLoc = S;
3012     Op->EndLoc = S;
3013     return Op;
3014   }
3015 
3016   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
3017                                                       SMLoc S) {
3018     auto Op = make_unique<ARMOperand>(k_ProcIFlags);
3019     Op->IFlags.Val = IFlags;
3020     Op->StartLoc = S;
3021     Op->EndLoc = S;
3022     return Op;
3023   }
3024 
3025   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
3026     auto Op = make_unique<ARMOperand>(k_MSRMask);
3027     Op->MMask.Val = MMask;
3028     Op->StartLoc = S;
3029     Op->EndLoc = S;
3030     return Op;
3031   }
3032 
3033   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
3034     auto Op = make_unique<ARMOperand>(k_BankedReg);
3035     Op->BankedReg.Val = Reg;
3036     Op->StartLoc = S;
3037     Op->EndLoc = S;
3038     return Op;
3039   }
3040 };
3041 
3042 } // end anonymous namespace.
3043 
3044 void ARMOperand::print(raw_ostream &OS) const {
3045   switch (Kind) {
3046   case k_CondCode:
3047     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
3048     break;
3049   case k_CCOut:
3050     OS << "<ccout " << getReg() << ">";
3051     break;
3052   case k_ITCondMask: {
3053     static const char *const MaskStr[] = {
3054       "()", "(t)", "(e)", "(tt)", "(et)", "(te)", "(ee)", "(ttt)", "(ett)",
3055       "(tet)", "(eet)", "(tte)", "(ete)", "(tee)", "(eee)"
3056     };
3057     assert((ITMask.Mask & 0xf) == ITMask.Mask);
3058     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
3059     break;
3060   }
3061   case k_CoprocNum:
3062     OS << "<coprocessor number: " << getCoproc() << ">";
3063     break;
3064   case k_CoprocReg:
3065     OS << "<coprocessor register: " << getCoproc() << ">";
3066     break;
3067   case k_CoprocOption:
3068     OS << "<coprocessor option: " << CoprocOption.Val << ">";
3069     break;
3070   case k_MSRMask:
3071     OS << "<mask: " << getMSRMask() << ">";
3072     break;
3073   case k_BankedReg:
3074     OS << "<banked reg: " << getBankedReg() << ">";
3075     break;
3076   case k_Immediate:
3077     OS << *getImm();
3078     break;
3079   case k_MemBarrierOpt:
3080     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
3081     break;
3082   case k_InstSyncBarrierOpt:
3083     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
3084     break;
3085   case k_Memory:
3086     OS << "<memory "
3087        << " base:" << Memory.BaseRegNum;
3088     OS << ">";
3089     break;
3090   case k_PostIndexRegister:
3091     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
3092        << PostIdxReg.RegNum;
3093     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
3094       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
3095          << PostIdxReg.ShiftImm;
3096     OS << ">";
3097     break;
3098   case k_ProcIFlags: {
3099     OS << "<ARM_PROC::";
3100     unsigned IFlags = getProcIFlags();
3101     for (int i=2; i >= 0; --i)
3102       if (IFlags & (1 << i))
3103         OS << ARM_PROC::IFlagsToString(1 << i);
3104     OS << ">";
3105     break;
3106   }
3107   case k_Register:
3108     OS << "<register " << getReg() << ">";
3109     break;
3110   case k_ShifterImmediate:
3111     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
3112        << " #" << ShifterImm.Imm << ">";
3113     break;
3114   case k_ShiftedRegister:
3115     OS << "<so_reg_reg "
3116        << RegShiftedReg.SrcReg << " "
3117        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy)
3118        << " " << RegShiftedReg.ShiftReg << ">";
3119     break;
3120   case k_ShiftedImmediate:
3121     OS << "<so_reg_imm "
3122        << RegShiftedImm.SrcReg << " "
3123        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy)
3124        << " #" << RegShiftedImm.ShiftImm << ">";
3125     break;
3126   case k_RotateImmediate:
3127     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
3128     break;
3129   case k_ModifiedImmediate:
3130     OS << "<mod_imm #" << ModImm.Bits << ", #"
3131        <<  ModImm.Rot << ")>";
3132     break;
3133   case k_ConstantPoolImmediate:
3134     OS << "<constant_pool_imm #" << *getConstantPoolImm();
3135     break;
3136   case k_BitfieldDescriptor:
3137     OS << "<bitfield " << "lsb: " << Bitfield.LSB
3138        << ", width: " << Bitfield.Width << ">";
3139     break;
3140   case k_RegisterList:
3141   case k_DPRRegisterList:
3142   case k_SPRRegisterList: {
3143     OS << "<register_list ";
3144 
3145     const SmallVectorImpl<unsigned> &RegList = getRegList();
3146     for (SmallVectorImpl<unsigned>::const_iterator
3147            I = RegList.begin(), E = RegList.end(); I != E; ) {
3148       OS << *I;
3149       if (++I < E) OS << ", ";
3150     }
3151 
3152     OS << ">";
3153     break;
3154   }
3155   case k_VectorList:
3156     OS << "<vector_list " << VectorList.Count << " * "
3157        << VectorList.RegNum << ">";
3158     break;
3159   case k_VectorListAllLanes:
3160     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
3161        << VectorList.RegNum << ">";
3162     break;
3163   case k_VectorListIndexed:
3164     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
3165        << VectorList.Count << " * " << VectorList.RegNum << ">";
3166     break;
3167   case k_Token:
3168     OS << "'" << getToken() << "'";
3169     break;
3170   case k_VectorIndex:
3171     OS << "<vectorindex " << getVectorIndex() << ">";
3172     break;
3173   }
3174 }
3175 
3176 /// @name Auto-generated Match Functions
3177 /// {
3178 
3179 static unsigned MatchRegisterName(StringRef Name);
3180 
3181 /// }
3182 
3183 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
3184                                  SMLoc &StartLoc, SMLoc &EndLoc) {
3185   const AsmToken &Tok = getParser().getTok();
3186   StartLoc = Tok.getLoc();
3187   EndLoc = Tok.getEndLoc();
3188   RegNo = tryParseRegister();
3189 
3190   return (RegNo == (unsigned)-1);
3191 }
3192 
3193 /// Try to parse a register name.  The token must be an Identifier when called,
3194 /// and if it is a register name the token is eaten and the register number is
3195 /// returned.  Otherwise return -1.
3196 ///
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 
3351 /// Try to parse a register name.  The token must be an Identifier when called.
3352 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
3353 /// if there is a "writeback". 'true' if it's not a register.
3354 ///
3355 /// TODO this is likely to change to allow different register types and or to
3356 /// parse for a specific register type.
3357 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
3358   MCAsmParser &Parser = getParser();
3359   const AsmToken &RegTok = Parser.getTok();
3360   int RegNo = tryParseRegister();
3361   if (RegNo == -1)
3362     return true;
3363 
3364   Operands.push_back(ARMOperand::CreateReg(RegNo, RegTok.getLoc(),
3365                                            RegTok.getEndLoc()));
3366 
3367   const AsmToken &ExclaimTok = Parser.getTok();
3368   if (ExclaimTok.is(AsmToken::Exclaim)) {
3369     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
3370                                                ExclaimTok.getLoc()));
3371     Parser.Lex(); // Eat exclaim token
3372     return false;
3373   }
3374 
3375   // Also check for an index operand. This is only legal for vector registers,
3376   // but that'll get caught OK in operand matching, so we don't need to
3377   // explicitly filter everything else out here.
3378   if (Parser.getTok().is(AsmToken::LBrac)) {
3379     SMLoc SIdx = Parser.getTok().getLoc();
3380     Parser.Lex(); // Eat left bracket token.
3381 
3382     const MCExpr *ImmVal;
3383     if (getParser().parseExpression(ImmVal))
3384       return true;
3385     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
3386     if (!MCE)
3387       return TokError("immediate value expected for vector index");
3388 
3389     if (Parser.getTok().isNot(AsmToken::RBrac))
3390       return Error(Parser.getTok().getLoc(), "']' expected");
3391 
3392     SMLoc E = Parser.getTok().getEndLoc();
3393     Parser.Lex(); // Eat right bracket token.
3394 
3395     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
3396                                                      SIdx, E,
3397                                                      getContext()));
3398   }
3399 
3400   return false;
3401 }
3402 
3403 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
3404 /// instruction with a symbolic operand name.
3405 /// We accept "crN" syntax for GAS compatibility.
3406 /// <operand-name> ::= <prefix><number>
3407 /// If CoprocOp is 'c', then:
3408 ///   <prefix> ::= c | cr
3409 /// If CoprocOp is 'p', then :
3410 ///   <prefix> ::= p
3411 /// <number> ::= integer in range [0, 15]
3412 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
3413   // Use the same layout as the tablegen'erated register name matcher. Ugly,
3414   // but efficient.
3415   if (Name.size() < 2 || Name[0] != CoprocOp)
3416     return -1;
3417   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
3418 
3419   switch (Name.size()) {
3420   default: return -1;
3421   case 1:
3422     switch (Name[0]) {
3423     default:  return -1;
3424     case '0': return 0;
3425     case '1': return 1;
3426     case '2': return 2;
3427     case '3': return 3;
3428     case '4': return 4;
3429     case '5': return 5;
3430     case '6': return 6;
3431     case '7': return 7;
3432     case '8': return 8;
3433     case '9': return 9;
3434     }
3435   case 2:
3436     if (Name[0] != '1')
3437       return -1;
3438     switch (Name[1]) {
3439     default:  return -1;
3440     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
3441     // However, old cores (v5/v6) did use them in that way.
3442     case '0': return 10;
3443     case '1': return 11;
3444     case '2': return 12;
3445     case '3': return 13;
3446     case '4': return 14;
3447     case '5': return 15;
3448     }
3449   }
3450 }
3451 
3452 /// parseITCondCode - Try to parse a condition code for an IT instruction.
3453 OperandMatchResultTy
3454 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
3455   MCAsmParser &Parser = getParser();
3456   SMLoc S = Parser.getTok().getLoc();
3457   const AsmToken &Tok = Parser.getTok();
3458   if (!Tok.is(AsmToken::Identifier))
3459     return MatchOperand_NoMatch;
3460   unsigned CC = StringSwitch<unsigned>(Tok.getString().lower())
3461     .Case("eq", ARMCC::EQ)
3462     .Case("ne", ARMCC::NE)
3463     .Case("hs", ARMCC::HS)
3464     .Case("cs", ARMCC::HS)
3465     .Case("lo", ARMCC::LO)
3466     .Case("cc", ARMCC::LO)
3467     .Case("mi", ARMCC::MI)
3468     .Case("pl", ARMCC::PL)
3469     .Case("vs", ARMCC::VS)
3470     .Case("vc", ARMCC::VC)
3471     .Case("hi", ARMCC::HI)
3472     .Case("ls", ARMCC::LS)
3473     .Case("ge", ARMCC::GE)
3474     .Case("lt", ARMCC::LT)
3475     .Case("gt", ARMCC::GT)
3476     .Case("le", ARMCC::LE)
3477     .Case("al", ARMCC::AL)
3478     .Default(~0U);
3479   if (CC == ~0U)
3480     return MatchOperand_NoMatch;
3481   Parser.Lex(); // Eat the token.
3482 
3483   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
3484 
3485   return MatchOperand_Success;
3486 }
3487 
3488 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
3489 /// token must be an Identifier when called, and if it is a coprocessor
3490 /// number, the token is eaten and the operand is added to the operand list.
3491 OperandMatchResultTy
3492 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
3493   MCAsmParser &Parser = getParser();
3494   SMLoc S = Parser.getTok().getLoc();
3495   const AsmToken &Tok = Parser.getTok();
3496   if (Tok.isNot(AsmToken::Identifier))
3497     return MatchOperand_NoMatch;
3498 
3499   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
3500   if (Num == -1)
3501     return MatchOperand_NoMatch;
3502   // ARMv7 and v8 don't allow cp10/cp11 due to VFP/NEON specific instructions
3503   if ((hasV7Ops() || hasV8Ops()) && (Num == 10 || Num == 11))
3504     return MatchOperand_NoMatch;
3505 
3506   Parser.Lex(); // Eat identifier token.
3507   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
3508   return MatchOperand_Success;
3509 }
3510 
3511 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
3512 /// token must be an Identifier when called, and if it is a coprocessor
3513 /// number, the token is eaten and the operand is added to the operand list.
3514 OperandMatchResultTy
3515 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
3516   MCAsmParser &Parser = getParser();
3517   SMLoc S = Parser.getTok().getLoc();
3518   const AsmToken &Tok = Parser.getTok();
3519   if (Tok.isNot(AsmToken::Identifier))
3520     return MatchOperand_NoMatch;
3521 
3522   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
3523   if (Reg == -1)
3524     return MatchOperand_NoMatch;
3525 
3526   Parser.Lex(); // Eat identifier token.
3527   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
3528   return MatchOperand_Success;
3529 }
3530 
3531 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
3532 /// coproc_option : '{' imm0_255 '}'
3533 OperandMatchResultTy
3534 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
3535   MCAsmParser &Parser = getParser();
3536   SMLoc S = Parser.getTok().getLoc();
3537 
3538   // If this isn't a '{', this isn't a coprocessor immediate operand.
3539   if (Parser.getTok().isNot(AsmToken::LCurly))
3540     return MatchOperand_NoMatch;
3541   Parser.Lex(); // Eat the '{'
3542 
3543   const MCExpr *Expr;
3544   SMLoc Loc = Parser.getTok().getLoc();
3545   if (getParser().parseExpression(Expr)) {
3546     Error(Loc, "illegal expression");
3547     return MatchOperand_ParseFail;
3548   }
3549   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
3550   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
3551     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
3552     return MatchOperand_ParseFail;
3553   }
3554   int Val = CE->getValue();
3555 
3556   // Check for and consume the closing '}'
3557   if (Parser.getTok().isNot(AsmToken::RCurly))
3558     return MatchOperand_ParseFail;
3559   SMLoc E = Parser.getTok().getEndLoc();
3560   Parser.Lex(); // Eat the '}'
3561 
3562   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
3563   return MatchOperand_Success;
3564 }
3565 
3566 // For register list parsing, we need to map from raw GPR register numbering
3567 // to the enumeration values. The enumeration values aren't sorted by
3568 // register number due to our using "sp", "lr" and "pc" as canonical names.
3569 static unsigned getNextRegister(unsigned Reg) {
3570   // If this is a GPR, we need to do it manually, otherwise we can rely
3571   // on the sort ordering of the enumeration since the other reg-classes
3572   // are sane.
3573   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3574     return Reg + 1;
3575   switch(Reg) {
3576   default: llvm_unreachable("Invalid GPR number!");
3577   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
3578   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
3579   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
3580   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
3581   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
3582   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
3583   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
3584   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
3585   }
3586 }
3587 
3588 // Return the low-subreg of a given Q register.
3589 static unsigned getDRegFromQReg(unsigned QReg) {
3590   switch (QReg) {
3591   default: llvm_unreachable("expected a Q register!");
3592   case ARM::Q0:  return ARM::D0;
3593   case ARM::Q1:  return ARM::D2;
3594   case ARM::Q2:  return ARM::D4;
3595   case ARM::Q3:  return ARM::D6;
3596   case ARM::Q4:  return ARM::D8;
3597   case ARM::Q5:  return ARM::D10;
3598   case ARM::Q6:  return ARM::D12;
3599   case ARM::Q7:  return ARM::D14;
3600   case ARM::Q8:  return ARM::D16;
3601   case ARM::Q9:  return ARM::D18;
3602   case ARM::Q10: return ARM::D20;
3603   case ARM::Q11: return ARM::D22;
3604   case ARM::Q12: return ARM::D24;
3605   case ARM::Q13: return ARM::D26;
3606   case ARM::Q14: return ARM::D28;
3607   case ARM::Q15: return ARM::D30;
3608   }
3609 }
3610 
3611 /// Parse a register list.
3612 bool ARMAsmParser::parseRegisterList(OperandVector &Operands) {
3613   MCAsmParser &Parser = getParser();
3614   if (Parser.getTok().isNot(AsmToken::LCurly))
3615     return TokError("Token is not a Left Curly Brace");
3616   SMLoc S = Parser.getTok().getLoc();
3617   Parser.Lex(); // Eat '{' token.
3618   SMLoc RegLoc = Parser.getTok().getLoc();
3619 
3620   // Check the first register in the list to see what register class
3621   // this is a list of.
3622   int Reg = tryParseRegister();
3623   if (Reg == -1)
3624     return Error(RegLoc, "register expected");
3625 
3626   // The reglist instructions have at most 16 registers, so reserve
3627   // space for that many.
3628   int EReg = 0;
3629   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
3630 
3631   // Allow Q regs and just interpret them as the two D sub-registers.
3632   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3633     Reg = getDRegFromQReg(Reg);
3634     EReg = MRI->getEncodingValue(Reg);
3635     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3636     ++Reg;
3637   }
3638   const MCRegisterClass *RC;
3639   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3640     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
3641   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
3642     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
3643   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
3644     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
3645   else
3646     return Error(RegLoc, "invalid register in register list");
3647 
3648   // Store the register.
3649   EReg = MRI->getEncodingValue(Reg);
3650   Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3651 
3652   // This starts immediately after the first register token in the list,
3653   // so we can see either a comma or a minus (range separator) as a legal
3654   // next token.
3655   while (Parser.getTok().is(AsmToken::Comma) ||
3656          Parser.getTok().is(AsmToken::Minus)) {
3657     if (Parser.getTok().is(AsmToken::Minus)) {
3658       Parser.Lex(); // Eat the minus.
3659       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3660       int EndReg = tryParseRegister();
3661       if (EndReg == -1)
3662         return Error(AfterMinusLoc, "register expected");
3663       // Allow Q regs and just interpret them as the two D sub-registers.
3664       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3665         EndReg = getDRegFromQReg(EndReg) + 1;
3666       // If the register is the same as the start reg, there's nothing
3667       // more to do.
3668       if (Reg == EndReg)
3669         continue;
3670       // The register must be in the same register class as the first.
3671       if (!RC->contains(EndReg))
3672         return Error(AfterMinusLoc, "invalid register in register list");
3673       // Ranges must go from low to high.
3674       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
3675         return Error(AfterMinusLoc, "bad range in register list");
3676 
3677       // Add all the registers in the range to the register list.
3678       while (Reg != EndReg) {
3679         Reg = getNextRegister(Reg);
3680         EReg = MRI->getEncodingValue(Reg);
3681         Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3682       }
3683       continue;
3684     }
3685     Parser.Lex(); // Eat the comma.
3686     RegLoc = Parser.getTok().getLoc();
3687     int OldReg = Reg;
3688     const AsmToken RegTok = Parser.getTok();
3689     Reg = tryParseRegister();
3690     if (Reg == -1)
3691       return Error(RegLoc, "register expected");
3692     // Allow Q regs and just interpret them as the two D sub-registers.
3693     bool isQReg = false;
3694     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3695       Reg = getDRegFromQReg(Reg);
3696       isQReg = true;
3697     }
3698     // The register must be in the same register class as the first.
3699     if (!RC->contains(Reg))
3700       return Error(RegLoc, "invalid register in register list");
3701     // List must be monotonically increasing.
3702     if (MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
3703       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3704         Warning(RegLoc, "register list not in ascending order");
3705       else
3706         return Error(RegLoc, "register list not in ascending order");
3707     }
3708     if (MRI->getEncodingValue(Reg) == MRI->getEncodingValue(OldReg)) {
3709       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
3710               ") in register list");
3711       continue;
3712     }
3713     // VFP register lists must also be contiguous.
3714     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
3715         Reg != OldReg + 1)
3716       return Error(RegLoc, "non-contiguous register range");
3717     EReg = MRI->getEncodingValue(Reg);
3718     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3719     if (isQReg) {
3720       EReg = MRI->getEncodingValue(++Reg);
3721       Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3722     }
3723   }
3724 
3725   if (Parser.getTok().isNot(AsmToken::RCurly))
3726     return Error(Parser.getTok().getLoc(), "'}' expected");
3727   SMLoc E = Parser.getTok().getEndLoc();
3728   Parser.Lex(); // Eat '}' token.
3729 
3730   // Push the register list operand.
3731   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
3732 
3733   // The ARM system instruction variants for LDM/STM have a '^' token here.
3734   if (Parser.getTok().is(AsmToken::Caret)) {
3735     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
3736     Parser.Lex(); // Eat '^' token.
3737   }
3738 
3739   return false;
3740 }
3741 
3742 // Helper function to parse the lane index for vector lists.
3743 OperandMatchResultTy ARMAsmParser::
3744 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
3745   MCAsmParser &Parser = getParser();
3746   Index = 0; // Always return a defined index value.
3747   if (Parser.getTok().is(AsmToken::LBrac)) {
3748     Parser.Lex(); // Eat the '['.
3749     if (Parser.getTok().is(AsmToken::RBrac)) {
3750       // "Dn[]" is the 'all lanes' syntax.
3751       LaneKind = AllLanes;
3752       EndLoc = Parser.getTok().getEndLoc();
3753       Parser.Lex(); // Eat the ']'.
3754       return MatchOperand_Success;
3755     }
3756 
3757     // There's an optional '#' token here. Normally there wouldn't be, but
3758     // inline assemble puts one in, and it's friendly to accept that.
3759     if (Parser.getTok().is(AsmToken::Hash))
3760       Parser.Lex(); // Eat '#' or '$'.
3761 
3762     const MCExpr *LaneIndex;
3763     SMLoc Loc = Parser.getTok().getLoc();
3764     if (getParser().parseExpression(LaneIndex)) {
3765       Error(Loc, "illegal expression");
3766       return MatchOperand_ParseFail;
3767     }
3768     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
3769     if (!CE) {
3770       Error(Loc, "lane index must be empty or an integer");
3771       return MatchOperand_ParseFail;
3772     }
3773     if (Parser.getTok().isNot(AsmToken::RBrac)) {
3774       Error(Parser.getTok().getLoc(), "']' expected");
3775       return MatchOperand_ParseFail;
3776     }
3777     EndLoc = Parser.getTok().getEndLoc();
3778     Parser.Lex(); // Eat the ']'.
3779     int64_t Val = CE->getValue();
3780 
3781     // FIXME: Make this range check context sensitive for .8, .16, .32.
3782     if (Val < 0 || Val > 7) {
3783       Error(Parser.getTok().getLoc(), "lane index out of range");
3784       return MatchOperand_ParseFail;
3785     }
3786     Index = Val;
3787     LaneKind = IndexedLane;
3788     return MatchOperand_Success;
3789   }
3790   LaneKind = NoLanes;
3791   return MatchOperand_Success;
3792 }
3793 
3794 // parse a vector register list
3795 OperandMatchResultTy
3796 ARMAsmParser::parseVectorList(OperandVector &Operands) {
3797   MCAsmParser &Parser = getParser();
3798   VectorLaneTy LaneKind;
3799   unsigned LaneIndex;
3800   SMLoc S = Parser.getTok().getLoc();
3801   // As an extension (to match gas), support a plain D register or Q register
3802   // (without encosing curly braces) as a single or double entry list,
3803   // respectively.
3804   if (Parser.getTok().is(AsmToken::Identifier)) {
3805     SMLoc E = Parser.getTok().getEndLoc();
3806     int Reg = tryParseRegister();
3807     if (Reg == -1)
3808       return MatchOperand_NoMatch;
3809     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
3810       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3811       if (Res != MatchOperand_Success)
3812         return Res;
3813       switch (LaneKind) {
3814       case NoLanes:
3815         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
3816         break;
3817       case AllLanes:
3818         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
3819                                                                 S, E));
3820         break;
3821       case IndexedLane:
3822         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
3823                                                                LaneIndex,
3824                                                                false, S, E));
3825         break;
3826       }
3827       return MatchOperand_Success;
3828     }
3829     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3830       Reg = getDRegFromQReg(Reg);
3831       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3832       if (Res != MatchOperand_Success)
3833         return Res;
3834       switch (LaneKind) {
3835       case NoLanes:
3836         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3837                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3838         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
3839         break;
3840       case AllLanes:
3841         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3842                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3843         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
3844                                                                 S, E));
3845         break;
3846       case IndexedLane:
3847         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
3848                                                                LaneIndex,
3849                                                                false, S, E));
3850         break;
3851       }
3852       return MatchOperand_Success;
3853     }
3854     Error(S, "vector register expected");
3855     return MatchOperand_ParseFail;
3856   }
3857 
3858   if (Parser.getTok().isNot(AsmToken::LCurly))
3859     return MatchOperand_NoMatch;
3860 
3861   Parser.Lex(); // Eat '{' token.
3862   SMLoc RegLoc = Parser.getTok().getLoc();
3863 
3864   int Reg = tryParseRegister();
3865   if (Reg == -1) {
3866     Error(RegLoc, "register expected");
3867     return MatchOperand_ParseFail;
3868   }
3869   unsigned Count = 1;
3870   int Spacing = 0;
3871   unsigned FirstReg = Reg;
3872   // The list is of D registers, but we also allow Q regs and just interpret
3873   // them as the two D sub-registers.
3874   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3875     FirstReg = Reg = getDRegFromQReg(Reg);
3876     Spacing = 1; // double-spacing requires explicit D registers, otherwise
3877                  // it's ambiguous with four-register single spaced.
3878     ++Reg;
3879     ++Count;
3880   }
3881 
3882   SMLoc E;
3883   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
3884     return MatchOperand_ParseFail;
3885 
3886   while (Parser.getTok().is(AsmToken::Comma) ||
3887          Parser.getTok().is(AsmToken::Minus)) {
3888     if (Parser.getTok().is(AsmToken::Minus)) {
3889       if (!Spacing)
3890         Spacing = 1; // Register range implies a single spaced list.
3891       else if (Spacing == 2) {
3892         Error(Parser.getTok().getLoc(),
3893               "sequential registers in double spaced list");
3894         return MatchOperand_ParseFail;
3895       }
3896       Parser.Lex(); // Eat the minus.
3897       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3898       int EndReg = tryParseRegister();
3899       if (EndReg == -1) {
3900         Error(AfterMinusLoc, "register expected");
3901         return MatchOperand_ParseFail;
3902       }
3903       // Allow Q regs and just interpret them as the two D sub-registers.
3904       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3905         EndReg = getDRegFromQReg(EndReg) + 1;
3906       // If the register is the same as the start reg, there's nothing
3907       // more to do.
3908       if (Reg == EndReg)
3909         continue;
3910       // The register must be in the same register class as the first.
3911       if (!ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg)) {
3912         Error(AfterMinusLoc, "invalid register in register list");
3913         return MatchOperand_ParseFail;
3914       }
3915       // Ranges must go from low to high.
3916       if (Reg > EndReg) {
3917         Error(AfterMinusLoc, "bad range in register list");
3918         return MatchOperand_ParseFail;
3919       }
3920       // Parse the lane specifier if present.
3921       VectorLaneTy NextLaneKind;
3922       unsigned NextLaneIndex;
3923       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3924           MatchOperand_Success)
3925         return MatchOperand_ParseFail;
3926       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3927         Error(AfterMinusLoc, "mismatched lane index in register list");
3928         return MatchOperand_ParseFail;
3929       }
3930 
3931       // Add all the registers in the range to the register list.
3932       Count += EndReg - Reg;
3933       Reg = EndReg;
3934       continue;
3935     }
3936     Parser.Lex(); // Eat the comma.
3937     RegLoc = Parser.getTok().getLoc();
3938     int OldReg = Reg;
3939     Reg = tryParseRegister();
3940     if (Reg == -1) {
3941       Error(RegLoc, "register expected");
3942       return MatchOperand_ParseFail;
3943     }
3944     // vector register lists must be contiguous.
3945     // It's OK to use the enumeration values directly here rather, as the
3946     // VFP register classes have the enum sorted properly.
3947     //
3948     // The list is of D registers, but we also allow Q regs and just interpret
3949     // them as the two D sub-registers.
3950     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3951       if (!Spacing)
3952         Spacing = 1; // Register range implies a single spaced list.
3953       else if (Spacing == 2) {
3954         Error(RegLoc,
3955               "invalid register in double-spaced list (must be 'D' register')");
3956         return MatchOperand_ParseFail;
3957       }
3958       Reg = getDRegFromQReg(Reg);
3959       if (Reg != OldReg + 1) {
3960         Error(RegLoc, "non-contiguous register range");
3961         return MatchOperand_ParseFail;
3962       }
3963       ++Reg;
3964       Count += 2;
3965       // Parse the lane specifier if present.
3966       VectorLaneTy NextLaneKind;
3967       unsigned NextLaneIndex;
3968       SMLoc LaneLoc = Parser.getTok().getLoc();
3969       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3970           MatchOperand_Success)
3971         return MatchOperand_ParseFail;
3972       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3973         Error(LaneLoc, "mismatched lane index in register list");
3974         return MatchOperand_ParseFail;
3975       }
3976       continue;
3977     }
3978     // Normal D register.
3979     // Figure out the register spacing (single or double) of the list if
3980     // we don't know it already.
3981     if (!Spacing)
3982       Spacing = 1 + (Reg == OldReg + 2);
3983 
3984     // Just check that it's contiguous and keep going.
3985     if (Reg != OldReg + Spacing) {
3986       Error(RegLoc, "non-contiguous register range");
3987       return MatchOperand_ParseFail;
3988     }
3989     ++Count;
3990     // Parse the lane specifier if present.
3991     VectorLaneTy NextLaneKind;
3992     unsigned NextLaneIndex;
3993     SMLoc EndLoc = Parser.getTok().getLoc();
3994     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
3995       return MatchOperand_ParseFail;
3996     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3997       Error(EndLoc, "mismatched lane index in register list");
3998       return MatchOperand_ParseFail;
3999     }
4000   }
4001 
4002   if (Parser.getTok().isNot(AsmToken::RCurly)) {
4003     Error(Parser.getTok().getLoc(), "'}' expected");
4004     return MatchOperand_ParseFail;
4005   }
4006   E = Parser.getTok().getEndLoc();
4007   Parser.Lex(); // Eat '}' token.
4008 
4009   switch (LaneKind) {
4010   case NoLanes:
4011     // Two-register operands have been converted to the
4012     // composite register classes.
4013     if (Count == 2) {
4014       const MCRegisterClass *RC = (Spacing == 1) ?
4015         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
4016         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
4017       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
4018     }
4019 
4020     Operands.push_back(ARMOperand::CreateVectorList(FirstReg, Count,
4021                                                     (Spacing == 2), S, E));
4022     break;
4023   case AllLanes:
4024     // Two-register operands have been converted to the
4025     // composite register classes.
4026     if (Count == 2) {
4027       const MCRegisterClass *RC = (Spacing == 1) ?
4028         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
4029         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
4030       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
4031     }
4032     Operands.push_back(ARMOperand::CreateVectorListAllLanes(FirstReg, Count,
4033                                                             (Spacing == 2),
4034                                                             S, E));
4035     break;
4036   case IndexedLane:
4037     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
4038                                                            LaneIndex,
4039                                                            (Spacing == 2),
4040                                                            S, E));
4041     break;
4042   }
4043   return MatchOperand_Success;
4044 }
4045 
4046 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
4047 OperandMatchResultTy
4048 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
4049   MCAsmParser &Parser = getParser();
4050   SMLoc S = Parser.getTok().getLoc();
4051   const AsmToken &Tok = Parser.getTok();
4052   unsigned Opt;
4053 
4054   if (Tok.is(AsmToken::Identifier)) {
4055     StringRef OptStr = Tok.getString();
4056 
4057     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
4058       .Case("sy",    ARM_MB::SY)
4059       .Case("st",    ARM_MB::ST)
4060       .Case("ld",    ARM_MB::LD)
4061       .Case("sh",    ARM_MB::ISH)
4062       .Case("ish",   ARM_MB::ISH)
4063       .Case("shst",  ARM_MB::ISHST)
4064       .Case("ishst", ARM_MB::ISHST)
4065       .Case("ishld", ARM_MB::ISHLD)
4066       .Case("nsh",   ARM_MB::NSH)
4067       .Case("un",    ARM_MB::NSH)
4068       .Case("nshst", ARM_MB::NSHST)
4069       .Case("nshld", ARM_MB::NSHLD)
4070       .Case("unst",  ARM_MB::NSHST)
4071       .Case("osh",   ARM_MB::OSH)
4072       .Case("oshst", ARM_MB::OSHST)
4073       .Case("oshld", ARM_MB::OSHLD)
4074       .Default(~0U);
4075 
4076     // ishld, oshld, nshld and ld are only available from ARMv8.
4077     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
4078                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
4079       Opt = ~0U;
4080 
4081     if (Opt == ~0U)
4082       return MatchOperand_NoMatch;
4083 
4084     Parser.Lex(); // Eat identifier token.
4085   } else if (Tok.is(AsmToken::Hash) ||
4086              Tok.is(AsmToken::Dollar) ||
4087              Tok.is(AsmToken::Integer)) {
4088     if (Parser.getTok().isNot(AsmToken::Integer))
4089       Parser.Lex(); // Eat '#' or '$'.
4090     SMLoc Loc = Parser.getTok().getLoc();
4091 
4092     const MCExpr *MemBarrierID;
4093     if (getParser().parseExpression(MemBarrierID)) {
4094       Error(Loc, "illegal expression");
4095       return MatchOperand_ParseFail;
4096     }
4097 
4098     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
4099     if (!CE) {
4100       Error(Loc, "constant expression expected");
4101       return MatchOperand_ParseFail;
4102     }
4103 
4104     int Val = CE->getValue();
4105     if (Val & ~0xf) {
4106       Error(Loc, "immediate value out of range");
4107       return MatchOperand_ParseFail;
4108     }
4109 
4110     Opt = ARM_MB::RESERVED_0 + Val;
4111   } else
4112     return MatchOperand_ParseFail;
4113 
4114   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
4115   return MatchOperand_Success;
4116 }
4117 
4118 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
4119 OperandMatchResultTy
4120 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
4121   MCAsmParser &Parser = getParser();
4122   SMLoc S = Parser.getTok().getLoc();
4123   const AsmToken &Tok = Parser.getTok();
4124   unsigned Opt;
4125 
4126   if (Tok.is(AsmToken::Identifier)) {
4127     StringRef OptStr = Tok.getString();
4128 
4129     if (OptStr.equals_lower("sy"))
4130       Opt = ARM_ISB::SY;
4131     else
4132       return MatchOperand_NoMatch;
4133 
4134     Parser.Lex(); // Eat identifier token.
4135   } else if (Tok.is(AsmToken::Hash) ||
4136              Tok.is(AsmToken::Dollar) ||
4137              Tok.is(AsmToken::Integer)) {
4138     if (Parser.getTok().isNot(AsmToken::Integer))
4139       Parser.Lex(); // Eat '#' or '$'.
4140     SMLoc Loc = Parser.getTok().getLoc();
4141 
4142     const MCExpr *ISBarrierID;
4143     if (getParser().parseExpression(ISBarrierID)) {
4144       Error(Loc, "illegal expression");
4145       return MatchOperand_ParseFail;
4146     }
4147 
4148     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
4149     if (!CE) {
4150       Error(Loc, "constant expression expected");
4151       return MatchOperand_ParseFail;
4152     }
4153 
4154     int Val = CE->getValue();
4155     if (Val & ~0xf) {
4156       Error(Loc, "immediate value out of range");
4157       return MatchOperand_ParseFail;
4158     }
4159 
4160     Opt = ARM_ISB::RESERVED_0 + Val;
4161   } else
4162     return MatchOperand_ParseFail;
4163 
4164   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
4165           (ARM_ISB::InstSyncBOpt)Opt, S));
4166   return MatchOperand_Success;
4167 }
4168 
4169 
4170 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
4171 OperandMatchResultTy
4172 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
4173   MCAsmParser &Parser = getParser();
4174   SMLoc S = Parser.getTok().getLoc();
4175   const AsmToken &Tok = Parser.getTok();
4176   if (!Tok.is(AsmToken::Identifier))
4177     return MatchOperand_NoMatch;
4178   StringRef IFlagsStr = Tok.getString();
4179 
4180   // An iflags string of "none" is interpreted to mean that none of the AIF
4181   // bits are set.  Not a terribly useful instruction, but a valid encoding.
4182   unsigned IFlags = 0;
4183   if (IFlagsStr != "none") {
4184         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
4185       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1))
4186         .Case("a", ARM_PROC::A)
4187         .Case("i", ARM_PROC::I)
4188         .Case("f", ARM_PROC::F)
4189         .Default(~0U);
4190 
4191       // If some specific iflag is already set, it means that some letter is
4192       // present more than once, this is not acceptable.
4193       if (Flag == ~0U || (IFlags & Flag))
4194         return MatchOperand_NoMatch;
4195 
4196       IFlags |= Flag;
4197     }
4198   }
4199 
4200   Parser.Lex(); // Eat identifier token.
4201   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
4202   return MatchOperand_Success;
4203 }
4204 
4205 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
4206 OperandMatchResultTy
4207 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
4208   MCAsmParser &Parser = getParser();
4209   SMLoc S = Parser.getTok().getLoc();
4210   const AsmToken &Tok = Parser.getTok();
4211   if (!Tok.is(AsmToken::Identifier))
4212     return MatchOperand_NoMatch;
4213   StringRef Mask = Tok.getString();
4214 
4215   if (isMClass()) {
4216     // See ARMv6-M 10.1.1
4217     std::string Name = Mask.lower();
4218     unsigned FlagsVal = StringSwitch<unsigned>(Name)
4219       // Note: in the documentation:
4220       //  ARM deprecates using MSR APSR without a _<bits> qualifier as an alias
4221       //  for MSR APSR_nzcvq.
4222       // but we do make it an alias here.  This is so to get the "mask encoding"
4223       // bits correct on MSR APSR writes.
4224       //
4225       // FIXME: Note the 0xc00 "mask encoding" bits version of the registers
4226       // should really only be allowed when writing a special register.  Note
4227       // they get dropped in the MRS instruction reading a special register as
4228       // the SYSm field is only 8 bits.
4229       .Case("apsr", 0x800)
4230       .Case("apsr_nzcvq", 0x800)
4231       .Case("apsr_g", 0x400)
4232       .Case("apsr_nzcvqg", 0xc00)
4233       .Case("iapsr", 0x801)
4234       .Case("iapsr_nzcvq", 0x801)
4235       .Case("iapsr_g", 0x401)
4236       .Case("iapsr_nzcvqg", 0xc01)
4237       .Case("eapsr", 0x802)
4238       .Case("eapsr_nzcvq", 0x802)
4239       .Case("eapsr_g", 0x402)
4240       .Case("eapsr_nzcvqg", 0xc02)
4241       .Case("xpsr", 0x803)
4242       .Case("xpsr_nzcvq", 0x803)
4243       .Case("xpsr_g", 0x403)
4244       .Case("xpsr_nzcvqg", 0xc03)
4245       .Case("ipsr", 0x805)
4246       .Case("epsr", 0x806)
4247       .Case("iepsr", 0x807)
4248       .Case("msp", 0x808)
4249       .Case("psp", 0x809)
4250       .Case("primask", 0x810)
4251       .Case("basepri", 0x811)
4252       .Case("basepri_max", 0x812)
4253       .Case("faultmask", 0x813)
4254       .Case("control", 0x814)
4255       .Case("msplim", 0x80a)
4256       .Case("psplim", 0x80b)
4257       .Case("msp_ns", 0x888)
4258       .Case("psp_ns", 0x889)
4259       .Case("msplim_ns", 0x88a)
4260       .Case("psplim_ns", 0x88b)
4261       .Case("primask_ns", 0x890)
4262       .Case("basepri_ns", 0x891)
4263       .Case("basepri_max_ns", 0x892)
4264       .Case("faultmask_ns", 0x893)
4265       .Case("control_ns", 0x894)
4266       .Case("sp_ns", 0x898)
4267       .Default(~0U);
4268 
4269     if (FlagsVal == ~0U)
4270       return MatchOperand_NoMatch;
4271 
4272     if (!hasDSP() && (FlagsVal & 0x400))
4273       // The _g and _nzcvqg versions are only valid if the DSP extension is
4274       // available.
4275       return MatchOperand_NoMatch;
4276 
4277     if (!hasV7Ops() && FlagsVal >= 0x811 && FlagsVal <= 0x813)
4278       // basepri, basepri_max and faultmask only valid for V7m.
4279       return MatchOperand_NoMatch;
4280 
4281     if (!has8MSecExt() && (FlagsVal == 0x80a || FlagsVal == 0x80b ||
4282                              (FlagsVal > 0x814 && FlagsVal < 0xc00)))
4283       return MatchOperand_NoMatch;
4284 
4285     if (!hasV8MMainline() && (FlagsVal == 0x88a || FlagsVal == 0x88b ||
4286                               (FlagsVal > 0x890 && FlagsVal <= 0x893)))
4287       return MatchOperand_NoMatch;
4288 
4289     Parser.Lex(); // Eat identifier token.
4290     Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4291     return MatchOperand_Success;
4292   }
4293 
4294   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
4295   size_t Start = 0, Next = Mask.find('_');
4296   StringRef Flags = "";
4297   std::string SpecReg = Mask.slice(Start, Next).lower();
4298   if (Next != StringRef::npos)
4299     Flags = Mask.slice(Next+1, Mask.size());
4300 
4301   // FlagsVal contains the complete mask:
4302   // 3-0: Mask
4303   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4304   unsigned FlagsVal = 0;
4305 
4306   if (SpecReg == "apsr") {
4307     FlagsVal = StringSwitch<unsigned>(Flags)
4308     .Case("nzcvq",  0x8) // same as CPSR_f
4309     .Case("g",      0x4) // same as CPSR_s
4310     .Case("nzcvqg", 0xc) // same as CPSR_fs
4311     .Default(~0U);
4312 
4313     if (FlagsVal == ~0U) {
4314       if (!Flags.empty())
4315         return MatchOperand_NoMatch;
4316       else
4317         FlagsVal = 8; // No flag
4318     }
4319   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
4320     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
4321     if (Flags == "all" || Flags == "")
4322       Flags = "fc";
4323     for (int i = 0, e = Flags.size(); i != e; ++i) {
4324       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
4325       .Case("c", 1)
4326       .Case("x", 2)
4327       .Case("s", 4)
4328       .Case("f", 8)
4329       .Default(~0U);
4330 
4331       // If some specific flag is already set, it means that some letter is
4332       // present more than once, this is not acceptable.
4333       if (Flag == ~0U || (FlagsVal & Flag))
4334         return MatchOperand_NoMatch;
4335       FlagsVal |= Flag;
4336     }
4337   } else // No match for special register.
4338     return MatchOperand_NoMatch;
4339 
4340   // Special register without flags is NOT equivalent to "fc" flags.
4341   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
4342   // two lines would enable gas compatibility at the expense of breaking
4343   // round-tripping.
4344   //
4345   // if (!FlagsVal)
4346   //  FlagsVal = 0x9;
4347 
4348   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4349   if (SpecReg == "spsr")
4350     FlagsVal |= 16;
4351 
4352   Parser.Lex(); // Eat identifier token.
4353   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4354   return MatchOperand_Success;
4355 }
4356 
4357 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
4358 /// use in the MRS/MSR instructions added to support virtualization.
4359 OperandMatchResultTy
4360 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
4361   MCAsmParser &Parser = getParser();
4362   SMLoc S = Parser.getTok().getLoc();
4363   const AsmToken &Tok = Parser.getTok();
4364   if (!Tok.is(AsmToken::Identifier))
4365     return MatchOperand_NoMatch;
4366   StringRef RegName = Tok.getString();
4367 
4368   // The values here come from B9.2.3 of the ARM ARM, where bits 4-0 are SysM
4369   // and bit 5 is R.
4370   unsigned Encoding = StringSwitch<unsigned>(RegName.lower())
4371                           .Case("r8_usr", 0x00)
4372                           .Case("r9_usr", 0x01)
4373                           .Case("r10_usr", 0x02)
4374                           .Case("r11_usr", 0x03)
4375                           .Case("r12_usr", 0x04)
4376                           .Case("sp_usr", 0x05)
4377                           .Case("lr_usr", 0x06)
4378                           .Case("r8_fiq", 0x08)
4379                           .Case("r9_fiq", 0x09)
4380                           .Case("r10_fiq", 0x0a)
4381                           .Case("r11_fiq", 0x0b)
4382                           .Case("r12_fiq", 0x0c)
4383                           .Case("sp_fiq", 0x0d)
4384                           .Case("lr_fiq", 0x0e)
4385                           .Case("lr_irq", 0x10)
4386                           .Case("sp_irq", 0x11)
4387                           .Case("lr_svc", 0x12)
4388                           .Case("sp_svc", 0x13)
4389                           .Case("lr_abt", 0x14)
4390                           .Case("sp_abt", 0x15)
4391                           .Case("lr_und", 0x16)
4392                           .Case("sp_und", 0x17)
4393                           .Case("lr_mon", 0x1c)
4394                           .Case("sp_mon", 0x1d)
4395                           .Case("elr_hyp", 0x1e)
4396                           .Case("sp_hyp", 0x1f)
4397                           .Case("spsr_fiq", 0x2e)
4398                           .Case("spsr_irq", 0x30)
4399                           .Case("spsr_svc", 0x32)
4400                           .Case("spsr_abt", 0x34)
4401                           .Case("spsr_und", 0x36)
4402                           .Case("spsr_mon", 0x3c)
4403                           .Case("spsr_hyp", 0x3e)
4404                           .Default(~0U);
4405 
4406   if (Encoding == ~0U)
4407     return MatchOperand_NoMatch;
4408 
4409   Parser.Lex(); // Eat identifier token.
4410   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
4411   return MatchOperand_Success;
4412 }
4413 
4414 OperandMatchResultTy
4415 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
4416                           int High) {
4417   MCAsmParser &Parser = getParser();
4418   const AsmToken &Tok = Parser.getTok();
4419   if (Tok.isNot(AsmToken::Identifier)) {
4420     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4421     return MatchOperand_ParseFail;
4422   }
4423   StringRef ShiftName = Tok.getString();
4424   std::string LowerOp = Op.lower();
4425   std::string UpperOp = Op.upper();
4426   if (ShiftName != LowerOp && ShiftName != UpperOp) {
4427     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4428     return MatchOperand_ParseFail;
4429   }
4430   Parser.Lex(); // Eat shift type token.
4431 
4432   // There must be a '#' and a shift amount.
4433   if (Parser.getTok().isNot(AsmToken::Hash) &&
4434       Parser.getTok().isNot(AsmToken::Dollar)) {
4435     Error(Parser.getTok().getLoc(), "'#' expected");
4436     return MatchOperand_ParseFail;
4437   }
4438   Parser.Lex(); // Eat hash token.
4439 
4440   const MCExpr *ShiftAmount;
4441   SMLoc Loc = Parser.getTok().getLoc();
4442   SMLoc EndLoc;
4443   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4444     Error(Loc, "illegal expression");
4445     return MatchOperand_ParseFail;
4446   }
4447   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4448   if (!CE) {
4449     Error(Loc, "constant expression expected");
4450     return MatchOperand_ParseFail;
4451   }
4452   int Val = CE->getValue();
4453   if (Val < Low || Val > High) {
4454     Error(Loc, "immediate value out of range");
4455     return MatchOperand_ParseFail;
4456   }
4457 
4458   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
4459 
4460   return MatchOperand_Success;
4461 }
4462 
4463 OperandMatchResultTy
4464 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
4465   MCAsmParser &Parser = getParser();
4466   const AsmToken &Tok = Parser.getTok();
4467   SMLoc S = Tok.getLoc();
4468   if (Tok.isNot(AsmToken::Identifier)) {
4469     Error(S, "'be' or 'le' operand expected");
4470     return MatchOperand_ParseFail;
4471   }
4472   int Val = StringSwitch<int>(Tok.getString().lower())
4473     .Case("be", 1)
4474     .Case("le", 0)
4475     .Default(-1);
4476   Parser.Lex(); // Eat the token.
4477 
4478   if (Val == -1) {
4479     Error(S, "'be' or 'le' operand expected");
4480     return MatchOperand_ParseFail;
4481   }
4482   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
4483                                                                   getContext()),
4484                                            S, Tok.getEndLoc()));
4485   return MatchOperand_Success;
4486 }
4487 
4488 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
4489 /// instructions. Legal values are:
4490 ///     lsl #n  'n' in [0,31]
4491 ///     asr #n  'n' in [1,32]
4492 ///             n == 32 encoded as n == 0.
4493 OperandMatchResultTy
4494 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
4495   MCAsmParser &Parser = getParser();
4496   const AsmToken &Tok = Parser.getTok();
4497   SMLoc S = Tok.getLoc();
4498   if (Tok.isNot(AsmToken::Identifier)) {
4499     Error(S, "shift operator 'asr' or 'lsl' expected");
4500     return MatchOperand_ParseFail;
4501   }
4502   StringRef ShiftName = Tok.getString();
4503   bool isASR;
4504   if (ShiftName == "lsl" || ShiftName == "LSL")
4505     isASR = false;
4506   else if (ShiftName == "asr" || ShiftName == "ASR")
4507     isASR = true;
4508   else {
4509     Error(S, "shift operator 'asr' or 'lsl' expected");
4510     return MatchOperand_ParseFail;
4511   }
4512   Parser.Lex(); // Eat the operator.
4513 
4514   // A '#' and a shift amount.
4515   if (Parser.getTok().isNot(AsmToken::Hash) &&
4516       Parser.getTok().isNot(AsmToken::Dollar)) {
4517     Error(Parser.getTok().getLoc(), "'#' expected");
4518     return MatchOperand_ParseFail;
4519   }
4520   Parser.Lex(); // Eat hash token.
4521   SMLoc ExLoc = Parser.getTok().getLoc();
4522 
4523   const MCExpr *ShiftAmount;
4524   SMLoc EndLoc;
4525   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4526     Error(ExLoc, "malformed shift expression");
4527     return MatchOperand_ParseFail;
4528   }
4529   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4530   if (!CE) {
4531     Error(ExLoc, "shift amount must be an immediate");
4532     return MatchOperand_ParseFail;
4533   }
4534 
4535   int64_t Val = CE->getValue();
4536   if (isASR) {
4537     // Shift amount must be in [1,32]
4538     if (Val < 1 || Val > 32) {
4539       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
4540       return MatchOperand_ParseFail;
4541     }
4542     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
4543     if (isThumb() && Val == 32) {
4544       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
4545       return MatchOperand_ParseFail;
4546     }
4547     if (Val == 32) Val = 0;
4548   } else {
4549     // Shift amount must be in [1,32]
4550     if (Val < 0 || Val > 31) {
4551       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
4552       return MatchOperand_ParseFail;
4553     }
4554   }
4555 
4556   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
4557 
4558   return MatchOperand_Success;
4559 }
4560 
4561 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
4562 /// of instructions. Legal values are:
4563 ///     ror #n  'n' in {0, 8, 16, 24}
4564 OperandMatchResultTy
4565 ARMAsmParser::parseRotImm(OperandVector &Operands) {
4566   MCAsmParser &Parser = getParser();
4567   const AsmToken &Tok = Parser.getTok();
4568   SMLoc S = Tok.getLoc();
4569   if (Tok.isNot(AsmToken::Identifier))
4570     return MatchOperand_NoMatch;
4571   StringRef ShiftName = Tok.getString();
4572   if (ShiftName != "ror" && ShiftName != "ROR")
4573     return MatchOperand_NoMatch;
4574   Parser.Lex(); // Eat the operator.
4575 
4576   // A '#' and a rotate amount.
4577   if (Parser.getTok().isNot(AsmToken::Hash) &&
4578       Parser.getTok().isNot(AsmToken::Dollar)) {
4579     Error(Parser.getTok().getLoc(), "'#' expected");
4580     return MatchOperand_ParseFail;
4581   }
4582   Parser.Lex(); // Eat hash token.
4583   SMLoc ExLoc = Parser.getTok().getLoc();
4584 
4585   const MCExpr *ShiftAmount;
4586   SMLoc EndLoc;
4587   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4588     Error(ExLoc, "malformed rotate expression");
4589     return MatchOperand_ParseFail;
4590   }
4591   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4592   if (!CE) {
4593     Error(ExLoc, "rotate amount must be an immediate");
4594     return MatchOperand_ParseFail;
4595   }
4596 
4597   int64_t Val = CE->getValue();
4598   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
4599   // normally, zero is represented in asm by omitting the rotate operand
4600   // entirely.
4601   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
4602     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
4603     return MatchOperand_ParseFail;
4604   }
4605 
4606   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
4607 
4608   return MatchOperand_Success;
4609 }
4610 
4611 OperandMatchResultTy
4612 ARMAsmParser::parseModImm(OperandVector &Operands) {
4613   MCAsmParser &Parser = getParser();
4614   MCAsmLexer &Lexer = getLexer();
4615   int64_t Imm1, Imm2;
4616 
4617   SMLoc S = Parser.getTok().getLoc();
4618 
4619   // 1) A mod_imm operand can appear in the place of a register name:
4620   //   add r0, #mod_imm
4621   //   add r0, r0, #mod_imm
4622   // to correctly handle the latter, we bail out as soon as we see an
4623   // identifier.
4624   //
4625   // 2) Similarly, we do not want to parse into complex operands:
4626   //   mov r0, #mod_imm
4627   //   mov r0, :lower16:(_foo)
4628   if (Parser.getTok().is(AsmToken::Identifier) ||
4629       Parser.getTok().is(AsmToken::Colon))
4630     return MatchOperand_NoMatch;
4631 
4632   // Hash (dollar) is optional as per the ARMARM
4633   if (Parser.getTok().is(AsmToken::Hash) ||
4634       Parser.getTok().is(AsmToken::Dollar)) {
4635     // Avoid parsing into complex operands (#:)
4636     if (Lexer.peekTok().is(AsmToken::Colon))
4637       return MatchOperand_NoMatch;
4638 
4639     // Eat the hash (dollar)
4640     Parser.Lex();
4641   }
4642 
4643   SMLoc Sx1, Ex1;
4644   Sx1 = Parser.getTok().getLoc();
4645   const MCExpr *Imm1Exp;
4646   if (getParser().parseExpression(Imm1Exp, Ex1)) {
4647     Error(Sx1, "malformed expression");
4648     return MatchOperand_ParseFail;
4649   }
4650 
4651   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
4652 
4653   if (CE) {
4654     // Immediate must fit within 32-bits
4655     Imm1 = CE->getValue();
4656     int Enc = ARM_AM::getSOImmVal(Imm1);
4657     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
4658       // We have a match!
4659       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
4660                                                   (Enc & 0xF00) >> 7,
4661                                                   Sx1, Ex1));
4662       return MatchOperand_Success;
4663     }
4664 
4665     // We have parsed an immediate which is not for us, fallback to a plain
4666     // immediate. This can happen for instruction aliases. For an example,
4667     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
4668     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
4669     // instruction with a mod_imm operand. The alias is defined such that the
4670     // parser method is shared, that's why we have to do this here.
4671     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
4672       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4673       return MatchOperand_Success;
4674     }
4675   } else {
4676     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
4677     // MCFixup). Fallback to a plain immediate.
4678     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4679     return MatchOperand_Success;
4680   }
4681 
4682   // From this point onward, we expect the input to be a (#bits, #rot) pair
4683   if (Parser.getTok().isNot(AsmToken::Comma)) {
4684     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
4685     return MatchOperand_ParseFail;
4686   }
4687 
4688   if (Imm1 & ~0xFF) {
4689     Error(Sx1, "immediate operand must a number in the range [0, 255]");
4690     return MatchOperand_ParseFail;
4691   }
4692 
4693   // Eat the comma
4694   Parser.Lex();
4695 
4696   // Repeat for #rot
4697   SMLoc Sx2, Ex2;
4698   Sx2 = Parser.getTok().getLoc();
4699 
4700   // Eat the optional hash (dollar)
4701   if (Parser.getTok().is(AsmToken::Hash) ||
4702       Parser.getTok().is(AsmToken::Dollar))
4703     Parser.Lex();
4704 
4705   const MCExpr *Imm2Exp;
4706   if (getParser().parseExpression(Imm2Exp, Ex2)) {
4707     Error(Sx2, "malformed expression");
4708     return MatchOperand_ParseFail;
4709   }
4710 
4711   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
4712 
4713   if (CE) {
4714     Imm2 = CE->getValue();
4715     if (!(Imm2 & ~0x1E)) {
4716       // We have a match!
4717       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
4718       return MatchOperand_Success;
4719     }
4720     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
4721     return MatchOperand_ParseFail;
4722   } else {
4723     Error(Sx2, "constant expression expected");
4724     return MatchOperand_ParseFail;
4725   }
4726 }
4727 
4728 OperandMatchResultTy
4729 ARMAsmParser::parseBitfield(OperandVector &Operands) {
4730   MCAsmParser &Parser = getParser();
4731   SMLoc S = Parser.getTok().getLoc();
4732   // The bitfield descriptor is really two operands, the LSB and the width.
4733   if (Parser.getTok().isNot(AsmToken::Hash) &&
4734       Parser.getTok().isNot(AsmToken::Dollar)) {
4735     Error(Parser.getTok().getLoc(), "'#' expected");
4736     return MatchOperand_ParseFail;
4737   }
4738   Parser.Lex(); // Eat hash token.
4739 
4740   const MCExpr *LSBExpr;
4741   SMLoc E = Parser.getTok().getLoc();
4742   if (getParser().parseExpression(LSBExpr)) {
4743     Error(E, "malformed immediate expression");
4744     return MatchOperand_ParseFail;
4745   }
4746   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
4747   if (!CE) {
4748     Error(E, "'lsb' operand must be an immediate");
4749     return MatchOperand_ParseFail;
4750   }
4751 
4752   int64_t LSB = CE->getValue();
4753   // The LSB must be in the range [0,31]
4754   if (LSB < 0 || LSB > 31) {
4755     Error(E, "'lsb' operand must be in the range [0,31]");
4756     return MatchOperand_ParseFail;
4757   }
4758   E = Parser.getTok().getLoc();
4759 
4760   // Expect another immediate operand.
4761   if (Parser.getTok().isNot(AsmToken::Comma)) {
4762     Error(Parser.getTok().getLoc(), "too few operands");
4763     return MatchOperand_ParseFail;
4764   }
4765   Parser.Lex(); // Eat hash token.
4766   if (Parser.getTok().isNot(AsmToken::Hash) &&
4767       Parser.getTok().isNot(AsmToken::Dollar)) {
4768     Error(Parser.getTok().getLoc(), "'#' expected");
4769     return MatchOperand_ParseFail;
4770   }
4771   Parser.Lex(); // Eat hash token.
4772 
4773   const MCExpr *WidthExpr;
4774   SMLoc EndLoc;
4775   if (getParser().parseExpression(WidthExpr, EndLoc)) {
4776     Error(E, "malformed immediate expression");
4777     return MatchOperand_ParseFail;
4778   }
4779   CE = dyn_cast<MCConstantExpr>(WidthExpr);
4780   if (!CE) {
4781     Error(E, "'width' operand must be an immediate");
4782     return MatchOperand_ParseFail;
4783   }
4784 
4785   int64_t Width = CE->getValue();
4786   // The LSB must be in the range [1,32-lsb]
4787   if (Width < 1 || Width > 32 - LSB) {
4788     Error(E, "'width' operand must be in the range [1,32-lsb]");
4789     return MatchOperand_ParseFail;
4790   }
4791 
4792   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
4793 
4794   return MatchOperand_Success;
4795 }
4796 
4797 OperandMatchResultTy
4798 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
4799   // Check for a post-index addressing register operand. Specifically:
4800   // postidx_reg := '+' register {, shift}
4801   //              | '-' register {, shift}
4802   //              | register {, shift}
4803 
4804   // This method must return MatchOperand_NoMatch without consuming any tokens
4805   // in the case where there is no match, as other alternatives take other
4806   // parse methods.
4807   MCAsmParser &Parser = getParser();
4808   AsmToken Tok = Parser.getTok();
4809   SMLoc S = Tok.getLoc();
4810   bool haveEaten = false;
4811   bool isAdd = true;
4812   if (Tok.is(AsmToken::Plus)) {
4813     Parser.Lex(); // Eat the '+' token.
4814     haveEaten = true;
4815   } else if (Tok.is(AsmToken::Minus)) {
4816     Parser.Lex(); // Eat the '-' token.
4817     isAdd = false;
4818     haveEaten = true;
4819   }
4820 
4821   SMLoc E = Parser.getTok().getEndLoc();
4822   int Reg = tryParseRegister();
4823   if (Reg == -1) {
4824     if (!haveEaten)
4825       return MatchOperand_NoMatch;
4826     Error(Parser.getTok().getLoc(), "register expected");
4827     return MatchOperand_ParseFail;
4828   }
4829 
4830   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
4831   unsigned ShiftImm = 0;
4832   if (Parser.getTok().is(AsmToken::Comma)) {
4833     Parser.Lex(); // Eat the ','.
4834     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
4835       return MatchOperand_ParseFail;
4836 
4837     // FIXME: Only approximates end...may include intervening whitespace.
4838     E = Parser.getTok().getLoc();
4839   }
4840 
4841   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
4842                                                   ShiftImm, S, E));
4843 
4844   return MatchOperand_Success;
4845 }
4846 
4847 OperandMatchResultTy
4848 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
4849   // Check for a post-index addressing register operand. Specifically:
4850   // am3offset := '+' register
4851   //              | '-' register
4852   //              | register
4853   //              | # imm
4854   //              | # + imm
4855   //              | # - imm
4856 
4857   // This method must return MatchOperand_NoMatch without consuming any tokens
4858   // in the case where there is no match, as other alternatives take other
4859   // parse methods.
4860   MCAsmParser &Parser = getParser();
4861   AsmToken Tok = Parser.getTok();
4862   SMLoc S = Tok.getLoc();
4863 
4864   // Do immediates first, as we always parse those if we have a '#'.
4865   if (Parser.getTok().is(AsmToken::Hash) ||
4866       Parser.getTok().is(AsmToken::Dollar)) {
4867     Parser.Lex(); // Eat '#' or '$'.
4868     // Explicitly look for a '-', as we need to encode negative zero
4869     // differently.
4870     bool isNegative = Parser.getTok().is(AsmToken::Minus);
4871     const MCExpr *Offset;
4872     SMLoc E;
4873     if (getParser().parseExpression(Offset, E))
4874       return MatchOperand_ParseFail;
4875     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4876     if (!CE) {
4877       Error(S, "constant expression expected");
4878       return MatchOperand_ParseFail;
4879     }
4880     // Negative zero is encoded as the flag value INT32_MIN.
4881     int32_t Val = CE->getValue();
4882     if (isNegative && Val == 0)
4883       Val = INT32_MIN;
4884 
4885     Operands.push_back(
4886       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
4887 
4888     return MatchOperand_Success;
4889   }
4890 
4891 
4892   bool haveEaten = false;
4893   bool isAdd = true;
4894   if (Tok.is(AsmToken::Plus)) {
4895     Parser.Lex(); // Eat the '+' token.
4896     haveEaten = true;
4897   } else if (Tok.is(AsmToken::Minus)) {
4898     Parser.Lex(); // Eat the '-' token.
4899     isAdd = false;
4900     haveEaten = true;
4901   }
4902 
4903   Tok = Parser.getTok();
4904   int Reg = tryParseRegister();
4905   if (Reg == -1) {
4906     if (!haveEaten)
4907       return MatchOperand_NoMatch;
4908     Error(Tok.getLoc(), "register expected");
4909     return MatchOperand_ParseFail;
4910   }
4911 
4912   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
4913                                                   0, S, Tok.getEndLoc()));
4914 
4915   return MatchOperand_Success;
4916 }
4917 
4918 /// Convert parsed operands to MCInst.  Needed here because this instruction
4919 /// only has two register operands, but multiplication is commutative so
4920 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
4921 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
4922                                     const OperandVector &Operands) {
4923   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
4924   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
4925   // If we have a three-operand form, make sure to set Rn to be the operand
4926   // that isn't the same as Rd.
4927   unsigned RegOp = 4;
4928   if (Operands.size() == 6 &&
4929       ((ARMOperand &)*Operands[4]).getReg() ==
4930           ((ARMOperand &)*Operands[3]).getReg())
4931     RegOp = 5;
4932   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
4933   Inst.addOperand(Inst.getOperand(0));
4934   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
4935 }
4936 
4937 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
4938                                     const OperandVector &Operands) {
4939   int CondOp = -1, ImmOp = -1;
4940   switch(Inst.getOpcode()) {
4941     case ARM::tB:
4942     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
4943 
4944     case ARM::t2B:
4945     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
4946 
4947     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
4948   }
4949   // first decide whether or not the branch should be conditional
4950   // by looking at it's location relative to an IT block
4951   if(inITBlock()) {
4952     // inside an IT block we cannot have any conditional branches. any
4953     // such instructions needs to be converted to unconditional form
4954     switch(Inst.getOpcode()) {
4955       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
4956       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
4957     }
4958   } else {
4959     // outside IT blocks we can only have unconditional branches with AL
4960     // condition code or conditional branches with non-AL condition code
4961     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
4962     switch(Inst.getOpcode()) {
4963       case ARM::tB:
4964       case ARM::tBcc:
4965         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc);
4966         break;
4967       case ARM::t2B:
4968       case ARM::t2Bcc:
4969         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
4970         break;
4971     }
4972   }
4973 
4974   // now decide on encoding size based on branch target range
4975   switch(Inst.getOpcode()) {
4976     // classify tB as either t2B or t1B based on range of immediate operand
4977     case ARM::tB: {
4978       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4979       if (!op.isSignedOffset<11, 1>() && isThumb() && hasV8MBaseline())
4980         Inst.setOpcode(ARM::t2B);
4981       break;
4982     }
4983     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
4984     case ARM::tBcc: {
4985       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4986       if (!op.isSignedOffset<8, 1>() && isThumb() && hasV8MBaseline())
4987         Inst.setOpcode(ARM::t2Bcc);
4988       break;
4989     }
4990   }
4991   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
4992   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
4993 }
4994 
4995 /// Parse an ARM memory expression, return false if successful else return true
4996 /// or an error.  The first token must be a '[' when called.
4997 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
4998   MCAsmParser &Parser = getParser();
4999   SMLoc S, E;
5000   if (Parser.getTok().isNot(AsmToken::LBrac))
5001     return TokError("Token is not a Left Bracket");
5002   S = Parser.getTok().getLoc();
5003   Parser.Lex(); // Eat left bracket token.
5004 
5005   const AsmToken &BaseRegTok = Parser.getTok();
5006   int BaseRegNum = tryParseRegister();
5007   if (BaseRegNum == -1)
5008     return Error(BaseRegTok.getLoc(), "register expected");
5009 
5010   // The next token must either be a comma, a colon or a closing bracket.
5011   const AsmToken &Tok = Parser.getTok();
5012   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
5013       !Tok.is(AsmToken::RBrac))
5014     return Error(Tok.getLoc(), "malformed memory operand");
5015 
5016   if (Tok.is(AsmToken::RBrac)) {
5017     E = Tok.getEndLoc();
5018     Parser.Lex(); // Eat right bracket token.
5019 
5020     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5021                                              ARM_AM::no_shift, 0, 0, false,
5022                                              S, E));
5023 
5024     // If there's a pre-indexing writeback marker, '!', just add it as a token
5025     // operand. It's rather odd, but syntactically valid.
5026     if (Parser.getTok().is(AsmToken::Exclaim)) {
5027       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5028       Parser.Lex(); // Eat the '!'.
5029     }
5030 
5031     return false;
5032   }
5033 
5034   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
5035          "Lost colon or comma in memory operand?!");
5036   if (Tok.is(AsmToken::Comma)) {
5037     Parser.Lex(); // Eat the comma.
5038   }
5039 
5040   // If we have a ':', it's an alignment specifier.
5041   if (Parser.getTok().is(AsmToken::Colon)) {
5042     Parser.Lex(); // Eat the ':'.
5043     E = Parser.getTok().getLoc();
5044     SMLoc AlignmentLoc = Tok.getLoc();
5045 
5046     const MCExpr *Expr;
5047     if (getParser().parseExpression(Expr))
5048      return true;
5049 
5050     // The expression has to be a constant. Memory references with relocations
5051     // don't come through here, as they use the <label> forms of the relevant
5052     // instructions.
5053     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5054     if (!CE)
5055       return Error (E, "constant expression expected");
5056 
5057     unsigned Align = 0;
5058     switch (CE->getValue()) {
5059     default:
5060       return Error(E,
5061                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
5062     case 16:  Align = 2; break;
5063     case 32:  Align = 4; break;
5064     case 64:  Align = 8; break;
5065     case 128: Align = 16; break;
5066     case 256: Align = 32; break;
5067     }
5068 
5069     // Now we should have the closing ']'
5070     if (Parser.getTok().isNot(AsmToken::RBrac))
5071       return Error(Parser.getTok().getLoc(), "']' expected");
5072     E = Parser.getTok().getEndLoc();
5073     Parser.Lex(); // Eat right bracket token.
5074 
5075     // Don't worry about range checking the value here. That's handled by
5076     // the is*() predicates.
5077     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5078                                              ARM_AM::no_shift, 0, Align,
5079                                              false, S, E, AlignmentLoc));
5080 
5081     // If there's a pre-indexing writeback marker, '!', just add it as a token
5082     // operand.
5083     if (Parser.getTok().is(AsmToken::Exclaim)) {
5084       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5085       Parser.Lex(); // Eat the '!'.
5086     }
5087 
5088     return false;
5089   }
5090 
5091   // If we have a '#', it's an immediate offset, else assume it's a register
5092   // offset. Be friendly and also accept a plain integer (without a leading
5093   // hash) for gas compatibility.
5094   if (Parser.getTok().is(AsmToken::Hash) ||
5095       Parser.getTok().is(AsmToken::Dollar) ||
5096       Parser.getTok().is(AsmToken::Integer)) {
5097     if (Parser.getTok().isNot(AsmToken::Integer))
5098       Parser.Lex(); // Eat '#' or '$'.
5099     E = Parser.getTok().getLoc();
5100 
5101     bool isNegative = getParser().getTok().is(AsmToken::Minus);
5102     const MCExpr *Offset;
5103     if (getParser().parseExpression(Offset))
5104      return true;
5105 
5106     // The expression has to be a constant. Memory references with relocations
5107     // don't come through here, as they use the <label> forms of the relevant
5108     // instructions.
5109     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
5110     if (!CE)
5111       return Error (E, "constant expression expected");
5112 
5113     // If the constant was #-0, represent it as INT32_MIN.
5114     int32_t Val = CE->getValue();
5115     if (isNegative && Val == 0)
5116       CE = MCConstantExpr::create(INT32_MIN, getContext());
5117 
5118     // Now we should have the closing ']'
5119     if (Parser.getTok().isNot(AsmToken::RBrac))
5120       return Error(Parser.getTok().getLoc(), "']' expected");
5121     E = Parser.getTok().getEndLoc();
5122     Parser.Lex(); // Eat right bracket token.
5123 
5124     // Don't worry about range checking the value here. That's handled by
5125     // the is*() predicates.
5126     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
5127                                              ARM_AM::no_shift, 0, 0,
5128                                              false, S, E));
5129 
5130     // If there's a pre-indexing writeback marker, '!', just add it as a token
5131     // operand.
5132     if (Parser.getTok().is(AsmToken::Exclaim)) {
5133       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5134       Parser.Lex(); // Eat the '!'.
5135     }
5136 
5137     return false;
5138   }
5139 
5140   // The register offset is optionally preceded by a '+' or '-'
5141   bool isNegative = false;
5142   if (Parser.getTok().is(AsmToken::Minus)) {
5143     isNegative = true;
5144     Parser.Lex(); // Eat the '-'.
5145   } else if (Parser.getTok().is(AsmToken::Plus)) {
5146     // Nothing to do.
5147     Parser.Lex(); // Eat the '+'.
5148   }
5149 
5150   E = Parser.getTok().getLoc();
5151   int OffsetRegNum = tryParseRegister();
5152   if (OffsetRegNum == -1)
5153     return Error(E, "register expected");
5154 
5155   // If there's a shift operator, handle it.
5156   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
5157   unsigned ShiftImm = 0;
5158   if (Parser.getTok().is(AsmToken::Comma)) {
5159     Parser.Lex(); // Eat the ','.
5160     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
5161       return true;
5162   }
5163 
5164   // Now we should have the closing ']'
5165   if (Parser.getTok().isNot(AsmToken::RBrac))
5166     return Error(Parser.getTok().getLoc(), "']' expected");
5167   E = Parser.getTok().getEndLoc();
5168   Parser.Lex(); // Eat right bracket token.
5169 
5170   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
5171                                            ShiftType, ShiftImm, 0, isNegative,
5172                                            S, E));
5173 
5174   // If there's a pre-indexing writeback marker, '!', just add it as a token
5175   // operand.
5176   if (Parser.getTok().is(AsmToken::Exclaim)) {
5177     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5178     Parser.Lex(); // Eat the '!'.
5179   }
5180 
5181   return false;
5182 }
5183 
5184 /// parseMemRegOffsetShift - one of these two:
5185 ///   ( lsl | lsr | asr | ror ) , # shift_amount
5186 ///   rrx
5187 /// return true if it parses a shift otherwise it returns false.
5188 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
5189                                           unsigned &Amount) {
5190   MCAsmParser &Parser = getParser();
5191   SMLoc Loc = Parser.getTok().getLoc();
5192   const AsmToken &Tok = Parser.getTok();
5193   if (Tok.isNot(AsmToken::Identifier))
5194     return true;
5195   StringRef ShiftName = Tok.getString();
5196   if (ShiftName == "lsl" || ShiftName == "LSL" ||
5197       ShiftName == "asl" || ShiftName == "ASL")
5198     St = ARM_AM::lsl;
5199   else if (ShiftName == "lsr" || ShiftName == "LSR")
5200     St = ARM_AM::lsr;
5201   else if (ShiftName == "asr" || ShiftName == "ASR")
5202     St = ARM_AM::asr;
5203   else if (ShiftName == "ror" || ShiftName == "ROR")
5204     St = ARM_AM::ror;
5205   else if (ShiftName == "rrx" || ShiftName == "RRX")
5206     St = ARM_AM::rrx;
5207   else
5208     return Error(Loc, "illegal shift operator");
5209   Parser.Lex(); // Eat shift type token.
5210 
5211   // rrx stands alone.
5212   Amount = 0;
5213   if (St != ARM_AM::rrx) {
5214     Loc = Parser.getTok().getLoc();
5215     // A '#' and a shift amount.
5216     const AsmToken &HashTok = Parser.getTok();
5217     if (HashTok.isNot(AsmToken::Hash) &&
5218         HashTok.isNot(AsmToken::Dollar))
5219       return Error(HashTok.getLoc(), "'#' expected");
5220     Parser.Lex(); // Eat hash token.
5221 
5222     const MCExpr *Expr;
5223     if (getParser().parseExpression(Expr))
5224       return true;
5225     // Range check the immediate.
5226     // lsl, ror: 0 <= imm <= 31
5227     // lsr, asr: 0 <= imm <= 32
5228     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5229     if (!CE)
5230       return Error(Loc, "shift amount must be an immediate");
5231     int64_t Imm = CE->getValue();
5232     if (Imm < 0 ||
5233         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
5234         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
5235       return Error(Loc, "immediate shift value out of range");
5236     // If <ShiftTy> #0, turn it into a no_shift.
5237     if (Imm == 0)
5238       St = ARM_AM::lsl;
5239     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
5240     if (Imm == 32)
5241       Imm = 0;
5242     Amount = Imm;
5243   }
5244 
5245   return false;
5246 }
5247 
5248 /// parseFPImm - A floating point immediate expression operand.
5249 OperandMatchResultTy
5250 ARMAsmParser::parseFPImm(OperandVector &Operands) {
5251   MCAsmParser &Parser = getParser();
5252   // Anything that can accept a floating point constant as an operand
5253   // needs to go through here, as the regular parseExpression is
5254   // integer only.
5255   //
5256   // This routine still creates a generic Immediate operand, containing
5257   // a bitcast of the 64-bit floating point value. The various operands
5258   // that accept floats can check whether the value is valid for them
5259   // via the standard is*() predicates.
5260 
5261   SMLoc S = Parser.getTok().getLoc();
5262 
5263   if (Parser.getTok().isNot(AsmToken::Hash) &&
5264       Parser.getTok().isNot(AsmToken::Dollar))
5265     return MatchOperand_NoMatch;
5266 
5267   // Disambiguate the VMOV forms that can accept an FP immediate.
5268   // vmov.f32 <sreg>, #imm
5269   // vmov.f64 <dreg>, #imm
5270   // vmov.f32 <dreg>, #imm  @ vector f32x2
5271   // vmov.f32 <qreg>, #imm  @ vector f32x4
5272   //
5273   // There are also the NEON VMOV instructions which expect an
5274   // integer constant. Make sure we don't try to parse an FPImm
5275   // for these:
5276   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
5277   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
5278   bool isVmovf = TyOp.isToken() &&
5279                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64" ||
5280                   TyOp.getToken() == ".f16");
5281   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
5282   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
5283                                          Mnemonic.getToken() == "fconsts");
5284   if (!(isVmovf || isFconst))
5285     return MatchOperand_NoMatch;
5286 
5287   Parser.Lex(); // Eat '#' or '$'.
5288 
5289   // Handle negation, as that still comes through as a separate token.
5290   bool isNegative = false;
5291   if (Parser.getTok().is(AsmToken::Minus)) {
5292     isNegative = true;
5293     Parser.Lex();
5294   }
5295   const AsmToken &Tok = Parser.getTok();
5296   SMLoc Loc = Tok.getLoc();
5297   if (Tok.is(AsmToken::Real) && isVmovf) {
5298     APFloat RealVal(APFloat::IEEEsingle(), Tok.getString());
5299     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
5300     // If we had a '-' in front, toggle the sign bit.
5301     IntVal ^= (uint64_t)isNegative << 31;
5302     Parser.Lex(); // Eat the token.
5303     Operands.push_back(ARMOperand::CreateImm(
5304           MCConstantExpr::create(IntVal, getContext()),
5305           S, Parser.getTok().getLoc()));
5306     return MatchOperand_Success;
5307   }
5308   // Also handle plain integers. Instructions which allow floating point
5309   // immediates also allow a raw encoded 8-bit value.
5310   if (Tok.is(AsmToken::Integer) && isFconst) {
5311     int64_t Val = Tok.getIntVal();
5312     Parser.Lex(); // Eat the token.
5313     if (Val > 255 || Val < 0) {
5314       Error(Loc, "encoded floating point value out of range");
5315       return MatchOperand_ParseFail;
5316     }
5317     float RealVal = ARM_AM::getFPImmFloat(Val);
5318     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
5319 
5320     Operands.push_back(ARMOperand::CreateImm(
5321         MCConstantExpr::create(Val, getContext()), S,
5322         Parser.getTok().getLoc()));
5323     return MatchOperand_Success;
5324   }
5325 
5326   Error(Loc, "invalid floating point immediate");
5327   return MatchOperand_ParseFail;
5328 }
5329 
5330 /// Parse a arm instruction operand.  For now this parses the operand regardless
5331 /// of the mnemonic.
5332 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
5333   MCAsmParser &Parser = getParser();
5334   SMLoc S, E;
5335 
5336   // Check if the current operand has a custom associated parser, if so, try to
5337   // custom parse the operand, or fallback to the general approach.
5338   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
5339   if (ResTy == MatchOperand_Success)
5340     return false;
5341   // If there wasn't a custom match, try the generic matcher below. Otherwise,
5342   // there was a match, but an error occurred, in which case, just return that
5343   // the operand parsing failed.
5344   if (ResTy == MatchOperand_ParseFail)
5345     return true;
5346 
5347   switch (getLexer().getKind()) {
5348   default:
5349     Error(Parser.getTok().getLoc(), "unexpected token in operand");
5350     return true;
5351   case AsmToken::Identifier: {
5352     // If we've seen a branch mnemonic, the next operand must be a label.  This
5353     // is true even if the label is a register name.  So "br r1" means branch to
5354     // label "r1".
5355     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
5356     if (!ExpectLabel) {
5357       if (!tryParseRegisterWithWriteBack(Operands))
5358         return false;
5359       int Res = tryParseShiftRegister(Operands);
5360       if (Res == 0) // success
5361         return false;
5362       else if (Res == -1) // irrecoverable error
5363         return true;
5364       // If this is VMRS, check for the apsr_nzcv operand.
5365       if (Mnemonic == "vmrs" &&
5366           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
5367         S = Parser.getTok().getLoc();
5368         Parser.Lex();
5369         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
5370         return false;
5371       }
5372     }
5373 
5374     // Fall though for the Identifier case that is not a register or a
5375     // special name.
5376   }
5377   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
5378   case AsmToken::Integer: // things like 1f and 2b as a branch targets
5379   case AsmToken::String:  // quoted label names.
5380   case AsmToken::Dot: {   // . as a branch target
5381     // This was not a register so parse other operands that start with an
5382     // identifier (like labels) as expressions and create them as immediates.
5383     const MCExpr *IdVal;
5384     S = Parser.getTok().getLoc();
5385     if (getParser().parseExpression(IdVal))
5386       return true;
5387     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5388     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
5389     return false;
5390   }
5391   case AsmToken::LBrac:
5392     return parseMemory(Operands);
5393   case AsmToken::LCurly:
5394     return parseRegisterList(Operands);
5395   case AsmToken::Dollar:
5396   case AsmToken::Hash: {
5397     // #42 -> immediate.
5398     S = Parser.getTok().getLoc();
5399     Parser.Lex();
5400 
5401     if (Parser.getTok().isNot(AsmToken::Colon)) {
5402       bool isNegative = Parser.getTok().is(AsmToken::Minus);
5403       const MCExpr *ImmVal;
5404       if (getParser().parseExpression(ImmVal))
5405         return true;
5406       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
5407       if (CE) {
5408         int32_t Val = CE->getValue();
5409         if (isNegative && Val == 0)
5410           ImmVal = MCConstantExpr::create(INT32_MIN, getContext());
5411       }
5412       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5413       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
5414 
5415       // There can be a trailing '!' on operands that we want as a separate
5416       // '!' Token operand. Handle that here. For example, the compatibility
5417       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
5418       if (Parser.getTok().is(AsmToken::Exclaim)) {
5419         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
5420                                                    Parser.getTok().getLoc()));
5421         Parser.Lex(); // Eat exclaim token
5422       }
5423       return false;
5424     }
5425     // w/ a ':' after the '#', it's just like a plain ':'.
5426     LLVM_FALLTHROUGH;
5427   }
5428   case AsmToken::Colon: {
5429     S = Parser.getTok().getLoc();
5430     // ":lower16:" and ":upper16:" expression prefixes
5431     // FIXME: Check it's an expression prefix,
5432     // e.g. (FOO - :lower16:BAR) isn't legal.
5433     ARMMCExpr::VariantKind RefKind;
5434     if (parsePrefix(RefKind))
5435       return true;
5436 
5437     const MCExpr *SubExprVal;
5438     if (getParser().parseExpression(SubExprVal))
5439       return true;
5440 
5441     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
5442                                               getContext());
5443     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5444     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
5445     return false;
5446   }
5447   case AsmToken::Equal: {
5448     S = Parser.getTok().getLoc();
5449     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
5450       return Error(S, "unexpected token in operand");
5451     Parser.Lex(); // Eat '='
5452     const MCExpr *SubExprVal;
5453     if (getParser().parseExpression(SubExprVal))
5454       return true;
5455     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5456 
5457     // execute-only: we assume that assembly programmers know what they are
5458     // doing and allow literal pool creation here
5459     Operands.push_back(ARMOperand::CreateConstantPoolImm(SubExprVal, S, E));
5460     return false;
5461   }
5462   }
5463 }
5464 
5465 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
5466 //  :lower16: and :upper16:.
5467 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
5468   MCAsmParser &Parser = getParser();
5469   RefKind = ARMMCExpr::VK_ARM_None;
5470 
5471   // consume an optional '#' (GNU compatibility)
5472   if (getLexer().is(AsmToken::Hash))
5473     Parser.Lex();
5474 
5475   // :lower16: and :upper16: modifiers
5476   assert(getLexer().is(AsmToken::Colon) && "expected a :");
5477   Parser.Lex(); // Eat ':'
5478 
5479   if (getLexer().isNot(AsmToken::Identifier)) {
5480     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
5481     return true;
5482   }
5483 
5484   enum {
5485     COFF = (1 << MCObjectFileInfo::IsCOFF),
5486     ELF = (1 << MCObjectFileInfo::IsELF),
5487     MACHO = (1 << MCObjectFileInfo::IsMachO),
5488     WASM = (1 << MCObjectFileInfo::IsWasm),
5489   };
5490   static const struct PrefixEntry {
5491     const char *Spelling;
5492     ARMMCExpr::VariantKind VariantKind;
5493     uint8_t SupportedFormats;
5494   } PrefixEntries[] = {
5495     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
5496     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
5497   };
5498 
5499   StringRef IDVal = Parser.getTok().getIdentifier();
5500 
5501   const auto &Prefix =
5502       std::find_if(std::begin(PrefixEntries), std::end(PrefixEntries),
5503                    [&IDVal](const PrefixEntry &PE) {
5504                       return PE.Spelling == IDVal;
5505                    });
5506   if (Prefix == std::end(PrefixEntries)) {
5507     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
5508     return true;
5509   }
5510 
5511   uint8_t CurrentFormat;
5512   switch (getContext().getObjectFileInfo()->getObjectFileType()) {
5513   case MCObjectFileInfo::IsMachO:
5514     CurrentFormat = MACHO;
5515     break;
5516   case MCObjectFileInfo::IsELF:
5517     CurrentFormat = ELF;
5518     break;
5519   case MCObjectFileInfo::IsCOFF:
5520     CurrentFormat = COFF;
5521     break;
5522   case MCObjectFileInfo::IsWasm:
5523     CurrentFormat = WASM;
5524     break;
5525   }
5526 
5527   if (~Prefix->SupportedFormats & CurrentFormat) {
5528     Error(Parser.getTok().getLoc(),
5529           "cannot represent relocation in the current file format");
5530     return true;
5531   }
5532 
5533   RefKind = Prefix->VariantKind;
5534   Parser.Lex();
5535 
5536   if (getLexer().isNot(AsmToken::Colon)) {
5537     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
5538     return true;
5539   }
5540   Parser.Lex(); // Eat the last ':'
5541 
5542   return false;
5543 }
5544 
5545 /// \brief Given a mnemonic, split out possible predication code and carry
5546 /// setting letters to form a canonical mnemonic and flags.
5547 //
5548 // FIXME: Would be nice to autogen this.
5549 // FIXME: This is a bit of a maze of special cases.
5550 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
5551                                       unsigned &PredicationCode,
5552                                       bool &CarrySetting,
5553                                       unsigned &ProcessorIMod,
5554                                       StringRef &ITMask) {
5555   PredicationCode = ARMCC::AL;
5556   CarrySetting = false;
5557   ProcessorIMod = 0;
5558 
5559   // Ignore some mnemonics we know aren't predicated forms.
5560   //
5561   // FIXME: Would be nice to autogen this.
5562   if ((Mnemonic == "movs" && isThumb()) ||
5563       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
5564       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
5565       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
5566       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
5567       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
5568       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
5569       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
5570       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
5571       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
5572       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
5573       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
5574       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
5575       Mnemonic.startswith("vsel") || Mnemonic == "vins" || Mnemonic == "vmovx" ||
5576       Mnemonic == "bxns"  || Mnemonic == "blxns")
5577     return Mnemonic;
5578 
5579   // First, split out any predication code. Ignore mnemonics we know aren't
5580   // predicated but do have a carry-set and so weren't caught above.
5581   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
5582       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
5583       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
5584       Mnemonic != "sbcs" && Mnemonic != "rscs") {
5585     unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
5586       .Case("eq", ARMCC::EQ)
5587       .Case("ne", ARMCC::NE)
5588       .Case("hs", ARMCC::HS)
5589       .Case("cs", ARMCC::HS)
5590       .Case("lo", ARMCC::LO)
5591       .Case("cc", ARMCC::LO)
5592       .Case("mi", ARMCC::MI)
5593       .Case("pl", ARMCC::PL)
5594       .Case("vs", ARMCC::VS)
5595       .Case("vc", ARMCC::VC)
5596       .Case("hi", ARMCC::HI)
5597       .Case("ls", ARMCC::LS)
5598       .Case("ge", ARMCC::GE)
5599       .Case("lt", ARMCC::LT)
5600       .Case("gt", ARMCC::GT)
5601       .Case("le", ARMCC::LE)
5602       .Case("al", ARMCC::AL)
5603       .Default(~0U);
5604     if (CC != ~0U) {
5605       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
5606       PredicationCode = CC;
5607     }
5608   }
5609 
5610   // Next, determine if we have a carry setting bit. We explicitly ignore all
5611   // the instructions we know end in 's'.
5612   if (Mnemonic.endswith("s") &&
5613       !(Mnemonic == "cps" || Mnemonic == "mls" ||
5614         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
5615         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
5616         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
5617         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
5618         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
5619         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
5620         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
5621         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
5622         Mnemonic == "bxns" || Mnemonic == "blxns" ||
5623         (Mnemonic == "movs" && isThumb()))) {
5624     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
5625     CarrySetting = true;
5626   }
5627 
5628   // The "cps" instruction can have a interrupt mode operand which is glued into
5629   // the mnemonic. Check if this is the case, split it and parse the imod op
5630   if (Mnemonic.startswith("cps")) {
5631     // Split out any imod code.
5632     unsigned IMod =
5633       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
5634       .Case("ie", ARM_PROC::IE)
5635       .Case("id", ARM_PROC::ID)
5636       .Default(~0U);
5637     if (IMod != ~0U) {
5638       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
5639       ProcessorIMod = IMod;
5640     }
5641   }
5642 
5643   // The "it" instruction has the condition mask on the end of the mnemonic.
5644   if (Mnemonic.startswith("it")) {
5645     ITMask = Mnemonic.slice(2, Mnemonic.size());
5646     Mnemonic = Mnemonic.slice(0, 2);
5647   }
5648 
5649   return Mnemonic;
5650 }
5651 
5652 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
5653 /// inclusion of carry set or predication code operands.
5654 //
5655 // FIXME: It would be nice to autogen this.
5656 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
5657                                          bool &CanAcceptCarrySet,
5658                                          bool &CanAcceptPredicationCode) {
5659   CanAcceptCarrySet =
5660       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5661       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
5662       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
5663       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
5664       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
5665       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
5666       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
5667       (!isThumb() &&
5668        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
5669         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
5670 
5671   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
5672       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
5673       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
5674       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
5675       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
5676       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
5677       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
5678       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
5679       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
5680       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
5681       (FullInst.startswith("vmull") && FullInst.endswith(".p64")) ||
5682       Mnemonic == "vmovx" || Mnemonic == "vins") {
5683     // These mnemonics are never predicable
5684     CanAcceptPredicationCode = false;
5685   } else if (!isThumb()) {
5686     // Some instructions are only predicable in Thumb mode
5687     CanAcceptPredicationCode =
5688         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
5689         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
5690         Mnemonic != "dmb" && Mnemonic != "dsb" && Mnemonic != "isb" &&
5691         Mnemonic != "pld" && Mnemonic != "pli" && Mnemonic != "pldw" &&
5692         Mnemonic != "ldc2" && Mnemonic != "ldc2l" && Mnemonic != "stc2" &&
5693         Mnemonic != "stc2l" && !Mnemonic.startswith("rfe") &&
5694         !Mnemonic.startswith("srs");
5695   } else if (isThumbOne()) {
5696     if (hasV6MOps())
5697       CanAcceptPredicationCode = Mnemonic != "movs";
5698     else
5699       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
5700   } else
5701     CanAcceptPredicationCode = true;
5702 }
5703 
5704 // \brief Some Thumb instructions have two operand forms that are not
5705 // available as three operand, convert to two operand form if possible.
5706 //
5707 // FIXME: We would really like to be able to tablegen'erate this.
5708 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
5709                                                  bool CarrySetting,
5710                                                  OperandVector &Operands) {
5711   if (Operands.size() != 6)
5712     return;
5713 
5714   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5715         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
5716   if (!Op3.isReg() || !Op4.isReg())
5717     return;
5718 
5719   auto Op3Reg = Op3.getReg();
5720   auto Op4Reg = Op4.getReg();
5721 
5722   // For most Thumb2 cases we just generate the 3 operand form and reduce
5723   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
5724   // won't accept SP or PC so we do the transformation here taking care
5725   // with immediate range in the 'add sp, sp #imm' case.
5726   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
5727   if (isThumbTwo()) {
5728     if (Mnemonic != "add")
5729       return;
5730     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
5731                         (Op5.isReg() && Op5.getReg() == ARM::PC);
5732     if (!TryTransform) {
5733       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
5734                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
5735                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
5736                        Op5.isImm() && !Op5.isImm0_508s4());
5737     }
5738     if (!TryTransform)
5739       return;
5740   } else if (!isThumbOne())
5741     return;
5742 
5743   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
5744         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5745         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
5746         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
5747     return;
5748 
5749   // If first 2 operands of a 3 operand instruction are the same
5750   // then transform to 2 operand version of the same instruction
5751   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
5752   bool Transform = Op3Reg == Op4Reg;
5753 
5754   // For communtative operations, we might be able to transform if we swap
5755   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
5756   // as tADDrsp.
5757   const ARMOperand *LastOp = &Op5;
5758   bool Swap = false;
5759   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
5760       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
5761        Mnemonic == "and" || Mnemonic == "eor" ||
5762        Mnemonic == "adc" || Mnemonic == "orr")) {
5763     Swap = true;
5764     LastOp = &Op4;
5765     Transform = true;
5766   }
5767 
5768   // If both registers are the same then remove one of them from
5769   // the operand list, with certain exceptions.
5770   if (Transform) {
5771     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
5772     // 2 operand forms don't exist.
5773     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
5774         LastOp->isReg())
5775       Transform = false;
5776 
5777     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
5778     // 3-bits because the ARMARM says not to.
5779     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
5780       Transform = false;
5781   }
5782 
5783   if (Transform) {
5784     if (Swap)
5785       std::swap(Op4, Op5);
5786     Operands.erase(Operands.begin() + 3);
5787   }
5788 }
5789 
5790 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
5791                                           OperandVector &Operands) {
5792   // FIXME: This is all horribly hacky. We really need a better way to deal
5793   // with optional operands like this in the matcher table.
5794 
5795   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
5796   // another does not. Specifically, the MOVW instruction does not. So we
5797   // special case it here and remove the defaulted (non-setting) cc_out
5798   // operand if that's the instruction we're trying to match.
5799   //
5800   // We do this as post-processing of the explicit operands rather than just
5801   // conditionally adding the cc_out in the first place because we need
5802   // to check the type of the parsed immediate operand.
5803   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
5804       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
5805       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
5806       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5807     return true;
5808 
5809   // Register-register 'add' for thumb does not have a cc_out operand
5810   // when there are only two register operands.
5811   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
5812       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5813       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5814       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5815     return true;
5816   // Register-register 'add' for thumb does not have a cc_out operand
5817   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
5818   // have to check the immediate range here since Thumb2 has a variant
5819   // that can handle a different range and has a cc_out operand.
5820   if (((isThumb() && Mnemonic == "add") ||
5821        (isThumbTwo() && Mnemonic == "sub")) &&
5822       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5823       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5824       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
5825       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5826       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
5827        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
5828     return true;
5829   // For Thumb2, add/sub immediate does not have a cc_out operand for the
5830   // imm0_4095 variant. That's the least-preferred variant when
5831   // selecting via the generic "add" mnemonic, so to know that we
5832   // should remove the cc_out operand, we have to explicitly check that
5833   // it's not one of the other variants. Ugh.
5834   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
5835       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5836       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5837       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5838     // Nest conditions rather than one big 'if' statement for readability.
5839     //
5840     // If both registers are low, we're in an IT block, and the immediate is
5841     // in range, we should use encoding T1 instead, which has a cc_out.
5842     if (inITBlock() &&
5843         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
5844         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
5845         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
5846       return false;
5847     // Check against T3. If the second register is the PC, this is an
5848     // alternate form of ADR, which uses encoding T4, so check for that too.
5849     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
5850         static_cast<ARMOperand &>(*Operands[5]).isT2SOImm())
5851       return false;
5852 
5853     // Otherwise, we use encoding T4, which does not have a cc_out
5854     // operand.
5855     return true;
5856   }
5857 
5858   // The thumb2 multiply instruction doesn't have a CCOut register, so
5859   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
5860   // use the 16-bit encoding or not.
5861   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
5862       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5863       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5864       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5865       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
5866       // If the registers aren't low regs, the destination reg isn't the
5867       // same as one of the source regs, or the cc_out operand is zero
5868       // outside of an IT block, we have to use the 32-bit encoding, so
5869       // remove the cc_out operand.
5870       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5871        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5872        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
5873        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5874                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
5875                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5876                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
5877     return true;
5878 
5879   // Also check the 'mul' syntax variant that doesn't specify an explicit
5880   // destination register.
5881   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
5882       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5883       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5884       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5885       // If the registers aren't low regs  or the cc_out operand is zero
5886       // outside of an IT block, we have to use the 32-bit encoding, so
5887       // remove the cc_out operand.
5888       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5889        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5890        !inITBlock()))
5891     return true;
5892 
5893 
5894 
5895   // Register-register 'add/sub' for thumb does not have a cc_out operand
5896   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
5897   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
5898   // right, this will result in better diagnostics (which operand is off)
5899   // anyway.
5900   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
5901       (Operands.size() == 5 || Operands.size() == 6) &&
5902       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5903       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
5904       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5905       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
5906        (Operands.size() == 6 &&
5907         static_cast<ARMOperand &>(*Operands[5]).isImm())))
5908     return true;
5909 
5910   return false;
5911 }
5912 
5913 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
5914                                               OperandVector &Operands) {
5915   // VRINT{Z, R, X} have a predicate operand in VFP, but not in NEON
5916   unsigned RegIdx = 3;
5917   if ((Mnemonic == "vrintz" || Mnemonic == "vrintx" || Mnemonic == "vrintr") &&
5918       (static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32" ||
5919        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f16")) {
5920     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
5921         (static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32" ||
5922          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f16"))
5923       RegIdx = 4;
5924 
5925     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
5926         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
5927              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
5928          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
5929              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
5930       return true;
5931   }
5932   return false;
5933 }
5934 
5935 static bool isDataTypeToken(StringRef Tok) {
5936   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
5937     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
5938     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
5939     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
5940     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
5941     Tok == ".f" || Tok == ".d";
5942 }
5943 
5944 // FIXME: This bit should probably be handled via an explicit match class
5945 // in the .td files that matches the suffix instead of having it be
5946 // a literal string token the way it is now.
5947 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
5948   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
5949 }
5950 static void applyMnemonicAliases(StringRef &Mnemonic, uint64_t Features,
5951                                  unsigned VariantID);
5952 
5953 static bool RequiresVFPRegListValidation(StringRef Inst,
5954                                          bool &AcceptSinglePrecisionOnly,
5955                                          bool &AcceptDoublePrecisionOnly) {
5956   if (Inst.size() < 7)
5957     return false;
5958 
5959   if (Inst.startswith("fldm") || Inst.startswith("fstm")) {
5960     StringRef AddressingMode = Inst.substr(4, 2);
5961     if (AddressingMode == "ia" || AddressingMode == "db" ||
5962         AddressingMode == "ea" || AddressingMode == "fd") {
5963       AcceptSinglePrecisionOnly = Inst[6] == 's';
5964       AcceptDoublePrecisionOnly = Inst[6] == 'd' || Inst[6] == 'x';
5965       return true;
5966     }
5967   }
5968 
5969   return false;
5970 }
5971 
5972 /// Parse an arm instruction mnemonic followed by its operands.
5973 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
5974                                     SMLoc NameLoc, OperandVector &Operands) {
5975   MCAsmParser &Parser = getParser();
5976   // FIXME: Can this be done via tablegen in some fashion?
5977   bool RequireVFPRegisterListCheck;
5978   bool AcceptSinglePrecisionOnly;
5979   bool AcceptDoublePrecisionOnly;
5980   RequireVFPRegisterListCheck =
5981     RequiresVFPRegListValidation(Name, AcceptSinglePrecisionOnly,
5982                                  AcceptDoublePrecisionOnly);
5983 
5984   // Apply mnemonic aliases before doing anything else, as the destination
5985   // mnemonic may include suffices and we want to handle them normally.
5986   // The generic tblgen'erated code does this later, at the start of
5987   // MatchInstructionImpl(), but that's too late for aliases that include
5988   // any sort of suffix.
5989   uint64_t AvailableFeatures = getAvailableFeatures();
5990   unsigned AssemblerDialect = getParser().getAssemblerDialect();
5991   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
5992 
5993   // First check for the ARM-specific .req directive.
5994   if (Parser.getTok().is(AsmToken::Identifier) &&
5995       Parser.getTok().getIdentifier() == ".req") {
5996     parseDirectiveReq(Name, NameLoc);
5997     // We always return 'error' for this, as we're done with this
5998     // statement and don't need to match the 'instruction."
5999     return true;
6000   }
6001 
6002   // Create the leading tokens for the mnemonic, split by '.' characters.
6003   size_t Start = 0, Next = Name.find('.');
6004   StringRef Mnemonic = Name.slice(Start, Next);
6005 
6006   // Split out the predication code and carry setting flag from the mnemonic.
6007   unsigned PredicationCode;
6008   unsigned ProcessorIMod;
6009   bool CarrySetting;
6010   StringRef ITMask;
6011   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
6012                            ProcessorIMod, ITMask);
6013 
6014   // In Thumb1, only the branch (B) instruction can be predicated.
6015   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
6016     return Error(NameLoc, "conditional execution not supported in Thumb1");
6017   }
6018 
6019   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
6020 
6021   // Handle the IT instruction ITMask. Convert it to a bitmask. This
6022   // is the mask as it will be for the IT encoding if the conditional
6023   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
6024   // where the conditional bit0 is zero, the instruction post-processing
6025   // will adjust the mask accordingly.
6026   if (Mnemonic == "it") {
6027     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
6028     if (ITMask.size() > 3) {
6029       return Error(Loc, "too many conditions on IT instruction");
6030     }
6031     unsigned Mask = 8;
6032     for (unsigned i = ITMask.size(); i != 0; --i) {
6033       char pos = ITMask[i - 1];
6034       if (pos != 't' && pos != 'e') {
6035         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
6036       }
6037       Mask >>= 1;
6038       if (ITMask[i - 1] == 't')
6039         Mask |= 8;
6040     }
6041     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
6042   }
6043 
6044   // FIXME: This is all a pretty gross hack. We should automatically handle
6045   // optional operands like this via tblgen.
6046 
6047   // Next, add the CCOut and ConditionCode operands, if needed.
6048   //
6049   // For mnemonics which can ever incorporate a carry setting bit or predication
6050   // code, our matching model involves us always generating CCOut and
6051   // ConditionCode operands to match the mnemonic "as written" and then we let
6052   // the matcher deal with finding the right instruction or generating an
6053   // appropriate error.
6054   bool CanAcceptCarrySet, CanAcceptPredicationCode;
6055   getMnemonicAcceptInfo(Mnemonic, Name, CanAcceptCarrySet, CanAcceptPredicationCode);
6056 
6057   // If we had a carry-set on an instruction that can't do that, issue an
6058   // error.
6059   if (!CanAcceptCarrySet && CarrySetting) {
6060     return Error(NameLoc, "instruction '" + Mnemonic +
6061                  "' can not set flags, but 's' suffix specified");
6062   }
6063   // If we had a predication code on an instruction that can't do that, issue an
6064   // error.
6065   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
6066     return Error(NameLoc, "instruction '" + Mnemonic +
6067                  "' is not predicable, but condition code specified");
6068   }
6069 
6070   // Add the carry setting operand, if necessary.
6071   if (CanAcceptCarrySet) {
6072     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
6073     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
6074                                                Loc));
6075   }
6076 
6077   // Add the predication code operand, if necessary.
6078   if (CanAcceptPredicationCode) {
6079     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
6080                                       CarrySetting);
6081     Operands.push_back(ARMOperand::CreateCondCode(
6082                          ARMCC::CondCodes(PredicationCode), Loc));
6083   }
6084 
6085   // Add the processor imod operand, if necessary.
6086   if (ProcessorIMod) {
6087     Operands.push_back(ARMOperand::CreateImm(
6088           MCConstantExpr::create(ProcessorIMod, getContext()),
6089                                  NameLoc, NameLoc));
6090   } else if (Mnemonic == "cps" && isMClass()) {
6091     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
6092   }
6093 
6094   // Add the remaining tokens in the mnemonic.
6095   while (Next != StringRef::npos) {
6096     Start = Next;
6097     Next = Name.find('.', Start + 1);
6098     StringRef ExtraToken = Name.slice(Start, Next);
6099 
6100     // Some NEON instructions have an optional datatype suffix that is
6101     // completely ignored. Check for that.
6102     if (isDataTypeToken(ExtraToken) &&
6103         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
6104       continue;
6105 
6106     // For for ARM mode generate an error if the .n qualifier is used.
6107     if (ExtraToken == ".n" && !isThumb()) {
6108       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
6109       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
6110                    "arm mode");
6111     }
6112 
6113     // The .n qualifier is always discarded as that is what the tables
6114     // and matcher expect.  In ARM mode the .w qualifier has no effect,
6115     // so discard it to avoid errors that can be caused by the matcher.
6116     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
6117       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
6118       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
6119     }
6120   }
6121 
6122   // Read the remaining operands.
6123   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6124     // Read the first operand.
6125     if (parseOperand(Operands, Mnemonic)) {
6126       return true;
6127     }
6128 
6129     while (parseOptionalToken(AsmToken::Comma)) {
6130       // Parse and remember the operand.
6131       if (parseOperand(Operands, Mnemonic)) {
6132         return true;
6133       }
6134     }
6135   }
6136 
6137   if (parseToken(AsmToken::EndOfStatement, "unexpected token in argument list"))
6138     return true;
6139 
6140   if (RequireVFPRegisterListCheck) {
6141     ARMOperand &Op = static_cast<ARMOperand &>(*Operands.back());
6142     if (AcceptSinglePrecisionOnly && !Op.isSPRRegList())
6143       return Error(Op.getStartLoc(),
6144                    "VFP/Neon single precision register expected");
6145     if (AcceptDoublePrecisionOnly && !Op.isDPRRegList())
6146       return Error(Op.getStartLoc(),
6147                    "VFP/Neon double precision register expected");
6148   }
6149 
6150   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
6151 
6152   // Some instructions, mostly Thumb, have forms for the same mnemonic that
6153   // do and don't have a cc_out optional-def operand. With some spot-checks
6154   // of the operand list, we can figure out which variant we're trying to
6155   // parse and adjust accordingly before actually matching. We shouldn't ever
6156   // try to remove a cc_out operand that was explicitly set on the
6157   // mnemonic, of course (CarrySetting == true). Reason number #317 the
6158   // table driven matcher doesn't fit well with the ARM instruction set.
6159   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
6160     Operands.erase(Operands.begin() + 1);
6161 
6162   // Some instructions have the same mnemonic, but don't always
6163   // have a predicate. Distinguish them here and delete the
6164   // predicate if needed.
6165   if (shouldOmitPredicateOperand(Mnemonic, Operands))
6166     Operands.erase(Operands.begin() + 1);
6167 
6168   // ARM mode 'blx' need special handling, as the register operand version
6169   // is predicable, but the label operand version is not. So, we can't rely
6170   // on the Mnemonic based checking to correctly figure out when to put
6171   // a k_CondCode operand in the list. If we're trying to match the label
6172   // version, remove the k_CondCode operand here.
6173   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
6174       static_cast<ARMOperand &>(*Operands[2]).isImm())
6175     Operands.erase(Operands.begin() + 1);
6176 
6177   // Adjust operands of ldrexd/strexd to MCK_GPRPair.
6178   // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
6179   // a single GPRPair reg operand is used in the .td file to replace the two
6180   // GPRs. However, when parsing from asm, the two GRPs cannot be automatically
6181   // expressed as a GPRPair, so we have to manually merge them.
6182   // FIXME: We would really like to be able to tablegen'erate this.
6183   if (!isThumb() && Operands.size() > 4 &&
6184       (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
6185        Mnemonic == "stlexd")) {
6186     bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
6187     unsigned Idx = isLoad ? 2 : 3;
6188     ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
6189     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
6190 
6191     const MCRegisterClass& MRC = MRI->getRegClass(ARM::GPRRegClassID);
6192     // Adjust only if Op1 and Op2 are GPRs.
6193     if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
6194         MRC.contains(Op2.getReg())) {
6195       unsigned Reg1 = Op1.getReg();
6196       unsigned Reg2 = Op2.getReg();
6197       unsigned Rt = MRI->getEncodingValue(Reg1);
6198       unsigned Rt2 = MRI->getEncodingValue(Reg2);
6199 
6200       // Rt2 must be Rt + 1 and Rt must be even.
6201       if (Rt + 1 != Rt2 || (Rt & 1)) {
6202         return Error(Op2.getStartLoc(),
6203                      isLoad ? "destination operands must be sequential"
6204                             : "source operands must be sequential");
6205       }
6206       unsigned NewReg = MRI->getMatchingSuperReg(Reg1, ARM::gsub_0,
6207           &(MRI->getRegClass(ARM::GPRPairRegClassID)));
6208       Operands[Idx] =
6209           ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
6210       Operands.erase(Operands.begin() + Idx + 1);
6211     }
6212   }
6213 
6214   // GNU Assembler extension (compatibility)
6215   if ((Mnemonic == "ldrd" || Mnemonic == "strd")) {
6216     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
6217     ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6218     if (Op3.isMem()) {
6219       assert(Op2.isReg() && "expected register argument");
6220 
6221       unsigned SuperReg = MRI->getMatchingSuperReg(
6222           Op2.getReg(), ARM::gsub_0, &MRI->getRegClass(ARM::GPRPairRegClassID));
6223 
6224       assert(SuperReg && "expected register pair");
6225 
6226       unsigned PairedReg = MRI->getSubReg(SuperReg, ARM::gsub_1);
6227 
6228       Operands.insert(
6229           Operands.begin() + 3,
6230           ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
6231     }
6232   }
6233 
6234   // FIXME: As said above, this is all a pretty gross hack.  This instruction
6235   // does not fit with other "subs" and tblgen.
6236   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
6237   // so the Mnemonic is the original name "subs" and delete the predicate
6238   // operand so it will match the table entry.
6239   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
6240       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6241       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
6242       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6243       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
6244       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
6245     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
6246     Operands.erase(Operands.begin() + 1);
6247   }
6248   return false;
6249 }
6250 
6251 // Validate context-sensitive operand constraints.
6252 
6253 // return 'true' if register list contains non-low GPR registers,
6254 // 'false' otherwise. If Reg is in the register list or is HiReg, set
6255 // 'containsReg' to true.
6256 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
6257                                  unsigned Reg, unsigned HiReg,
6258                                  bool &containsReg) {
6259   containsReg = false;
6260   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
6261     unsigned OpReg = Inst.getOperand(i).getReg();
6262     if (OpReg == Reg)
6263       containsReg = true;
6264     // Anything other than a low register isn't legal here.
6265     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
6266       return true;
6267   }
6268   return false;
6269 }
6270 
6271 // Check if the specified regisgter is in the register list of the inst,
6272 // starting at the indicated operand number.
6273 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
6274   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
6275     unsigned OpReg = Inst.getOperand(i).getReg();
6276     if (OpReg == Reg)
6277       return true;
6278   }
6279   return false;
6280 }
6281 
6282 // Return true if instruction has the interesting property of being
6283 // allowed in IT blocks, but not being predicable.
6284 static bool instIsBreakpoint(const MCInst &Inst) {
6285     return Inst.getOpcode() == ARM::tBKPT ||
6286            Inst.getOpcode() == ARM::BKPT ||
6287            Inst.getOpcode() == ARM::tHLT ||
6288            Inst.getOpcode() == ARM::HLT;
6289 
6290 }
6291 
6292 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
6293                                        const OperandVector &Operands,
6294                                        unsigned ListNo, bool IsARPop) {
6295   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6296   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6297 
6298   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6299   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
6300   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6301 
6302   if (!IsARPop && ListContainsSP)
6303     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6304                  "SP may not be in the register list");
6305   else if (ListContainsPC && ListContainsLR)
6306     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6307                  "PC and LR may not be in the register list simultaneously");
6308   return false;
6309 }
6310 
6311 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
6312                                        const OperandVector &Operands,
6313                                        unsigned ListNo) {
6314   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6315   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6316 
6317   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6318   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6319 
6320   if (ListContainsSP && ListContainsPC)
6321     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6322                  "SP and PC may not be in the register list");
6323   else if (ListContainsSP)
6324     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6325                  "SP may not be in the register list");
6326   else if (ListContainsPC)
6327     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6328                  "PC may not be in the register list");
6329   return false;
6330 }
6331 
6332 // FIXME: We would really like to be able to tablegen'erate this.
6333 bool ARMAsmParser::validateInstruction(MCInst &Inst,
6334                                        const OperandVector &Operands) {
6335   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
6336   SMLoc Loc = Operands[0]->getStartLoc();
6337 
6338   // Check the IT block state first.
6339   // NOTE: BKPT and HLT instructions have the interesting property of being
6340   // allowed in IT blocks, but not being predicable. They just always execute.
6341   if (inITBlock() && !instIsBreakpoint(Inst)) {
6342     // The instruction must be predicable.
6343     if (!MCID.isPredicable())
6344       return Error(Loc, "instructions in IT block must be predicable");
6345     unsigned Cond = Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm();
6346     if (Cond != currentITCond()) {
6347       // Find the condition code Operand to get its SMLoc information.
6348       SMLoc CondLoc;
6349       for (unsigned I = 1; I < Operands.size(); ++I)
6350         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
6351           CondLoc = Operands[I]->getStartLoc();
6352       return Error(CondLoc, "incorrect condition in IT block; got '" +
6353                    StringRef(ARMCondCodeToString(ARMCC::CondCodes(Cond))) +
6354                    "', but expected '" +
6355                    ARMCondCodeToString(ARMCC::CondCodes(currentITCond())) + "'");
6356     }
6357   // Check for non-'al' condition codes outside of the IT block.
6358   } else if (isThumbTwo() && MCID.isPredicable() &&
6359              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6360              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
6361              Inst.getOpcode() != ARM::t2Bcc) {
6362     return Error(Loc, "predicated instructions must be in IT block");
6363   } else if (!isThumb() && !useImplicitITARM() && MCID.isPredicable() &&
6364              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6365                  ARMCC::AL) {
6366     return Warning(Loc, "predicated instructions should be in IT block");
6367   }
6368 
6369   // PC-setting instructions in an IT block, but not the last instruction of
6370   // the block, are UNPREDICTABLE.
6371   if (inExplicitITBlock() && !lastInITBlock() && isITBlockTerminator(Inst)) {
6372     return Error(Loc, "instruction must be outside of IT block or the last instruction in an IT block");
6373   }
6374 
6375   const unsigned Opcode = Inst.getOpcode();
6376   switch (Opcode) {
6377   case ARM::LDRD:
6378   case ARM::LDRD_PRE:
6379   case ARM::LDRD_POST: {
6380     const unsigned RtReg = Inst.getOperand(0).getReg();
6381 
6382     // Rt can't be R14.
6383     if (RtReg == ARM::LR)
6384       return Error(Operands[3]->getStartLoc(),
6385                    "Rt can't be R14");
6386 
6387     const unsigned Rt = MRI->getEncodingValue(RtReg);
6388     // Rt must be even-numbered.
6389     if ((Rt & 1) == 1)
6390       return Error(Operands[3]->getStartLoc(),
6391                    "Rt must be even-numbered");
6392 
6393     // Rt2 must be Rt + 1.
6394     const unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6395     if (Rt2 != Rt + 1)
6396       return Error(Operands[3]->getStartLoc(),
6397                    "destination operands must be sequential");
6398 
6399     if (Opcode == ARM::LDRD_PRE || Opcode == ARM::LDRD_POST) {
6400       const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
6401       // For addressing modes with writeback, the base register needs to be
6402       // different from the destination registers.
6403       if (Rn == Rt || Rn == Rt2)
6404         return Error(Operands[3]->getStartLoc(),
6405                      "base register needs to be different from destination "
6406                      "registers");
6407     }
6408 
6409     return false;
6410   }
6411   case ARM::t2LDRDi8:
6412   case ARM::t2LDRD_PRE:
6413   case ARM::t2LDRD_POST: {
6414     // Rt2 must be different from Rt.
6415     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6416     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6417     if (Rt2 == Rt)
6418       return Error(Operands[3]->getStartLoc(),
6419                    "destination operands can't be identical");
6420     return false;
6421   }
6422   case ARM::t2BXJ: {
6423     const unsigned RmReg = Inst.getOperand(0).getReg();
6424     // Rm = SP is no longer unpredictable in v8-A
6425     if (RmReg == ARM::SP && !hasV8Ops())
6426       return Error(Operands[2]->getStartLoc(),
6427                    "r13 (SP) is an unpredictable operand to BXJ");
6428     return false;
6429   }
6430   case ARM::STRD: {
6431     // Rt2 must be Rt + 1.
6432     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6433     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6434     if (Rt2 != Rt + 1)
6435       return Error(Operands[3]->getStartLoc(),
6436                    "source operands must be sequential");
6437     return false;
6438   }
6439   case ARM::STRD_PRE:
6440   case ARM::STRD_POST: {
6441     // Rt2 must be Rt + 1.
6442     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6443     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6444     if (Rt2 != Rt + 1)
6445       return Error(Operands[3]->getStartLoc(),
6446                    "source operands must be sequential");
6447     return false;
6448   }
6449   case ARM::STR_PRE_IMM:
6450   case ARM::STR_PRE_REG:
6451   case ARM::STR_POST_IMM:
6452   case ARM::STR_POST_REG:
6453   case ARM::STRH_PRE:
6454   case ARM::STRH_POST:
6455   case ARM::STRB_PRE_IMM:
6456   case ARM::STRB_PRE_REG:
6457   case ARM::STRB_POST_IMM:
6458   case ARM::STRB_POST_REG: {
6459     // Rt must be different from Rn.
6460     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6461     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6462 
6463     if (Rt == Rn)
6464       return Error(Operands[3]->getStartLoc(),
6465                    "source register and base register can't be identical");
6466     return false;
6467   }
6468   case ARM::LDR_PRE_IMM:
6469   case ARM::LDR_PRE_REG:
6470   case ARM::LDR_POST_IMM:
6471   case ARM::LDR_POST_REG:
6472   case ARM::LDRH_PRE:
6473   case ARM::LDRH_POST:
6474   case ARM::LDRSH_PRE:
6475   case ARM::LDRSH_POST:
6476   case ARM::LDRB_PRE_IMM:
6477   case ARM::LDRB_PRE_REG:
6478   case ARM::LDRB_POST_IMM:
6479   case ARM::LDRB_POST_REG:
6480   case ARM::LDRSB_PRE:
6481   case ARM::LDRSB_POST: {
6482     // Rt must be different from Rn.
6483     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6484     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6485 
6486     if (Rt == Rn)
6487       return Error(Operands[3]->getStartLoc(),
6488                    "destination register and base register can't be identical");
6489     return false;
6490   }
6491   case ARM::SBFX:
6492   case ARM::UBFX: {
6493     // Width must be in range [1, 32-lsb].
6494     unsigned LSB = Inst.getOperand(2).getImm();
6495     unsigned Widthm1 = Inst.getOperand(3).getImm();
6496     if (Widthm1 >= 32 - LSB)
6497       return Error(Operands[5]->getStartLoc(),
6498                    "bitfield width must be in range [1,32-lsb]");
6499     return false;
6500   }
6501   // Notionally handles ARM::tLDMIA_UPD too.
6502   case ARM::tLDMIA: {
6503     // If we're parsing Thumb2, the .w variant is available and handles
6504     // most cases that are normally illegal for a Thumb1 LDM instruction.
6505     // We'll make the transformation in processInstruction() if necessary.
6506     //
6507     // Thumb LDM instructions are writeback iff the base register is not
6508     // in the register list.
6509     unsigned Rn = Inst.getOperand(0).getReg();
6510     bool HasWritebackToken =
6511         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6512          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
6513     bool ListContainsBase;
6514     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
6515       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
6516                    "registers must be in range r0-r7");
6517     // If we should have writeback, then there should be a '!' token.
6518     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
6519       return Error(Operands[2]->getStartLoc(),
6520                    "writeback operator '!' expected");
6521     // If we should not have writeback, there must not be a '!'. This is
6522     // true even for the 32-bit wide encodings.
6523     if (ListContainsBase && HasWritebackToken)
6524       return Error(Operands[3]->getStartLoc(),
6525                    "writeback operator '!' not allowed when base register "
6526                    "in register list");
6527 
6528     if (validatetLDMRegList(Inst, Operands, 3))
6529       return true;
6530     break;
6531   }
6532   case ARM::LDMIA_UPD:
6533   case ARM::LDMDB_UPD:
6534   case ARM::LDMIB_UPD:
6535   case ARM::LDMDA_UPD:
6536     // ARM variants loading and updating the same register are only officially
6537     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
6538     if (!hasV7Ops())
6539       break;
6540     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6541       return Error(Operands.back()->getStartLoc(),
6542                    "writeback register not allowed in register list");
6543     break;
6544   case ARM::t2LDMIA:
6545   case ARM::t2LDMDB:
6546     if (validatetLDMRegList(Inst, Operands, 3))
6547       return true;
6548     break;
6549   case ARM::t2STMIA:
6550   case ARM::t2STMDB:
6551     if (validatetSTMRegList(Inst, Operands, 3))
6552       return true;
6553     break;
6554   case ARM::t2LDMIA_UPD:
6555   case ARM::t2LDMDB_UPD:
6556   case ARM::t2STMIA_UPD:
6557   case ARM::t2STMDB_UPD: {
6558     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6559       return Error(Operands.back()->getStartLoc(),
6560                    "writeback register not allowed in register list");
6561 
6562     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
6563       if (validatetLDMRegList(Inst, Operands, 3))
6564         return true;
6565     } else {
6566       if (validatetSTMRegList(Inst, Operands, 3))
6567         return true;
6568     }
6569     break;
6570   }
6571   case ARM::sysLDMIA_UPD:
6572   case ARM::sysLDMDA_UPD:
6573   case ARM::sysLDMDB_UPD:
6574   case ARM::sysLDMIB_UPD:
6575     if (!listContainsReg(Inst, 3, ARM::PC))
6576       return Error(Operands[4]->getStartLoc(),
6577                    "writeback register only allowed on system LDM "
6578                    "if PC in register-list");
6579     break;
6580   case ARM::sysSTMIA_UPD:
6581   case ARM::sysSTMDA_UPD:
6582   case ARM::sysSTMDB_UPD:
6583   case ARM::sysSTMIB_UPD:
6584     return Error(Operands[2]->getStartLoc(),
6585                  "system STM cannot have writeback register");
6586   case ARM::tMUL: {
6587     // The second source operand must be the same register as the destination
6588     // operand.
6589     //
6590     // In this case, we must directly check the parsed operands because the
6591     // cvtThumbMultiply() function is written in such a way that it guarantees
6592     // this first statement is always true for the new Inst.  Essentially, the
6593     // destination is unconditionally copied into the second source operand
6594     // without checking to see if it matches what we actually parsed.
6595     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
6596                                  ((ARMOperand &)*Operands[5]).getReg()) &&
6597         (((ARMOperand &)*Operands[3]).getReg() !=
6598          ((ARMOperand &)*Operands[4]).getReg())) {
6599       return Error(Operands[3]->getStartLoc(),
6600                    "destination register must match source register");
6601     }
6602     break;
6603   }
6604   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
6605   // so only issue a diagnostic for thumb1. The instructions will be
6606   // switched to the t2 encodings in processInstruction() if necessary.
6607   case ARM::tPOP: {
6608     bool ListContainsBase;
6609     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
6610         !isThumbTwo())
6611       return Error(Operands[2]->getStartLoc(),
6612                    "registers must be in range r0-r7 or pc");
6613     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
6614       return true;
6615     break;
6616   }
6617   case ARM::tPUSH: {
6618     bool ListContainsBase;
6619     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
6620         !isThumbTwo())
6621       return Error(Operands[2]->getStartLoc(),
6622                    "registers must be in range r0-r7 or lr");
6623     if (validatetSTMRegList(Inst, Operands, 2))
6624       return true;
6625     break;
6626   }
6627   case ARM::tSTMIA_UPD: {
6628     bool ListContainsBase, InvalidLowList;
6629     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
6630                                           0, ListContainsBase);
6631     if (InvalidLowList && !isThumbTwo())
6632       return Error(Operands[4]->getStartLoc(),
6633                    "registers must be in range r0-r7");
6634 
6635     // This would be converted to a 32-bit stm, but that's not valid if the
6636     // writeback register is in the list.
6637     if (InvalidLowList && ListContainsBase)
6638       return Error(Operands[4]->getStartLoc(),
6639                    "writeback operator '!' not allowed when base register "
6640                    "in register list");
6641 
6642     if (validatetSTMRegList(Inst, Operands, 4))
6643       return true;
6644     break;
6645   }
6646   case ARM::tADDrSP: {
6647     // If the non-SP source operand and the destination operand are not the
6648     // same, we need thumb2 (for the wide encoding), or we have an error.
6649     if (!isThumbTwo() &&
6650         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
6651       return Error(Operands[4]->getStartLoc(),
6652                    "source register must be the same as destination");
6653     }
6654     break;
6655   }
6656   // Final range checking for Thumb unconditional branch instructions.
6657   case ARM::tB:
6658     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
6659       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6660     break;
6661   case ARM::t2B: {
6662     int op = (Operands[2]->isImm()) ? 2 : 3;
6663     if (!static_cast<ARMOperand &>(*Operands[op]).isSignedOffset<24, 1>())
6664       return Error(Operands[op]->getStartLoc(), "branch target out of range");
6665     break;
6666   }
6667   // Final range checking for Thumb conditional branch instructions.
6668   case ARM::tBcc:
6669     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
6670       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6671     break;
6672   case ARM::t2Bcc: {
6673     int Op = (Operands[2]->isImm()) ? 2 : 3;
6674     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
6675       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
6676     break;
6677   }
6678   case ARM::tCBZ:
6679   case ARM::tCBNZ: {
6680     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<6, 1>())
6681       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6682     break;
6683   }
6684   case ARM::MOVi16:
6685   case ARM::MOVTi16:
6686   case ARM::t2MOVi16:
6687   case ARM::t2MOVTi16:
6688     {
6689     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
6690     // especially when we turn it into a movw and the expression <symbol> does
6691     // not have a :lower16: or :upper16 as part of the expression.  We don't
6692     // want the behavior of silently truncating, which can be unexpected and
6693     // lead to bugs that are difficult to find since this is an easy mistake
6694     // to make.
6695     int i = (Operands[3]->isImm()) ? 3 : 4;
6696     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
6697     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
6698     if (CE) break;
6699     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
6700     if (!E) break;
6701     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
6702     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
6703                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
6704       return Error(
6705           Op.getStartLoc(),
6706           "immediate expression for mov requires :lower16: or :upper16");
6707     break;
6708   }
6709   case ARM::HINT:
6710   case ARM::t2HINT: {
6711     if (hasRAS()) {
6712       // ESB is not predicable (pred must be AL)
6713       unsigned Imm8 = Inst.getOperand(0).getImm();
6714       unsigned Pred = Inst.getOperand(1).getImm();
6715       if (Imm8 == 0x10 && Pred != ARMCC::AL)
6716         return Error(Operands[1]->getStartLoc(), "instruction 'esb' is not "
6717                                                  "predicable, but condition "
6718                                                  "code specified");
6719     }
6720     // Without the RAS extension, this behaves as any other unallocated hint.
6721     break;
6722   }
6723   }
6724 
6725   return false;
6726 }
6727 
6728 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
6729   switch(Opc) {
6730   default: llvm_unreachable("unexpected opcode!");
6731   // VST1LN
6732   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6733   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6734   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6735   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6736   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6737   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6738   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
6739   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
6740   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
6741 
6742   // VST2LN
6743   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6744   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6745   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6746   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6747   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6748 
6749   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6750   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6751   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6752   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6753   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6754 
6755   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
6756   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
6757   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
6758   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
6759   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
6760 
6761   // VST3LN
6762   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6763   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6764   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6765   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
6766   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6767   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6768   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6769   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6770   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
6771   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6772   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
6773   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
6774   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
6775   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
6776   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
6777 
6778   // VST3
6779   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6780   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6781   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6782   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6783   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6784   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6785   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6786   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6787   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6788   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6789   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6790   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6791   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
6792   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
6793   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
6794   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
6795   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
6796   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
6797 
6798   // VST4LN
6799   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6800   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6801   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6802   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
6803   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6804   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6805   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6806   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6807   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
6808   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6809   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
6810   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
6811   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
6812   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
6813   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
6814 
6815   // VST4
6816   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6817   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6818   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6819   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6820   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6821   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6822   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6823   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6824   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6825   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6826   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6827   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6828   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
6829   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
6830   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
6831   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
6832   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
6833   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
6834   }
6835 }
6836 
6837 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
6838   switch(Opc) {
6839   default: llvm_unreachable("unexpected opcode!");
6840   // VLD1LN
6841   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6842   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6843   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6844   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6845   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6846   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6847   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
6848   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
6849   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
6850 
6851   // VLD2LN
6852   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6853   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6854   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6855   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
6856   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6857   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6858   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6859   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6860   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
6861   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6862   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
6863   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
6864   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
6865   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
6866   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
6867 
6868   // VLD3DUP
6869   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6870   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6871   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6872   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
6873   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6874   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6875   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6876   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6877   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6878   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
6879   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6880   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6881   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
6882   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
6883   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
6884   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
6885   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
6886   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
6887 
6888   // VLD3LN
6889   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6890   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6891   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6892   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
6893   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6894   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6895   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6896   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6897   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
6898   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6899   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
6900   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
6901   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
6902   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
6903   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
6904 
6905   // VLD3
6906   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6907   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6908   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6909   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6910   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6911   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6912   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6913   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6914   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6915   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6916   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6917   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6918   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
6919   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
6920   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
6921   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
6922   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
6923   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
6924 
6925   // VLD4LN
6926   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6927   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6928   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6929   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6930   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6931   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6932   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6933   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6934   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6935   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6936   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
6937   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
6938   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
6939   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
6940   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
6941 
6942   // VLD4DUP
6943   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6944   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6945   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6946   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
6947   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
6948   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6949   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6950   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6951   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6952   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
6953   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
6954   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6955   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
6956   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
6957   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
6958   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
6959   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
6960   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
6961 
6962   // VLD4
6963   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6964   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6965   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6966   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6967   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6968   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6969   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6970   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6971   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6972   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6973   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6974   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6975   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
6976   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
6977   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
6978   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
6979   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
6980   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
6981   }
6982 }
6983 
6984 bool ARMAsmParser::processInstruction(MCInst &Inst,
6985                                       const OperandVector &Operands,
6986                                       MCStreamer &Out) {
6987   switch (Inst.getOpcode()) {
6988   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
6989   case ARM::LDRT_POST:
6990   case ARM::LDRBT_POST: {
6991     const unsigned Opcode =
6992       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
6993                                            : ARM::LDRBT_POST_IMM;
6994     MCInst TmpInst;
6995     TmpInst.setOpcode(Opcode);
6996     TmpInst.addOperand(Inst.getOperand(0));
6997     TmpInst.addOperand(Inst.getOperand(1));
6998     TmpInst.addOperand(Inst.getOperand(1));
6999     TmpInst.addOperand(MCOperand::createReg(0));
7000     TmpInst.addOperand(MCOperand::createImm(0));
7001     TmpInst.addOperand(Inst.getOperand(2));
7002     TmpInst.addOperand(Inst.getOperand(3));
7003     Inst = TmpInst;
7004     return true;
7005   }
7006   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
7007   case ARM::STRT_POST:
7008   case ARM::STRBT_POST: {
7009     const unsigned Opcode =
7010       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
7011                                            : ARM::STRBT_POST_IMM;
7012     MCInst TmpInst;
7013     TmpInst.setOpcode(Opcode);
7014     TmpInst.addOperand(Inst.getOperand(1));
7015     TmpInst.addOperand(Inst.getOperand(0));
7016     TmpInst.addOperand(Inst.getOperand(1));
7017     TmpInst.addOperand(MCOperand::createReg(0));
7018     TmpInst.addOperand(MCOperand::createImm(0));
7019     TmpInst.addOperand(Inst.getOperand(2));
7020     TmpInst.addOperand(Inst.getOperand(3));
7021     Inst = TmpInst;
7022     return true;
7023   }
7024   // Alias for alternate form of 'ADR Rd, #imm' instruction.
7025   case ARM::ADDri: {
7026     if (Inst.getOperand(1).getReg() != ARM::PC ||
7027         Inst.getOperand(5).getReg() != 0 ||
7028         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
7029       return false;
7030     MCInst TmpInst;
7031     TmpInst.setOpcode(ARM::ADR);
7032     TmpInst.addOperand(Inst.getOperand(0));
7033     if (Inst.getOperand(2).isImm()) {
7034       // Immediate (mod_imm) will be in its encoded form, we must unencode it
7035       // before passing it to the ADR instruction.
7036       unsigned Enc = Inst.getOperand(2).getImm();
7037       TmpInst.addOperand(MCOperand::createImm(
7038         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
7039     } else {
7040       // Turn PC-relative expression into absolute expression.
7041       // Reading PC provides the start of the current instruction + 8 and
7042       // the transform to adr is biased by that.
7043       MCSymbol *Dot = getContext().createTempSymbol();
7044       Out.EmitLabel(Dot);
7045       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
7046       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
7047                                                      MCSymbolRefExpr::VK_None,
7048                                                      getContext());
7049       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
7050       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
7051                                                      getContext());
7052       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
7053                                                         getContext());
7054       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
7055     }
7056     TmpInst.addOperand(Inst.getOperand(3));
7057     TmpInst.addOperand(Inst.getOperand(4));
7058     Inst = TmpInst;
7059     return true;
7060   }
7061   // Aliases for alternate PC+imm syntax of LDR instructions.
7062   case ARM::t2LDRpcrel:
7063     // Select the narrow version if the immediate will fit.
7064     if (Inst.getOperand(1).getImm() > 0 &&
7065         Inst.getOperand(1).getImm() <= 0xff &&
7066         !(static_cast<ARMOperand &>(*Operands[2]).isToken() &&
7067           static_cast<ARMOperand &>(*Operands[2]).getToken() == ".w"))
7068       Inst.setOpcode(ARM::tLDRpci);
7069     else
7070       Inst.setOpcode(ARM::t2LDRpci);
7071     return true;
7072   case ARM::t2LDRBpcrel:
7073     Inst.setOpcode(ARM::t2LDRBpci);
7074     return true;
7075   case ARM::t2LDRHpcrel:
7076     Inst.setOpcode(ARM::t2LDRHpci);
7077     return true;
7078   case ARM::t2LDRSBpcrel:
7079     Inst.setOpcode(ARM::t2LDRSBpci);
7080     return true;
7081   case ARM::t2LDRSHpcrel:
7082     Inst.setOpcode(ARM::t2LDRSHpci);
7083     return true;
7084   case ARM::LDRConstPool:
7085   case ARM::tLDRConstPool:
7086   case ARM::t2LDRConstPool: {
7087     // Pseudo instruction ldr rt, =immediate is converted to a
7088     // MOV rt, immediate if immediate is known and representable
7089     // otherwise we create a constant pool entry that we load from.
7090     MCInst TmpInst;
7091     if (Inst.getOpcode() == ARM::LDRConstPool)
7092       TmpInst.setOpcode(ARM::LDRi12);
7093     else if (Inst.getOpcode() == ARM::tLDRConstPool)
7094       TmpInst.setOpcode(ARM::tLDRpci);
7095     else if (Inst.getOpcode() == ARM::t2LDRConstPool)
7096       TmpInst.setOpcode(ARM::t2LDRpci);
7097     const ARMOperand &PoolOperand =
7098       (static_cast<ARMOperand &>(*Operands[2]).isToken() &&
7099        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".w") ?
7100       static_cast<ARMOperand &>(*Operands[4]) :
7101       static_cast<ARMOperand &>(*Operands[3]);
7102     const MCExpr *SubExprVal = PoolOperand.getConstantPoolImm();
7103     // If SubExprVal is a constant we may be able to use a MOV
7104     if (isa<MCConstantExpr>(SubExprVal) &&
7105         Inst.getOperand(0).getReg() != ARM::PC &&
7106         Inst.getOperand(0).getReg() != ARM::SP) {
7107       int64_t Value =
7108         (int64_t) (cast<MCConstantExpr>(SubExprVal))->getValue();
7109       bool UseMov  = true;
7110       bool MovHasS = true;
7111       if (Inst.getOpcode() == ARM::LDRConstPool) {
7112         // ARM Constant
7113         if (ARM_AM::getSOImmVal(Value) != -1) {
7114           Value = ARM_AM::getSOImmVal(Value);
7115           TmpInst.setOpcode(ARM::MOVi);
7116         }
7117         else if (ARM_AM::getSOImmVal(~Value) != -1) {
7118           Value = ARM_AM::getSOImmVal(~Value);
7119           TmpInst.setOpcode(ARM::MVNi);
7120         }
7121         else if (hasV6T2Ops() &&
7122                  Value >=0 && Value < 65536) {
7123           TmpInst.setOpcode(ARM::MOVi16);
7124           MovHasS = false;
7125         }
7126         else
7127           UseMov = false;
7128       }
7129       else {
7130         // Thumb/Thumb2 Constant
7131         if (hasThumb2() &&
7132             ARM_AM::getT2SOImmVal(Value) != -1)
7133           TmpInst.setOpcode(ARM::t2MOVi);
7134         else if (hasThumb2() &&
7135                  ARM_AM::getT2SOImmVal(~Value) != -1) {
7136           TmpInst.setOpcode(ARM::t2MVNi);
7137           Value = ~Value;
7138         }
7139         else if (hasV8MBaseline() &&
7140                  Value >=0 && Value < 65536) {
7141           TmpInst.setOpcode(ARM::t2MOVi16);
7142           MovHasS = false;
7143         }
7144         else
7145           UseMov = false;
7146       }
7147       if (UseMov) {
7148         TmpInst.addOperand(Inst.getOperand(0));           // Rt
7149         TmpInst.addOperand(MCOperand::createImm(Value));  // Immediate
7150         TmpInst.addOperand(Inst.getOperand(2));           // CondCode
7151         TmpInst.addOperand(Inst.getOperand(3));           // CondCode
7152         if (MovHasS)
7153           TmpInst.addOperand(MCOperand::createReg(0));    // S
7154         Inst = TmpInst;
7155         return true;
7156       }
7157     }
7158     // No opportunity to use MOV/MVN create constant pool
7159     const MCExpr *CPLoc =
7160       getTargetStreamer().addConstantPoolEntry(SubExprVal,
7161                                                PoolOperand.getStartLoc());
7162     TmpInst.addOperand(Inst.getOperand(0));           // Rt
7163     TmpInst.addOperand(MCOperand::createExpr(CPLoc)); // offset to constpool
7164     if (TmpInst.getOpcode() == ARM::LDRi12)
7165       TmpInst.addOperand(MCOperand::createImm(0));    // unused offset
7166     TmpInst.addOperand(Inst.getOperand(2));           // CondCode
7167     TmpInst.addOperand(Inst.getOperand(3));           // CondCode
7168     Inst = TmpInst;
7169     return true;
7170   }
7171   // Handle NEON VST complex aliases.
7172   case ARM::VST1LNdWB_register_Asm_8:
7173   case ARM::VST1LNdWB_register_Asm_16:
7174   case ARM::VST1LNdWB_register_Asm_32: {
7175     MCInst TmpInst;
7176     // Shuffle the operands around so the lane index operand is in the
7177     // right place.
7178     unsigned Spacing;
7179     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7180     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7181     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7182     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7183     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7184     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7185     TmpInst.addOperand(Inst.getOperand(1)); // lane
7186     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7187     TmpInst.addOperand(Inst.getOperand(6));
7188     Inst = TmpInst;
7189     return true;
7190   }
7191 
7192   case ARM::VST2LNdWB_register_Asm_8:
7193   case ARM::VST2LNdWB_register_Asm_16:
7194   case ARM::VST2LNdWB_register_Asm_32:
7195   case ARM::VST2LNqWB_register_Asm_16:
7196   case ARM::VST2LNqWB_register_Asm_32: {
7197     MCInst TmpInst;
7198     // Shuffle the operands around so the lane index operand is in the
7199     // right place.
7200     unsigned Spacing;
7201     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7202     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7203     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7204     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7205     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7206     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7207     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7208                                             Spacing));
7209     TmpInst.addOperand(Inst.getOperand(1)); // lane
7210     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7211     TmpInst.addOperand(Inst.getOperand(6));
7212     Inst = TmpInst;
7213     return true;
7214   }
7215 
7216   case ARM::VST3LNdWB_register_Asm_8:
7217   case ARM::VST3LNdWB_register_Asm_16:
7218   case ARM::VST3LNdWB_register_Asm_32:
7219   case ARM::VST3LNqWB_register_Asm_16:
7220   case ARM::VST3LNqWB_register_Asm_32: {
7221     MCInst TmpInst;
7222     // Shuffle the operands around so the lane index operand is in the
7223     // right place.
7224     unsigned Spacing;
7225     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7226     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7227     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7228     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7229     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7230     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7231     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7232                                             Spacing));
7233     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7234                                             Spacing * 2));
7235     TmpInst.addOperand(Inst.getOperand(1)); // lane
7236     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7237     TmpInst.addOperand(Inst.getOperand(6));
7238     Inst = TmpInst;
7239     return true;
7240   }
7241 
7242   case ARM::VST4LNdWB_register_Asm_8:
7243   case ARM::VST4LNdWB_register_Asm_16:
7244   case ARM::VST4LNdWB_register_Asm_32:
7245   case ARM::VST4LNqWB_register_Asm_16:
7246   case ARM::VST4LNqWB_register_Asm_32: {
7247     MCInst TmpInst;
7248     // Shuffle the operands around so the lane index operand is in the
7249     // right place.
7250     unsigned Spacing;
7251     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7252     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7253     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7254     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7255     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7256     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7257     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7258                                             Spacing));
7259     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7260                                             Spacing * 2));
7261     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7262                                             Spacing * 3));
7263     TmpInst.addOperand(Inst.getOperand(1)); // lane
7264     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7265     TmpInst.addOperand(Inst.getOperand(6));
7266     Inst = TmpInst;
7267     return true;
7268   }
7269 
7270   case ARM::VST1LNdWB_fixed_Asm_8:
7271   case ARM::VST1LNdWB_fixed_Asm_16:
7272   case ARM::VST1LNdWB_fixed_Asm_32: {
7273     MCInst TmpInst;
7274     // Shuffle the operands around so the lane index operand is in the
7275     // right place.
7276     unsigned Spacing;
7277     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7278     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7279     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7280     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7281     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7282     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7283     TmpInst.addOperand(Inst.getOperand(1)); // lane
7284     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7285     TmpInst.addOperand(Inst.getOperand(5));
7286     Inst = TmpInst;
7287     return true;
7288   }
7289 
7290   case ARM::VST2LNdWB_fixed_Asm_8:
7291   case ARM::VST2LNdWB_fixed_Asm_16:
7292   case ARM::VST2LNdWB_fixed_Asm_32:
7293   case ARM::VST2LNqWB_fixed_Asm_16:
7294   case ARM::VST2LNqWB_fixed_Asm_32: {
7295     MCInst TmpInst;
7296     // Shuffle the operands around so the lane index operand is in the
7297     // right place.
7298     unsigned Spacing;
7299     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7300     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7301     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7302     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7303     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7304     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7305     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7306                                             Spacing));
7307     TmpInst.addOperand(Inst.getOperand(1)); // lane
7308     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7309     TmpInst.addOperand(Inst.getOperand(5));
7310     Inst = TmpInst;
7311     return true;
7312   }
7313 
7314   case ARM::VST3LNdWB_fixed_Asm_8:
7315   case ARM::VST3LNdWB_fixed_Asm_16:
7316   case ARM::VST3LNdWB_fixed_Asm_32:
7317   case ARM::VST3LNqWB_fixed_Asm_16:
7318   case ARM::VST3LNqWB_fixed_Asm_32: {
7319     MCInst TmpInst;
7320     // Shuffle the operands around so the lane index operand is in the
7321     // right place.
7322     unsigned Spacing;
7323     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7324     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7325     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7326     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7327     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7328     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7329     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7330                                             Spacing));
7331     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7332                                             Spacing * 2));
7333     TmpInst.addOperand(Inst.getOperand(1)); // lane
7334     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7335     TmpInst.addOperand(Inst.getOperand(5));
7336     Inst = TmpInst;
7337     return true;
7338   }
7339 
7340   case ARM::VST4LNdWB_fixed_Asm_8:
7341   case ARM::VST4LNdWB_fixed_Asm_16:
7342   case ARM::VST4LNdWB_fixed_Asm_32:
7343   case ARM::VST4LNqWB_fixed_Asm_16:
7344   case ARM::VST4LNqWB_fixed_Asm_32: {
7345     MCInst TmpInst;
7346     // Shuffle the operands around so the lane index operand is in the
7347     // right place.
7348     unsigned Spacing;
7349     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7350     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7351     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7352     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7353     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7354     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7355     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7356                                             Spacing));
7357     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7358                                             Spacing * 2));
7359     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7360                                             Spacing * 3));
7361     TmpInst.addOperand(Inst.getOperand(1)); // lane
7362     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7363     TmpInst.addOperand(Inst.getOperand(5));
7364     Inst = TmpInst;
7365     return true;
7366   }
7367 
7368   case ARM::VST1LNdAsm_8:
7369   case ARM::VST1LNdAsm_16:
7370   case ARM::VST1LNdAsm_32: {
7371     MCInst TmpInst;
7372     // Shuffle the operands around so the lane index operand is in the
7373     // right place.
7374     unsigned Spacing;
7375     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7376     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7377     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7378     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7379     TmpInst.addOperand(Inst.getOperand(1)); // lane
7380     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7381     TmpInst.addOperand(Inst.getOperand(5));
7382     Inst = TmpInst;
7383     return true;
7384   }
7385 
7386   case ARM::VST2LNdAsm_8:
7387   case ARM::VST2LNdAsm_16:
7388   case ARM::VST2LNdAsm_32:
7389   case ARM::VST2LNqAsm_16:
7390   case ARM::VST2LNqAsm_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(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7396     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7397     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7398     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7399     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7400                                             Spacing));
7401     TmpInst.addOperand(Inst.getOperand(1)); // lane
7402     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7403     TmpInst.addOperand(Inst.getOperand(5));
7404     Inst = TmpInst;
7405     return true;
7406   }
7407 
7408   case ARM::VST3LNdAsm_8:
7409   case ARM::VST3LNdAsm_16:
7410   case ARM::VST3LNdAsm_32:
7411   case ARM::VST3LNqAsm_16:
7412   case ARM::VST3LNqAsm_32: {
7413     MCInst TmpInst;
7414     // Shuffle the operands around so the lane index operand is in the
7415     // right place.
7416     unsigned Spacing;
7417     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7418     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7419     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7420     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7421     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7422                                             Spacing));
7423     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7424                                             Spacing * 2));
7425     TmpInst.addOperand(Inst.getOperand(1)); // lane
7426     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7427     TmpInst.addOperand(Inst.getOperand(5));
7428     Inst = TmpInst;
7429     return true;
7430   }
7431 
7432   case ARM::VST4LNdAsm_8:
7433   case ARM::VST4LNdAsm_16:
7434   case ARM::VST4LNdAsm_32:
7435   case ARM::VST4LNqAsm_16:
7436   case ARM::VST4LNqAsm_32: {
7437     MCInst TmpInst;
7438     // Shuffle the operands around so the lane index operand is in the
7439     // right place.
7440     unsigned Spacing;
7441     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7442     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7443     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7444     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7445     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7446                                             Spacing));
7447     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7448                                             Spacing * 2));
7449     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7450                                             Spacing * 3));
7451     TmpInst.addOperand(Inst.getOperand(1)); // lane
7452     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7453     TmpInst.addOperand(Inst.getOperand(5));
7454     Inst = TmpInst;
7455     return true;
7456   }
7457 
7458   // Handle NEON VLD complex aliases.
7459   case ARM::VLD1LNdWB_register_Asm_8:
7460   case ARM::VLD1LNdWB_register_Asm_16:
7461   case ARM::VLD1LNdWB_register_Asm_32: {
7462     MCInst TmpInst;
7463     // Shuffle the operands around so the lane index operand is in the
7464     // right place.
7465     unsigned Spacing;
7466     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7467     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7468     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7469     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7470     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7471     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7472     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7473     TmpInst.addOperand(Inst.getOperand(1)); // lane
7474     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7475     TmpInst.addOperand(Inst.getOperand(6));
7476     Inst = TmpInst;
7477     return true;
7478   }
7479 
7480   case ARM::VLD2LNdWB_register_Asm_8:
7481   case ARM::VLD2LNdWB_register_Asm_16:
7482   case ARM::VLD2LNdWB_register_Asm_32:
7483   case ARM::VLD2LNqWB_register_Asm_16:
7484   case ARM::VLD2LNqWB_register_Asm_32: {
7485     MCInst TmpInst;
7486     // Shuffle the operands around so the lane index operand is in the
7487     // right place.
7488     unsigned Spacing;
7489     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7490     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7491     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7492                                             Spacing));
7493     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7494     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7495     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7496     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7497     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7498     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7499                                             Spacing));
7500     TmpInst.addOperand(Inst.getOperand(1)); // lane
7501     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7502     TmpInst.addOperand(Inst.getOperand(6));
7503     Inst = TmpInst;
7504     return true;
7505   }
7506 
7507   case ARM::VLD3LNdWB_register_Asm_8:
7508   case ARM::VLD3LNdWB_register_Asm_16:
7509   case ARM::VLD3LNdWB_register_Asm_32:
7510   case ARM::VLD3LNqWB_register_Asm_16:
7511   case ARM::VLD3LNqWB_register_Asm_32: {
7512     MCInst TmpInst;
7513     // Shuffle the operands around so the lane index operand is in the
7514     // right place.
7515     unsigned Spacing;
7516     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7517     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7518     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7519                                             Spacing));
7520     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7521                                             Spacing * 2));
7522     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7523     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7524     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7525     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7526     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7527     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7528                                             Spacing));
7529     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7530                                             Spacing * 2));
7531     TmpInst.addOperand(Inst.getOperand(1)); // lane
7532     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7533     TmpInst.addOperand(Inst.getOperand(6));
7534     Inst = TmpInst;
7535     return true;
7536   }
7537 
7538   case ARM::VLD4LNdWB_register_Asm_8:
7539   case ARM::VLD4LNdWB_register_Asm_16:
7540   case ARM::VLD4LNdWB_register_Asm_32:
7541   case ARM::VLD4LNqWB_register_Asm_16:
7542   case ARM::VLD4LNqWB_register_Asm_32: {
7543     MCInst TmpInst;
7544     // Shuffle the operands around so the lane index operand is in the
7545     // right place.
7546     unsigned Spacing;
7547     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7548     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7549     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7550                                             Spacing));
7551     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7552                                             Spacing * 2));
7553     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7554                                             Spacing * 3));
7555     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7556     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7557     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7558     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7559     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7560     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7561                                             Spacing));
7562     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7563                                             Spacing * 2));
7564     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7565                                             Spacing * 3));
7566     TmpInst.addOperand(Inst.getOperand(1)); // lane
7567     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7568     TmpInst.addOperand(Inst.getOperand(6));
7569     Inst = TmpInst;
7570     return true;
7571   }
7572 
7573   case ARM::VLD1LNdWB_fixed_Asm_8:
7574   case ARM::VLD1LNdWB_fixed_Asm_16:
7575   case ARM::VLD1LNdWB_fixed_Asm_32: {
7576     MCInst TmpInst;
7577     // Shuffle the operands around so the lane index operand is in the
7578     // right place.
7579     unsigned Spacing;
7580     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7581     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7582     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7583     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7584     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7585     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7586     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7587     TmpInst.addOperand(Inst.getOperand(1)); // lane
7588     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7589     TmpInst.addOperand(Inst.getOperand(5));
7590     Inst = TmpInst;
7591     return true;
7592   }
7593 
7594   case ARM::VLD2LNdWB_fixed_Asm_8:
7595   case ARM::VLD2LNdWB_fixed_Asm_16:
7596   case ARM::VLD2LNdWB_fixed_Asm_32:
7597   case ARM::VLD2LNqWB_fixed_Asm_16:
7598   case ARM::VLD2LNqWB_fixed_Asm_32: {
7599     MCInst TmpInst;
7600     // Shuffle the operands around so the lane index operand is in the
7601     // right place.
7602     unsigned Spacing;
7603     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7604     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7605     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7606                                             Spacing));
7607     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7608     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7609     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7610     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7611     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7612     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7613                                             Spacing));
7614     TmpInst.addOperand(Inst.getOperand(1)); // lane
7615     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7616     TmpInst.addOperand(Inst.getOperand(5));
7617     Inst = TmpInst;
7618     return true;
7619   }
7620 
7621   case ARM::VLD3LNdWB_fixed_Asm_8:
7622   case ARM::VLD3LNdWB_fixed_Asm_16:
7623   case ARM::VLD3LNdWB_fixed_Asm_32:
7624   case ARM::VLD3LNqWB_fixed_Asm_16:
7625   case ARM::VLD3LNqWB_fixed_Asm_32: {
7626     MCInst TmpInst;
7627     // Shuffle the operands around so the lane index operand is in the
7628     // right place.
7629     unsigned Spacing;
7630     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7631     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7632     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7633                                             Spacing));
7634     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7635                                             Spacing * 2));
7636     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7637     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7638     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7639     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7640     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7641     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7642                                             Spacing));
7643     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7644                                             Spacing * 2));
7645     TmpInst.addOperand(Inst.getOperand(1)); // lane
7646     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7647     TmpInst.addOperand(Inst.getOperand(5));
7648     Inst = TmpInst;
7649     return true;
7650   }
7651 
7652   case ARM::VLD4LNdWB_fixed_Asm_8:
7653   case ARM::VLD4LNdWB_fixed_Asm_16:
7654   case ARM::VLD4LNdWB_fixed_Asm_32:
7655   case ARM::VLD4LNqWB_fixed_Asm_16:
7656   case ARM::VLD4LNqWB_fixed_Asm_32: {
7657     MCInst TmpInst;
7658     // Shuffle the operands around so the lane index operand is in the
7659     // right place.
7660     unsigned Spacing;
7661     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7662     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7663     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7664                                             Spacing));
7665     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7666                                             Spacing * 2));
7667     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7668                                             Spacing * 3));
7669     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7670     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7671     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7672     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7673     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== 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(MCOperand::createReg(Inst.getOperand(0).getReg() +
7679                                             Spacing * 3));
7680     TmpInst.addOperand(Inst.getOperand(1)); // lane
7681     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7682     TmpInst.addOperand(Inst.getOperand(5));
7683     Inst = TmpInst;
7684     return true;
7685   }
7686 
7687   case ARM::VLD1LNdAsm_8:
7688   case ARM::VLD1LNdAsm_16:
7689   case ARM::VLD1LNdAsm_32: {
7690     MCInst TmpInst;
7691     // Shuffle the operands around so the lane index operand is in the
7692     // right place.
7693     unsigned Spacing;
7694     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7695     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7696     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7697     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7698     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7699     TmpInst.addOperand(Inst.getOperand(1)); // lane
7700     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7701     TmpInst.addOperand(Inst.getOperand(5));
7702     Inst = TmpInst;
7703     return true;
7704   }
7705 
7706   case ARM::VLD2LNdAsm_8:
7707   case ARM::VLD2LNdAsm_16:
7708   case ARM::VLD2LNdAsm_32:
7709   case ARM::VLD2LNqAsm_16:
7710   case ARM::VLD2LNqAsm_32: {
7711     MCInst TmpInst;
7712     // Shuffle the operands around so the lane index operand is in the
7713     // right place.
7714     unsigned Spacing;
7715     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7716     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7717     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7718                                             Spacing));
7719     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7720     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7721     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7722     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7723                                             Spacing));
7724     TmpInst.addOperand(Inst.getOperand(1)); // lane
7725     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7726     TmpInst.addOperand(Inst.getOperand(5));
7727     Inst = TmpInst;
7728     return true;
7729   }
7730 
7731   case ARM::VLD3LNdAsm_8:
7732   case ARM::VLD3LNdAsm_16:
7733   case ARM::VLD3LNdAsm_32:
7734   case ARM::VLD3LNqAsm_16:
7735   case ARM::VLD3LNqAsm_32: {
7736     MCInst TmpInst;
7737     // Shuffle the operands around so the lane index operand is in the
7738     // right place.
7739     unsigned Spacing;
7740     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7741     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7742     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7743                                             Spacing));
7744     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7745                                             Spacing * 2));
7746     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7747     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7748     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7749     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7750                                             Spacing));
7751     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7752                                             Spacing * 2));
7753     TmpInst.addOperand(Inst.getOperand(1)); // lane
7754     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7755     TmpInst.addOperand(Inst.getOperand(5));
7756     Inst = TmpInst;
7757     return true;
7758   }
7759 
7760   case ARM::VLD4LNdAsm_8:
7761   case ARM::VLD4LNdAsm_16:
7762   case ARM::VLD4LNdAsm_32:
7763   case ARM::VLD4LNqAsm_16:
7764   case ARM::VLD4LNqAsm_32: {
7765     MCInst TmpInst;
7766     // Shuffle the operands around so the lane index operand is in the
7767     // right place.
7768     unsigned Spacing;
7769     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7770     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7771     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7772                                             Spacing));
7773     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7774                                             Spacing * 2));
7775     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7776                                             Spacing * 3));
7777     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7778     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7779     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7780     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7781                                             Spacing));
7782     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7783                                             Spacing * 2));
7784     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7785                                             Spacing * 3));
7786     TmpInst.addOperand(Inst.getOperand(1)); // lane
7787     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7788     TmpInst.addOperand(Inst.getOperand(5));
7789     Inst = TmpInst;
7790     return true;
7791   }
7792 
7793   // VLD3DUP single 3-element structure to all lanes instructions.
7794   case ARM::VLD3DUPdAsm_8:
7795   case ARM::VLD3DUPdAsm_16:
7796   case ARM::VLD3DUPdAsm_32:
7797   case ARM::VLD3DUPqAsm_8:
7798   case ARM::VLD3DUPqAsm_16:
7799   case ARM::VLD3DUPqAsm_32: {
7800     MCInst TmpInst;
7801     unsigned Spacing;
7802     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7803     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7804     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7805                                             Spacing));
7806     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7807                                             Spacing * 2));
7808     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7809     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7810     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7811     TmpInst.addOperand(Inst.getOperand(4));
7812     Inst = TmpInst;
7813     return true;
7814   }
7815 
7816   case ARM::VLD3DUPdWB_fixed_Asm_8:
7817   case ARM::VLD3DUPdWB_fixed_Asm_16:
7818   case ARM::VLD3DUPdWB_fixed_Asm_32:
7819   case ARM::VLD3DUPqWB_fixed_Asm_8:
7820   case ARM::VLD3DUPqWB_fixed_Asm_16:
7821   case ARM::VLD3DUPqWB_fixed_Asm_32: {
7822     MCInst TmpInst;
7823     unsigned Spacing;
7824     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7825     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7826     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7827                                             Spacing));
7828     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7829                                             Spacing * 2));
7830     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7831     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7832     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7833     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7834     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7835     TmpInst.addOperand(Inst.getOperand(4));
7836     Inst = TmpInst;
7837     return true;
7838   }
7839 
7840   case ARM::VLD3DUPdWB_register_Asm_8:
7841   case ARM::VLD3DUPdWB_register_Asm_16:
7842   case ARM::VLD3DUPdWB_register_Asm_32:
7843   case ARM::VLD3DUPqWB_register_Asm_8:
7844   case ARM::VLD3DUPqWB_register_Asm_16:
7845   case ARM::VLD3DUPqWB_register_Asm_32: {
7846     MCInst TmpInst;
7847     unsigned Spacing;
7848     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7849     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7850     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7851                                             Spacing));
7852     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7853                                             Spacing * 2));
7854     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7855     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7856     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7857     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7858     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7859     TmpInst.addOperand(Inst.getOperand(5));
7860     Inst = TmpInst;
7861     return true;
7862   }
7863 
7864   // VLD3 multiple 3-element structure instructions.
7865   case ARM::VLD3dAsm_8:
7866   case ARM::VLD3dAsm_16:
7867   case ARM::VLD3dAsm_32:
7868   case ARM::VLD3qAsm_8:
7869   case ARM::VLD3qAsm_16:
7870   case ARM::VLD3qAsm_32: {
7871     MCInst TmpInst;
7872     unsigned Spacing;
7873     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7874     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7875     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7876                                             Spacing));
7877     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7878                                             Spacing * 2));
7879     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7880     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7881     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7882     TmpInst.addOperand(Inst.getOperand(4));
7883     Inst = TmpInst;
7884     return true;
7885   }
7886 
7887   case ARM::VLD3dWB_fixed_Asm_8:
7888   case ARM::VLD3dWB_fixed_Asm_16:
7889   case ARM::VLD3dWB_fixed_Asm_32:
7890   case ARM::VLD3qWB_fixed_Asm_8:
7891   case ARM::VLD3qWB_fixed_Asm_16:
7892   case ARM::VLD3qWB_fixed_Asm_32: {
7893     MCInst TmpInst;
7894     unsigned Spacing;
7895     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7896     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7897     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7898                                             Spacing));
7899     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7900                                             Spacing * 2));
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::VLD3dWB_register_Asm_8:
7912   case ARM::VLD3dWB_register_Asm_16:
7913   case ARM::VLD3dWB_register_Asm_32:
7914   case ARM::VLD3qWB_register_Asm_8:
7915   case ARM::VLD3qWB_register_Asm_16:
7916   case ARM::VLD3qWB_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(Inst.getOperand(1)); // Rn
7926     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7927     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7928     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7929     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7930     TmpInst.addOperand(Inst.getOperand(5));
7931     Inst = TmpInst;
7932     return true;
7933   }
7934 
7935   // VLD4DUP single 3-element structure to all lanes instructions.
7936   case ARM::VLD4DUPdAsm_8:
7937   case ARM::VLD4DUPdAsm_16:
7938   case ARM::VLD4DUPdAsm_32:
7939   case ARM::VLD4DUPqAsm_8:
7940   case ARM::VLD4DUPqAsm_16:
7941   case ARM::VLD4DUPqAsm_32: {
7942     MCInst TmpInst;
7943     unsigned Spacing;
7944     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7945     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7946     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7947                                             Spacing));
7948     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7949                                             Spacing * 2));
7950     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7951                                             Spacing * 3));
7952     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7953     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7954     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7955     TmpInst.addOperand(Inst.getOperand(4));
7956     Inst = TmpInst;
7957     return true;
7958   }
7959 
7960   case ARM::VLD4DUPdWB_fixed_Asm_8:
7961   case ARM::VLD4DUPdWB_fixed_Asm_16:
7962   case ARM::VLD4DUPdWB_fixed_Asm_32:
7963   case ARM::VLD4DUPqWB_fixed_Asm_8:
7964   case ARM::VLD4DUPqWB_fixed_Asm_16:
7965   case ARM::VLD4DUPqWB_fixed_Asm_32: {
7966     MCInst TmpInst;
7967     unsigned Spacing;
7968     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7969     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7970     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7971                                             Spacing));
7972     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7973                                             Spacing * 2));
7974     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7975                                             Spacing * 3));
7976     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7977     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7978     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7979     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7980     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7981     TmpInst.addOperand(Inst.getOperand(4));
7982     Inst = TmpInst;
7983     return true;
7984   }
7985 
7986   case ARM::VLD4DUPdWB_register_Asm_8:
7987   case ARM::VLD4DUPdWB_register_Asm_16:
7988   case ARM::VLD4DUPdWB_register_Asm_32:
7989   case ARM::VLD4DUPqWB_register_Asm_8:
7990   case ARM::VLD4DUPqWB_register_Asm_16:
7991   case ARM::VLD4DUPqWB_register_Asm_32: {
7992     MCInst TmpInst;
7993     unsigned Spacing;
7994     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7995     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7996     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7997                                             Spacing));
7998     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7999                                             Spacing * 2));
8000     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8001                                             Spacing * 3));
8002     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8003     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8004     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8005     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8006     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8007     TmpInst.addOperand(Inst.getOperand(5));
8008     Inst = TmpInst;
8009     return true;
8010   }
8011 
8012   // VLD4 multiple 4-element structure instructions.
8013   case ARM::VLD4dAsm_8:
8014   case ARM::VLD4dAsm_16:
8015   case ARM::VLD4dAsm_32:
8016   case ARM::VLD4qAsm_8:
8017   case ARM::VLD4qAsm_16:
8018   case ARM::VLD4qAsm_32: {
8019     MCInst TmpInst;
8020     unsigned Spacing;
8021     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8022     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8023     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8024                                             Spacing));
8025     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8026                                             Spacing * 2));
8027     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8028                                             Spacing * 3));
8029     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8030     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8031     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8032     TmpInst.addOperand(Inst.getOperand(4));
8033     Inst = TmpInst;
8034     return true;
8035   }
8036 
8037   case ARM::VLD4dWB_fixed_Asm_8:
8038   case ARM::VLD4dWB_fixed_Asm_16:
8039   case ARM::VLD4dWB_fixed_Asm_32:
8040   case ARM::VLD4qWB_fixed_Asm_8:
8041   case ARM::VLD4qWB_fixed_Asm_16:
8042   case ARM::VLD4qWB_fixed_Asm_32: {
8043     MCInst TmpInst;
8044     unsigned Spacing;
8045     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
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(1)); // Rn
8054     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8055     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8056     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8057     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8058     TmpInst.addOperand(Inst.getOperand(4));
8059     Inst = TmpInst;
8060     return true;
8061   }
8062 
8063   case ARM::VLD4dWB_register_Asm_8:
8064   case ARM::VLD4dWB_register_Asm_16:
8065   case ARM::VLD4dWB_register_Asm_32:
8066   case ARM::VLD4qWB_register_Asm_8:
8067   case ARM::VLD4qWB_register_Asm_16:
8068   case ARM::VLD4qWB_register_Asm_32: {
8069     MCInst TmpInst;
8070     unsigned Spacing;
8071     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
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(1)); // Rn
8080     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8081     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8082     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8083     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8084     TmpInst.addOperand(Inst.getOperand(5));
8085     Inst = TmpInst;
8086     return true;
8087   }
8088 
8089   // VST3 multiple 3-element structure instructions.
8090   case ARM::VST3dAsm_8:
8091   case ARM::VST3dAsm_16:
8092   case ARM::VST3dAsm_32:
8093   case ARM::VST3qAsm_8:
8094   case ARM::VST3qAsm_16:
8095   case ARM::VST3qAsm_32: {
8096     MCInst TmpInst;
8097     unsigned Spacing;
8098     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8099     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8100     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8101     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8102     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8103                                             Spacing));
8104     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8105                                             Spacing * 2));
8106     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8107     TmpInst.addOperand(Inst.getOperand(4));
8108     Inst = TmpInst;
8109     return true;
8110   }
8111 
8112   case ARM::VST3dWB_fixed_Asm_8:
8113   case ARM::VST3dWB_fixed_Asm_16:
8114   case ARM::VST3dWB_fixed_Asm_32:
8115   case ARM::VST3qWB_fixed_Asm_8:
8116   case ARM::VST3qWB_fixed_Asm_16:
8117   case ARM::VST3qWB_fixed_Asm_32: {
8118     MCInst TmpInst;
8119     unsigned Spacing;
8120     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8121     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8122     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8123     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8124     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8125     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8126     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8127                                             Spacing));
8128     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8129                                             Spacing * 2));
8130     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8131     TmpInst.addOperand(Inst.getOperand(4));
8132     Inst = TmpInst;
8133     return true;
8134   }
8135 
8136   case ARM::VST3dWB_register_Asm_8:
8137   case ARM::VST3dWB_register_Asm_16:
8138   case ARM::VST3dWB_register_Asm_32:
8139   case ARM::VST3qWB_register_Asm_8:
8140   case ARM::VST3qWB_register_Asm_16:
8141   case ARM::VST3qWB_register_Asm_32: {
8142     MCInst TmpInst;
8143     unsigned Spacing;
8144     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8145     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8146     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8147     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8148     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8149     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8150     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8151                                             Spacing));
8152     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8153                                             Spacing * 2));
8154     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8155     TmpInst.addOperand(Inst.getOperand(5));
8156     Inst = TmpInst;
8157     return true;
8158   }
8159 
8160   // VST4 multiple 3-element structure instructions.
8161   case ARM::VST4dAsm_8:
8162   case ARM::VST4dAsm_16:
8163   case ARM::VST4dAsm_32:
8164   case ARM::VST4qAsm_8:
8165   case ARM::VST4qAsm_16:
8166   case ARM::VST4qAsm_32: {
8167     MCInst TmpInst;
8168     unsigned Spacing;
8169     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8170     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8171     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8172     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8173     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8174                                             Spacing));
8175     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8176                                             Spacing * 2));
8177     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8178                                             Spacing * 3));
8179     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8180     TmpInst.addOperand(Inst.getOperand(4));
8181     Inst = TmpInst;
8182     return true;
8183   }
8184 
8185   case ARM::VST4dWB_fixed_Asm_8:
8186   case ARM::VST4dWB_fixed_Asm_16:
8187   case ARM::VST4dWB_fixed_Asm_32:
8188   case ARM::VST4qWB_fixed_Asm_8:
8189   case ARM::VST4qWB_fixed_Asm_16:
8190   case ARM::VST4qWB_fixed_Asm_32: {
8191     MCInst TmpInst;
8192     unsigned Spacing;
8193     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8194     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8195     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8196     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8197     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8198     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8199     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8200                                             Spacing));
8201     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8202                                             Spacing * 2));
8203     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8204                                             Spacing * 3));
8205     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8206     TmpInst.addOperand(Inst.getOperand(4));
8207     Inst = TmpInst;
8208     return true;
8209   }
8210 
8211   case ARM::VST4dWB_register_Asm_8:
8212   case ARM::VST4dWB_register_Asm_16:
8213   case ARM::VST4dWB_register_Asm_32:
8214   case ARM::VST4qWB_register_Asm_8:
8215   case ARM::VST4qWB_register_Asm_16:
8216   case ARM::VST4qWB_register_Asm_32: {
8217     MCInst TmpInst;
8218     unsigned Spacing;
8219     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8220     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8221     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8222     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8223     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8224     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8225     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8226                                             Spacing));
8227     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8228                                             Spacing * 2));
8229     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8230                                             Spacing * 3));
8231     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8232     TmpInst.addOperand(Inst.getOperand(5));
8233     Inst = TmpInst;
8234     return true;
8235   }
8236 
8237   // Handle encoding choice for the shift-immediate instructions.
8238   case ARM::t2LSLri:
8239   case ARM::t2LSRri:
8240   case ARM::t2ASRri: {
8241     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8242         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8243         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8244         !(static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8245           static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w")) {
8246       unsigned NewOpc;
8247       switch (Inst.getOpcode()) {
8248       default: llvm_unreachable("unexpected opcode");
8249       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
8250       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
8251       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
8252       }
8253       // The Thumb1 operands aren't in the same order. Awesome, eh?
8254       MCInst TmpInst;
8255       TmpInst.setOpcode(NewOpc);
8256       TmpInst.addOperand(Inst.getOperand(0));
8257       TmpInst.addOperand(Inst.getOperand(5));
8258       TmpInst.addOperand(Inst.getOperand(1));
8259       TmpInst.addOperand(Inst.getOperand(2));
8260       TmpInst.addOperand(Inst.getOperand(3));
8261       TmpInst.addOperand(Inst.getOperand(4));
8262       Inst = TmpInst;
8263       return true;
8264     }
8265     return false;
8266   }
8267 
8268   // Handle the Thumb2 mode MOV complex aliases.
8269   case ARM::t2MOVsr:
8270   case ARM::t2MOVSsr: {
8271     // Which instruction to expand to depends on the CCOut operand and
8272     // whether we're in an IT block if the register operands are low
8273     // registers.
8274     bool isNarrow = false;
8275     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8276         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8277         isARMLowRegister(Inst.getOperand(2).getReg()) &&
8278         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8279         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr))
8280       isNarrow = true;
8281     MCInst TmpInst;
8282     unsigned newOpc;
8283     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
8284     default: llvm_unreachable("unexpected opcode!");
8285     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
8286     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
8287     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
8288     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
8289     }
8290     TmpInst.setOpcode(newOpc);
8291     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8292     if (isNarrow)
8293       TmpInst.addOperand(MCOperand::createReg(
8294           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8295     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8296     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8297     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8298     TmpInst.addOperand(Inst.getOperand(5));
8299     if (!isNarrow)
8300       TmpInst.addOperand(MCOperand::createReg(
8301           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8302     Inst = TmpInst;
8303     return true;
8304   }
8305   case ARM::t2MOVsi:
8306   case ARM::t2MOVSsi: {
8307     // Which instruction to expand to depends on the CCOut operand and
8308     // whether we're in an IT block if the register operands are low
8309     // registers.
8310     bool isNarrow = false;
8311     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8312         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8313         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi))
8314       isNarrow = true;
8315     MCInst TmpInst;
8316     unsigned newOpc;
8317     unsigned Shift = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8318     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
8319     bool isMov = false;
8320     // MOV rd, rm, LSL #0 is actually a MOV instruction
8321     if (Shift == ARM_AM::lsl && Amount == 0) {
8322       isMov = true;
8323       // The 16-bit encoding of MOV rd, rm, LSL #N is explicitly encoding T2 of
8324       // MOV (register) in the ARMv8-A and ARMv8-M manuals, and immediate 0 is
8325       // unpredictable in an IT block so the 32-bit encoding T3 has to be used
8326       // instead.
8327       if (inITBlock()) {
8328         isNarrow = false;
8329       }
8330       newOpc = isNarrow ? ARM::tMOVSr : ARM::t2MOVr;
8331     } else {
8332       switch(Shift) {
8333       default: llvm_unreachable("unexpected opcode!");
8334       case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
8335       case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
8336       case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
8337       case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
8338       case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
8339       }
8340     }
8341     if (Amount == 32) Amount = 0;
8342     TmpInst.setOpcode(newOpc);
8343     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8344     if (isNarrow && !isMov)
8345       TmpInst.addOperand(MCOperand::createReg(
8346           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8347     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8348     if (newOpc != ARM::t2RRX && !isMov)
8349       TmpInst.addOperand(MCOperand::createImm(Amount));
8350     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8351     TmpInst.addOperand(Inst.getOperand(4));
8352     if (!isNarrow)
8353       TmpInst.addOperand(MCOperand::createReg(
8354           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8355     Inst = TmpInst;
8356     return true;
8357   }
8358   // Handle the ARM mode MOV complex aliases.
8359   case ARM::ASRr:
8360   case ARM::LSRr:
8361   case ARM::LSLr:
8362   case ARM::RORr: {
8363     ARM_AM::ShiftOpc ShiftTy;
8364     switch(Inst.getOpcode()) {
8365     default: llvm_unreachable("unexpected opcode!");
8366     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
8367     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
8368     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
8369     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
8370     }
8371     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
8372     MCInst TmpInst;
8373     TmpInst.setOpcode(ARM::MOVsr);
8374     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8375     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8376     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8377     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8378     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8379     TmpInst.addOperand(Inst.getOperand(4));
8380     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8381     Inst = TmpInst;
8382     return true;
8383   }
8384   case ARM::ASRi:
8385   case ARM::LSRi:
8386   case ARM::LSLi:
8387   case ARM::RORi: {
8388     ARM_AM::ShiftOpc ShiftTy;
8389     switch(Inst.getOpcode()) {
8390     default: llvm_unreachable("unexpected opcode!");
8391     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
8392     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
8393     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
8394     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
8395     }
8396     // A shift by zero is a plain MOVr, not a MOVsi.
8397     unsigned Amt = Inst.getOperand(2).getImm();
8398     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
8399     // A shift by 32 should be encoded as 0 when permitted
8400     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
8401       Amt = 0;
8402     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
8403     MCInst TmpInst;
8404     TmpInst.setOpcode(Opc);
8405     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8406     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8407     if (Opc == ARM::MOVsi)
8408       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8409     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8410     TmpInst.addOperand(Inst.getOperand(4));
8411     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8412     Inst = TmpInst;
8413     return true;
8414   }
8415   case ARM::RRXi: {
8416     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
8417     MCInst TmpInst;
8418     TmpInst.setOpcode(ARM::MOVsi);
8419     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8420     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8421     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8422     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8423     TmpInst.addOperand(Inst.getOperand(3));
8424     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
8425     Inst = TmpInst;
8426     return true;
8427   }
8428   case ARM::t2LDMIA_UPD: {
8429     // If this is a load of a single register, then we should use
8430     // a post-indexed LDR instruction instead, per the ARM ARM.
8431     if (Inst.getNumOperands() != 5)
8432       return false;
8433     MCInst TmpInst;
8434     TmpInst.setOpcode(ARM::t2LDR_POST);
8435     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8436     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8437     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8438     TmpInst.addOperand(MCOperand::createImm(4));
8439     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8440     TmpInst.addOperand(Inst.getOperand(3));
8441     Inst = TmpInst;
8442     return true;
8443   }
8444   case ARM::t2STMDB_UPD: {
8445     // If this is a store of a single register, then we should use
8446     // a pre-indexed STR instruction instead, per the ARM ARM.
8447     if (Inst.getNumOperands() != 5)
8448       return false;
8449     MCInst TmpInst;
8450     TmpInst.setOpcode(ARM::t2STR_PRE);
8451     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8452     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8453     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8454     TmpInst.addOperand(MCOperand::createImm(-4));
8455     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8456     TmpInst.addOperand(Inst.getOperand(3));
8457     Inst = TmpInst;
8458     return true;
8459   }
8460   case ARM::LDMIA_UPD:
8461     // If this is a load of a single register via a 'pop', then we should use
8462     // a post-indexed LDR instruction instead, per the ARM ARM.
8463     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
8464         Inst.getNumOperands() == 5) {
8465       MCInst TmpInst;
8466       TmpInst.setOpcode(ARM::LDR_POST_IMM);
8467       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8468       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8469       TmpInst.addOperand(Inst.getOperand(1)); // Rn
8470       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
8471       TmpInst.addOperand(MCOperand::createImm(4));
8472       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8473       TmpInst.addOperand(Inst.getOperand(3));
8474       Inst = TmpInst;
8475       return true;
8476     }
8477     break;
8478   case ARM::STMDB_UPD:
8479     // If this is a store of a single register via a 'push', then we should use
8480     // a pre-indexed STR instruction instead, per the ARM ARM.
8481     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
8482         Inst.getNumOperands() == 5) {
8483       MCInst TmpInst;
8484       TmpInst.setOpcode(ARM::STR_PRE_IMM);
8485       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8486       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8487       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
8488       TmpInst.addOperand(MCOperand::createImm(-4));
8489       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8490       TmpInst.addOperand(Inst.getOperand(3));
8491       Inst = TmpInst;
8492     }
8493     break;
8494   case ARM::t2ADDri12:
8495     // If the immediate fits for encoding T3 (t2ADDri) and the generic "add"
8496     // mnemonic was used (not "addw"), encoding T3 is preferred.
8497     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "add" ||
8498         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8499       break;
8500     Inst.setOpcode(ARM::t2ADDri);
8501     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8502     break;
8503   case ARM::t2SUBri12:
8504     // If the immediate fits for encoding T3 (t2SUBri) and the generic "sub"
8505     // mnemonic was used (not "subw"), encoding T3 is preferred.
8506     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "sub" ||
8507         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8508       break;
8509     Inst.setOpcode(ARM::t2SUBri);
8510     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8511     break;
8512   case ARM::tADDi8:
8513     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8514     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8515     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8516     // to encoding T1 if <Rd> is omitted."
8517     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8518       Inst.setOpcode(ARM::tADDi3);
8519       return true;
8520     }
8521     break;
8522   case ARM::tSUBi8:
8523     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8524     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8525     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8526     // to encoding T1 if <Rd> is omitted."
8527     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8528       Inst.setOpcode(ARM::tSUBi3);
8529       return true;
8530     }
8531     break;
8532   case ARM::t2ADDri:
8533   case ARM::t2SUBri: {
8534     // If the destination and first source operand are the same, and
8535     // the flags are compatible with the current IT status, use encoding T2
8536     // instead of T3. For compatibility with the system 'as'. Make sure the
8537     // wide encoding wasn't explicit.
8538     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
8539         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
8540         (unsigned)Inst.getOperand(2).getImm() > 255 ||
8541         ((!inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR) ||
8542          (inITBlock() && Inst.getOperand(5).getReg() != 0)) ||
8543         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8544          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w"))
8545       break;
8546     MCInst TmpInst;
8547     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
8548                       ARM::tADDi8 : ARM::tSUBi8);
8549     TmpInst.addOperand(Inst.getOperand(0));
8550     TmpInst.addOperand(Inst.getOperand(5));
8551     TmpInst.addOperand(Inst.getOperand(0));
8552     TmpInst.addOperand(Inst.getOperand(2));
8553     TmpInst.addOperand(Inst.getOperand(3));
8554     TmpInst.addOperand(Inst.getOperand(4));
8555     Inst = TmpInst;
8556     return true;
8557   }
8558   case ARM::t2ADDrr: {
8559     // If the destination and first source operand are the same, and
8560     // there's no setting of the flags, use encoding T2 instead of T3.
8561     // Note that this is only for ADD, not SUB. This mirrors the system
8562     // 'as' behaviour.  Also take advantage of ADD being commutative.
8563     // Make sure the wide encoding wasn't explicit.
8564     bool Swap = false;
8565     auto DestReg = Inst.getOperand(0).getReg();
8566     bool Transform = DestReg == Inst.getOperand(1).getReg();
8567     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
8568       Transform = true;
8569       Swap = true;
8570     }
8571     if (!Transform ||
8572         Inst.getOperand(5).getReg() != 0 ||
8573         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8574          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w"))
8575       break;
8576     MCInst TmpInst;
8577     TmpInst.setOpcode(ARM::tADDhirr);
8578     TmpInst.addOperand(Inst.getOperand(0));
8579     TmpInst.addOperand(Inst.getOperand(0));
8580     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
8581     TmpInst.addOperand(Inst.getOperand(3));
8582     TmpInst.addOperand(Inst.getOperand(4));
8583     Inst = TmpInst;
8584     return true;
8585   }
8586   case ARM::tADDrSP: {
8587     // If the non-SP source operand and the destination operand are not the
8588     // same, we need to use the 32-bit encoding if it's available.
8589     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
8590       Inst.setOpcode(ARM::t2ADDrr);
8591       Inst.addOperand(MCOperand::createReg(0)); // cc_out
8592       return true;
8593     }
8594     break;
8595   }
8596   case ARM::tB:
8597     // A Thumb conditional branch outside of an IT block is a tBcc.
8598     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
8599       Inst.setOpcode(ARM::tBcc);
8600       return true;
8601     }
8602     break;
8603   case ARM::t2B:
8604     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
8605     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
8606       Inst.setOpcode(ARM::t2Bcc);
8607       return true;
8608     }
8609     break;
8610   case ARM::t2Bcc:
8611     // If the conditional is AL or we're in an IT block, we really want t2B.
8612     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
8613       Inst.setOpcode(ARM::t2B);
8614       return true;
8615     }
8616     break;
8617   case ARM::tBcc:
8618     // If the conditional is AL, we really want tB.
8619     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
8620       Inst.setOpcode(ARM::tB);
8621       return true;
8622     }
8623     break;
8624   case ARM::tLDMIA: {
8625     // If the register list contains any high registers, or if the writeback
8626     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
8627     // instead if we're in Thumb2. Otherwise, this should have generated
8628     // an error in validateInstruction().
8629     unsigned Rn = Inst.getOperand(0).getReg();
8630     bool hasWritebackToken =
8631         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8632          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
8633     bool listContainsBase;
8634     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
8635         (!listContainsBase && !hasWritebackToken) ||
8636         (listContainsBase && hasWritebackToken)) {
8637       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8638       assert (isThumbTwo());
8639       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
8640       // If we're switching to the updating version, we need to insert
8641       // the writeback tied operand.
8642       if (hasWritebackToken)
8643         Inst.insert(Inst.begin(),
8644                     MCOperand::createReg(Inst.getOperand(0).getReg()));
8645       return true;
8646     }
8647     break;
8648   }
8649   case ARM::tSTMIA_UPD: {
8650     // If the register list contains any high registers, we need to use
8651     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8652     // should have generated an error in validateInstruction().
8653     unsigned Rn = Inst.getOperand(0).getReg();
8654     bool listContainsBase;
8655     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
8656       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8657       assert (isThumbTwo());
8658       Inst.setOpcode(ARM::t2STMIA_UPD);
8659       return true;
8660     }
8661     break;
8662   }
8663   case ARM::tPOP: {
8664     bool listContainsBase;
8665     // If the register list contains any high registers, we need to use
8666     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8667     // should have generated an error in validateInstruction().
8668     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
8669       return false;
8670     assert (isThumbTwo());
8671     Inst.setOpcode(ARM::t2LDMIA_UPD);
8672     // Add the base register and writeback operands.
8673     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8674     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8675     return true;
8676   }
8677   case ARM::tPUSH: {
8678     bool listContainsBase;
8679     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
8680       return false;
8681     assert (isThumbTwo());
8682     Inst.setOpcode(ARM::t2STMDB_UPD);
8683     // Add the base register and writeback operands.
8684     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8685     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8686     return true;
8687   }
8688   case ARM::t2MOVi: {
8689     // If we can use the 16-bit encoding and the user didn't explicitly
8690     // request the 32-bit variant, transform it here.
8691     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8692         (unsigned)Inst.getOperand(1).getImm() <= 255 &&
8693         ((!inITBlock() && Inst.getOperand(2).getImm() == ARMCC::AL &&
8694           Inst.getOperand(4).getReg() == ARM::CPSR) ||
8695          (inITBlock() && Inst.getOperand(4).getReg() == 0)) &&
8696         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8697          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8698       // The operands aren't in the same order for tMOVi8...
8699       MCInst TmpInst;
8700       TmpInst.setOpcode(ARM::tMOVi8);
8701       TmpInst.addOperand(Inst.getOperand(0));
8702       TmpInst.addOperand(Inst.getOperand(4));
8703       TmpInst.addOperand(Inst.getOperand(1));
8704       TmpInst.addOperand(Inst.getOperand(2));
8705       TmpInst.addOperand(Inst.getOperand(3));
8706       Inst = TmpInst;
8707       return true;
8708     }
8709     break;
8710   }
8711   case ARM::t2MOVr: {
8712     // If we can use the 16-bit encoding and the user didn't explicitly
8713     // request the 32-bit variant, transform it here.
8714     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8715         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8716         Inst.getOperand(2).getImm() == ARMCC::AL &&
8717         Inst.getOperand(4).getReg() == ARM::CPSR &&
8718         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8719          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8720       // The operands aren't the same for tMOV[S]r... (no cc_out)
8721       MCInst TmpInst;
8722       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
8723       TmpInst.addOperand(Inst.getOperand(0));
8724       TmpInst.addOperand(Inst.getOperand(1));
8725       TmpInst.addOperand(Inst.getOperand(2));
8726       TmpInst.addOperand(Inst.getOperand(3));
8727       Inst = TmpInst;
8728       return true;
8729     }
8730     break;
8731   }
8732   case ARM::t2SXTH:
8733   case ARM::t2SXTB:
8734   case ARM::t2UXTH:
8735   case ARM::t2UXTB: {
8736     // If we can use the 16-bit encoding and the user didn't explicitly
8737     // request the 32-bit variant, transform it here.
8738     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8739         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8740         Inst.getOperand(2).getImm() == 0 &&
8741         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8742          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8743       unsigned NewOpc;
8744       switch (Inst.getOpcode()) {
8745       default: llvm_unreachable("Illegal opcode!");
8746       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
8747       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
8748       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
8749       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
8750       }
8751       // The operands aren't the same for thumb1 (no rotate operand).
8752       MCInst TmpInst;
8753       TmpInst.setOpcode(NewOpc);
8754       TmpInst.addOperand(Inst.getOperand(0));
8755       TmpInst.addOperand(Inst.getOperand(1));
8756       TmpInst.addOperand(Inst.getOperand(3));
8757       TmpInst.addOperand(Inst.getOperand(4));
8758       Inst = TmpInst;
8759       return true;
8760     }
8761     break;
8762   }
8763   case ARM::MOVsi: {
8764     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8765     // rrx shifts and asr/lsr of #32 is encoded as 0
8766     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr)
8767       return false;
8768     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
8769       // Shifting by zero is accepted as a vanilla 'MOVr'
8770       MCInst TmpInst;
8771       TmpInst.setOpcode(ARM::MOVr);
8772       TmpInst.addOperand(Inst.getOperand(0));
8773       TmpInst.addOperand(Inst.getOperand(1));
8774       TmpInst.addOperand(Inst.getOperand(3));
8775       TmpInst.addOperand(Inst.getOperand(4));
8776       TmpInst.addOperand(Inst.getOperand(5));
8777       Inst = TmpInst;
8778       return true;
8779     }
8780     return false;
8781   }
8782   case ARM::ANDrsi:
8783   case ARM::ORRrsi:
8784   case ARM::EORrsi:
8785   case ARM::BICrsi:
8786   case ARM::SUBrsi:
8787   case ARM::ADDrsi: {
8788     unsigned newOpc;
8789     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
8790     if (SOpc == ARM_AM::rrx) return false;
8791     switch (Inst.getOpcode()) {
8792     default: llvm_unreachable("unexpected opcode!");
8793     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
8794     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
8795     case ARM::EORrsi: newOpc = ARM::EORrr; break;
8796     case ARM::BICrsi: newOpc = ARM::BICrr; break;
8797     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
8798     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
8799     }
8800     // If the shift is by zero, use the non-shifted instruction definition.
8801     // The exception is for right shifts, where 0 == 32
8802     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
8803         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
8804       MCInst TmpInst;
8805       TmpInst.setOpcode(newOpc);
8806       TmpInst.addOperand(Inst.getOperand(0));
8807       TmpInst.addOperand(Inst.getOperand(1));
8808       TmpInst.addOperand(Inst.getOperand(2));
8809       TmpInst.addOperand(Inst.getOperand(4));
8810       TmpInst.addOperand(Inst.getOperand(5));
8811       TmpInst.addOperand(Inst.getOperand(6));
8812       Inst = TmpInst;
8813       return true;
8814     }
8815     return false;
8816   }
8817   case ARM::ITasm:
8818   case ARM::t2IT: {
8819     MCOperand &MO = Inst.getOperand(1);
8820     unsigned Mask = MO.getImm();
8821     ARMCC::CondCodes Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
8822 
8823     // Set up the IT block state according to the IT instruction we just
8824     // matched.
8825     assert(!inITBlock() && "nested IT blocks?!");
8826     startExplicitITBlock(Cond, Mask);
8827     MO.setImm(getITMaskEncoding());
8828     break;
8829   }
8830   case ARM::t2LSLrr:
8831   case ARM::t2LSRrr:
8832   case ARM::t2ASRrr:
8833   case ARM::t2SBCrr:
8834   case ARM::t2RORrr:
8835   case ARM::t2BICrr:
8836   {
8837     // Assemblers should use the narrow encodings of these instructions when permissible.
8838     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8839          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8840         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8841         ((!inITBlock() && Inst.getOperand(5).getReg() == ARM::CPSR) ||
8842          (inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR)) &&
8843         (!static_cast<ARMOperand &>(*Operands[3]).isToken() ||
8844          !static_cast<ARMOperand &>(*Operands[3]).getToken().equals_lower(
8845              ".w"))) {
8846       unsigned NewOpc;
8847       switch (Inst.getOpcode()) {
8848         default: llvm_unreachable("unexpected opcode");
8849         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
8850         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
8851         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
8852         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
8853         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
8854         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
8855       }
8856       MCInst TmpInst;
8857       TmpInst.setOpcode(NewOpc);
8858       TmpInst.addOperand(Inst.getOperand(0));
8859       TmpInst.addOperand(Inst.getOperand(5));
8860       TmpInst.addOperand(Inst.getOperand(1));
8861       TmpInst.addOperand(Inst.getOperand(2));
8862       TmpInst.addOperand(Inst.getOperand(3));
8863       TmpInst.addOperand(Inst.getOperand(4));
8864       Inst = TmpInst;
8865       return true;
8866     }
8867     return false;
8868   }
8869   case ARM::t2ANDrr:
8870   case ARM::t2EORrr:
8871   case ARM::t2ADCrr:
8872   case ARM::t2ORRrr:
8873   {
8874     // Assemblers should use the narrow encodings of these instructions when permissible.
8875     // These instructions are special in that they are commutable, so shorter encodings
8876     // are available more often.
8877     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8878          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8879         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
8880          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
8881         ((!inITBlock() && Inst.getOperand(5).getReg() == ARM::CPSR) ||
8882          (inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR)) &&
8883         (!static_cast<ARMOperand &>(*Operands[3]).isToken() ||
8884          !static_cast<ARMOperand &>(*Operands[3]).getToken().equals_lower(
8885              ".w"))) {
8886       unsigned NewOpc;
8887       switch (Inst.getOpcode()) {
8888         default: llvm_unreachable("unexpected opcode");
8889         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
8890         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
8891         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
8892         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
8893       }
8894       MCInst TmpInst;
8895       TmpInst.setOpcode(NewOpc);
8896       TmpInst.addOperand(Inst.getOperand(0));
8897       TmpInst.addOperand(Inst.getOperand(5));
8898       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
8899         TmpInst.addOperand(Inst.getOperand(1));
8900         TmpInst.addOperand(Inst.getOperand(2));
8901       } else {
8902         TmpInst.addOperand(Inst.getOperand(2));
8903         TmpInst.addOperand(Inst.getOperand(1));
8904       }
8905       TmpInst.addOperand(Inst.getOperand(3));
8906       TmpInst.addOperand(Inst.getOperand(4));
8907       Inst = TmpInst;
8908       return true;
8909     }
8910     return false;
8911   }
8912   }
8913   return false;
8914 }
8915 
8916 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
8917   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
8918   // suffix depending on whether they're in an IT block or not.
8919   unsigned Opc = Inst.getOpcode();
8920   const MCInstrDesc &MCID = MII.get(Opc);
8921   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
8922     assert(MCID.hasOptionalDef() &&
8923            "optionally flag setting instruction missing optional def operand");
8924     assert(MCID.NumOperands == Inst.getNumOperands() &&
8925            "operand count mismatch!");
8926     // Find the optional-def operand (cc_out).
8927     unsigned OpNo;
8928     for (OpNo = 0;
8929          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
8930          ++OpNo)
8931       ;
8932     // If we're parsing Thumb1, reject it completely.
8933     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
8934       return Match_RequiresFlagSetting;
8935     // If we're parsing Thumb2, which form is legal depends on whether we're
8936     // in an IT block.
8937     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
8938         !inITBlock())
8939       return Match_RequiresITBlock;
8940     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
8941         inITBlock())
8942       return Match_RequiresNotITBlock;
8943     // LSL with zero immediate is not allowed in an IT block
8944     if (Opc == ARM::tLSLri && Inst.getOperand(3).getImm() == 0 && inITBlock())
8945       return Match_RequiresNotITBlock;
8946   } else if (isThumbOne()) {
8947     // Some high-register supporting Thumb1 encodings only allow both registers
8948     // to be from r0-r7 when in Thumb2.
8949     if (Opc == ARM::tADDhirr && !hasV6MOps() &&
8950         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8951         isARMLowRegister(Inst.getOperand(2).getReg()))
8952       return Match_RequiresThumb2;
8953     // Others only require ARMv6 or later.
8954     else if (Opc == ARM::tMOVr && !hasV6Ops() &&
8955              isARMLowRegister(Inst.getOperand(0).getReg()) &&
8956              isARMLowRegister(Inst.getOperand(1).getReg()))
8957       return Match_RequiresV6;
8958   }
8959 
8960   // Before ARMv8 the rules for when SP is allowed in t2MOVr are more complex
8961   // than the loop below can handle, so it uses the GPRnopc register class and
8962   // we do SP handling here.
8963   if (Opc == ARM::t2MOVr && !hasV8Ops())
8964   {
8965     // SP as both source and destination is not allowed
8966     if (Inst.getOperand(0).getReg() == ARM::SP &&
8967         Inst.getOperand(1).getReg() == ARM::SP)
8968       return Match_RequiresV8;
8969     // When flags-setting SP as either source or destination is not allowed
8970     if (Inst.getOperand(4).getReg() == ARM::CPSR &&
8971         (Inst.getOperand(0).getReg() == ARM::SP ||
8972          Inst.getOperand(1).getReg() == ARM::SP))
8973       return Match_RequiresV8;
8974   }
8975 
8976   for (unsigned I = 0; I < MCID.NumOperands; ++I)
8977     if (MCID.OpInfo[I].RegClass == ARM::rGPRRegClassID) {
8978       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
8979       if ((Inst.getOperand(I).getReg() == ARM::SP) && !hasV8Ops())
8980         return Match_RequiresV8;
8981       else if (Inst.getOperand(I).getReg() == ARM::PC)
8982         return Match_InvalidOperand;
8983     }
8984 
8985   return Match_Success;
8986 }
8987 
8988 namespace llvm {
8989 template <> inline bool IsCPSRDead<MCInst>(const MCInst *Instr) {
8990   return true; // In an assembly source, no need to second-guess
8991 }
8992 }
8993 
8994 // Returns true if Inst is unpredictable if it is in and IT block, but is not
8995 // the last instruction in the block.
8996 bool ARMAsmParser::isITBlockTerminator(MCInst &Inst) const {
8997   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8998 
8999   // All branch & call instructions terminate IT blocks.
9000   if (MCID.isTerminator() || MCID.isCall() || MCID.isReturn() ||
9001       MCID.isBranch() || MCID.isIndirectBranch())
9002     return true;
9003 
9004   // Any arithmetic instruction which writes to the PC also terminates the IT
9005   // block.
9006   for (unsigned OpIdx = 0; OpIdx < MCID.getNumDefs(); ++OpIdx) {
9007     MCOperand &Op = Inst.getOperand(OpIdx);
9008     if (Op.isReg() && Op.getReg() == ARM::PC)
9009       return true;
9010   }
9011 
9012   if (MCID.hasImplicitDefOfPhysReg(ARM::PC, MRI))
9013     return true;
9014 
9015   // Instructions with variable operand lists, which write to the variable
9016   // operands. We only care about Thumb instructions here, as ARM instructions
9017   // obviously can't be in an IT block.
9018   switch (Inst.getOpcode()) {
9019   case ARM::tLDMIA:
9020   case ARM::t2LDMIA:
9021   case ARM::t2LDMIA_UPD:
9022   case ARM::t2LDMDB:
9023   case ARM::t2LDMDB_UPD:
9024     if (listContainsReg(Inst, 3, ARM::PC))
9025       return true;
9026     break;
9027   case ARM::tPOP:
9028     if (listContainsReg(Inst, 2, ARM::PC))
9029       return true;
9030     break;
9031   }
9032 
9033   return false;
9034 }
9035 
9036 unsigned ARMAsmParser::MatchInstruction(OperandVector &Operands, MCInst &Inst,
9037                                           uint64_t &ErrorInfo,
9038                                           bool MatchingInlineAsm,
9039                                           bool &EmitInITBlock,
9040                                           MCStreamer &Out) {
9041   // If we can't use an implicit IT block here, just match as normal.
9042   if (inExplicitITBlock() || !isThumbTwo() || !useImplicitITThumb())
9043     return MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
9044 
9045   // Try to match the instruction in an extension of the current IT block (if
9046   // there is one).
9047   if (inImplicitITBlock()) {
9048     extendImplicitITBlock(ITState.Cond);
9049     if (MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm) ==
9050             Match_Success) {
9051       // The match succeded, but we still have to check that the instruction is
9052       // valid in this implicit IT block.
9053       const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
9054       if (MCID.isPredicable()) {
9055         ARMCC::CondCodes InstCond =
9056             (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
9057                 .getImm();
9058         ARMCC::CondCodes ITCond = currentITCond();
9059         if (InstCond == ITCond) {
9060           EmitInITBlock = true;
9061           return Match_Success;
9062         } else if (InstCond == ARMCC::getOppositeCondition(ITCond)) {
9063           invertCurrentITCondition();
9064           EmitInITBlock = true;
9065           return Match_Success;
9066         }
9067       }
9068     }
9069     rewindImplicitITPosition();
9070   }
9071 
9072   // Finish the current IT block, and try to match outside any IT block.
9073   flushPendingInstructions(Out);
9074   unsigned PlainMatchResult =
9075       MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
9076   if (PlainMatchResult == Match_Success) {
9077     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
9078     if (MCID.isPredicable()) {
9079       ARMCC::CondCodes InstCond =
9080           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
9081               .getImm();
9082       // Some forms of the branch instruction have their own condition code
9083       // fields, so can be conditionally executed without an IT block.
9084       if (Inst.getOpcode() == ARM::tBcc || Inst.getOpcode() == ARM::t2Bcc) {
9085         EmitInITBlock = false;
9086         return Match_Success;
9087       }
9088       if (InstCond == ARMCC::AL) {
9089         EmitInITBlock = false;
9090         return Match_Success;
9091       }
9092     } else {
9093       EmitInITBlock = false;
9094       return Match_Success;
9095     }
9096   }
9097 
9098   // Try to match in a new IT block. The matcher doesn't check the actual
9099   // condition, so we create an IT block with a dummy condition, and fix it up
9100   // once we know the actual condition.
9101   startImplicitITBlock();
9102   if (MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm) ==
9103       Match_Success) {
9104     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
9105     if (MCID.isPredicable()) {
9106       ITState.Cond =
9107           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
9108               .getImm();
9109       EmitInITBlock = true;
9110       return Match_Success;
9111     }
9112   }
9113   discardImplicitITBlock();
9114 
9115   // If none of these succeed, return the error we got when trying to match
9116   // outside any IT blocks.
9117   EmitInITBlock = false;
9118   return PlainMatchResult;
9119 }
9120 
9121 static const char *getSubtargetFeatureName(uint64_t Val);
9122 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
9123                                            OperandVector &Operands,
9124                                            MCStreamer &Out, uint64_t &ErrorInfo,
9125                                            bool MatchingInlineAsm) {
9126   MCInst Inst;
9127   unsigned MatchResult;
9128   bool PendConditionalInstruction = false;
9129 
9130   MatchResult = MatchInstruction(Operands, Inst, ErrorInfo, MatchingInlineAsm,
9131                                  PendConditionalInstruction, Out);
9132 
9133   switch (MatchResult) {
9134   case Match_Success:
9135     // Context sensitive operand constraints aren't handled by the matcher,
9136     // so check them here.
9137     if (validateInstruction(Inst, Operands)) {
9138       // Still progress the IT block, otherwise one wrong condition causes
9139       // nasty cascading errors.
9140       forwardITPosition();
9141       return true;
9142     }
9143 
9144     { // processInstruction() updates inITBlock state, we need to save it away
9145       bool wasInITBlock = inITBlock();
9146 
9147       // Some instructions need post-processing to, for example, tweak which
9148       // encoding is selected. Loop on it while changes happen so the
9149       // individual transformations can chain off each other. E.g.,
9150       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
9151       while (processInstruction(Inst, Operands, Out))
9152         ;
9153 
9154       // Only after the instruction is fully processed, we can validate it
9155       if (wasInITBlock && hasV8Ops() && isThumb() &&
9156           !isV8EligibleForIT(&Inst)) {
9157         Warning(IDLoc, "deprecated instruction in IT block");
9158       }
9159     }
9160 
9161     // Only move forward at the very end so that everything in validate
9162     // and process gets a consistent answer about whether we're in an IT
9163     // block.
9164     forwardITPosition();
9165 
9166     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
9167     // doesn't actually encode.
9168     if (Inst.getOpcode() == ARM::ITasm)
9169       return false;
9170 
9171     Inst.setLoc(IDLoc);
9172     if (PendConditionalInstruction) {
9173       PendingConditionalInsts.push_back(Inst);
9174       if (isITBlockFull() || isITBlockTerminator(Inst))
9175         flushPendingInstructions(Out);
9176     } else {
9177       Out.EmitInstruction(Inst, getSTI());
9178     }
9179     return false;
9180   case Match_MissingFeature: {
9181     assert(ErrorInfo && "Unknown missing feature!");
9182     // Special case the error message for the very common case where only
9183     // a single subtarget feature is missing (Thumb vs. ARM, e.g.).
9184     std::string Msg = "instruction requires:";
9185     uint64_t Mask = 1;
9186     for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
9187       if (ErrorInfo & Mask) {
9188         Msg += " ";
9189         Msg += getSubtargetFeatureName(ErrorInfo & Mask);
9190       }
9191       Mask <<= 1;
9192     }
9193     return Error(IDLoc, Msg);
9194   }
9195   case Match_InvalidOperand: {
9196     SMLoc ErrorLoc = IDLoc;
9197     if (ErrorInfo != ~0ULL) {
9198       if (ErrorInfo >= Operands.size())
9199         return Error(IDLoc, "too few operands for instruction");
9200 
9201       ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
9202       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
9203     }
9204 
9205     return Error(ErrorLoc, "invalid operand for instruction");
9206   }
9207   case Match_MnemonicFail:
9208     return Error(IDLoc, "invalid instruction",
9209                  ((ARMOperand &)*Operands[0]).getLocRange());
9210   case Match_RequiresNotITBlock:
9211     return Error(IDLoc, "flag setting instruction only valid outside IT block");
9212   case Match_RequiresITBlock:
9213     return Error(IDLoc, "instruction only valid inside IT block");
9214   case Match_RequiresV6:
9215     return Error(IDLoc, "instruction variant requires ARMv6 or later");
9216   case Match_RequiresThumb2:
9217     return Error(IDLoc, "instruction variant requires Thumb2");
9218   case Match_RequiresV8:
9219     return Error(IDLoc, "instruction variant requires ARMv8 or later");
9220   case Match_RequiresFlagSetting:
9221     return Error(IDLoc, "no flag-preserving variant of this instruction available");
9222   case Match_ImmRange0_15: {
9223     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
9224     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
9225     return Error(ErrorLoc, "immediate operand must be in the range [0,15]");
9226   }
9227   case Match_ImmRange0_239: {
9228     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
9229     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
9230     return Error(ErrorLoc, "immediate operand must be in the range [0,239]");
9231   }
9232   case Match_AlignedMemoryRequiresNone:
9233   case Match_DupAlignedMemoryRequiresNone:
9234   case Match_AlignedMemoryRequires16:
9235   case Match_DupAlignedMemoryRequires16:
9236   case Match_AlignedMemoryRequires32:
9237   case Match_DupAlignedMemoryRequires32:
9238   case Match_AlignedMemoryRequires64:
9239   case Match_DupAlignedMemoryRequires64:
9240   case Match_AlignedMemoryRequires64or128:
9241   case Match_DupAlignedMemoryRequires64or128:
9242   case Match_AlignedMemoryRequires64or128or256:
9243   {
9244     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getAlignmentLoc();
9245     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
9246     switch (MatchResult) {
9247       default:
9248         llvm_unreachable("Missing Match_Aligned type");
9249       case Match_AlignedMemoryRequiresNone:
9250       case Match_DupAlignedMemoryRequiresNone:
9251         return Error(ErrorLoc, "alignment must be omitted");
9252       case Match_AlignedMemoryRequires16:
9253       case Match_DupAlignedMemoryRequires16:
9254         return Error(ErrorLoc, "alignment must be 16 or omitted");
9255       case Match_AlignedMemoryRequires32:
9256       case Match_DupAlignedMemoryRequires32:
9257         return Error(ErrorLoc, "alignment must be 32 or omitted");
9258       case Match_AlignedMemoryRequires64:
9259       case Match_DupAlignedMemoryRequires64:
9260         return Error(ErrorLoc, "alignment must be 64 or omitted");
9261       case Match_AlignedMemoryRequires64or128:
9262       case Match_DupAlignedMemoryRequires64or128:
9263         return Error(ErrorLoc, "alignment must be 64, 128 or omitted");
9264       case Match_AlignedMemoryRequires64or128or256:
9265         return Error(ErrorLoc, "alignment must be 64, 128, 256 or omitted");
9266     }
9267   }
9268   }
9269 
9270   llvm_unreachable("Implement any new match types added!");
9271 }
9272 
9273 /// parseDirective parses the arm specific directives
9274 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
9275   const MCObjectFileInfo::Environment Format =
9276     getContext().getObjectFileInfo()->getObjectFileType();
9277   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9278   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
9279 
9280   StringRef IDVal = DirectiveID.getIdentifier();
9281   if (IDVal == ".word")
9282     parseLiteralValues(4, DirectiveID.getLoc());
9283   else if (IDVal == ".short" || IDVal == ".hword")
9284     parseLiteralValues(2, DirectiveID.getLoc());
9285   else if (IDVal == ".thumb")
9286     parseDirectiveThumb(DirectiveID.getLoc());
9287   else if (IDVal == ".arm")
9288     parseDirectiveARM(DirectiveID.getLoc());
9289   else if (IDVal == ".thumb_func")
9290     parseDirectiveThumbFunc(DirectiveID.getLoc());
9291   else if (IDVal == ".code")
9292     parseDirectiveCode(DirectiveID.getLoc());
9293   else if (IDVal == ".syntax")
9294     parseDirectiveSyntax(DirectiveID.getLoc());
9295   else if (IDVal == ".unreq")
9296     parseDirectiveUnreq(DirectiveID.getLoc());
9297   else if (IDVal == ".fnend")
9298     parseDirectiveFnEnd(DirectiveID.getLoc());
9299   else if (IDVal == ".cantunwind")
9300     parseDirectiveCantUnwind(DirectiveID.getLoc());
9301   else if (IDVal == ".personality")
9302     parseDirectivePersonality(DirectiveID.getLoc());
9303   else if (IDVal == ".handlerdata")
9304     parseDirectiveHandlerData(DirectiveID.getLoc());
9305   else if (IDVal == ".setfp")
9306     parseDirectiveSetFP(DirectiveID.getLoc());
9307   else if (IDVal == ".pad")
9308     parseDirectivePad(DirectiveID.getLoc());
9309   else if (IDVal == ".save")
9310     parseDirectiveRegSave(DirectiveID.getLoc(), false);
9311   else if (IDVal == ".vsave")
9312     parseDirectiveRegSave(DirectiveID.getLoc(), true);
9313   else if (IDVal == ".ltorg" || IDVal == ".pool")
9314     parseDirectiveLtorg(DirectiveID.getLoc());
9315   else if (IDVal == ".even")
9316     parseDirectiveEven(DirectiveID.getLoc());
9317   else if (IDVal == ".personalityindex")
9318     parseDirectivePersonalityIndex(DirectiveID.getLoc());
9319   else if (IDVal == ".unwind_raw")
9320     parseDirectiveUnwindRaw(DirectiveID.getLoc());
9321   else if (IDVal == ".movsp")
9322     parseDirectiveMovSP(DirectiveID.getLoc());
9323   else if (IDVal == ".arch_extension")
9324     parseDirectiveArchExtension(DirectiveID.getLoc());
9325   else if (IDVal == ".align")
9326     return parseDirectiveAlign(DirectiveID.getLoc()); // Use Generic on failure.
9327   else if (IDVal == ".thumb_set")
9328     parseDirectiveThumbSet(DirectiveID.getLoc());
9329   else if (!IsMachO && !IsCOFF) {
9330     if (IDVal == ".arch")
9331       parseDirectiveArch(DirectiveID.getLoc());
9332     else if (IDVal == ".cpu")
9333       parseDirectiveCPU(DirectiveID.getLoc());
9334     else if (IDVal == ".eabi_attribute")
9335       parseDirectiveEabiAttr(DirectiveID.getLoc());
9336     else if (IDVal == ".fpu")
9337       parseDirectiveFPU(DirectiveID.getLoc());
9338     else if (IDVal == ".fnstart")
9339       parseDirectiveFnStart(DirectiveID.getLoc());
9340     else if (IDVal == ".inst")
9341       parseDirectiveInst(DirectiveID.getLoc());
9342     else if (IDVal == ".inst.n")
9343       parseDirectiveInst(DirectiveID.getLoc(), 'n');
9344     else if (IDVal == ".inst.w")
9345       parseDirectiveInst(DirectiveID.getLoc(), 'w');
9346     else if (IDVal == ".object_arch")
9347       parseDirectiveObjectArch(DirectiveID.getLoc());
9348     else if (IDVal == ".tlsdescseq")
9349       parseDirectiveTLSDescSeq(DirectiveID.getLoc());
9350     else
9351       return true;
9352   } else
9353     return true;
9354   return false;
9355 }
9356 
9357 /// parseLiteralValues
9358 ///  ::= .hword expression [, expression]*
9359 ///  ::= .short expression [, expression]*
9360 ///  ::= .word expression [, expression]*
9361 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
9362   auto parseOne = [&]() -> bool {
9363     const MCExpr *Value;
9364     if (getParser().parseExpression(Value))
9365       return true;
9366     getParser().getStreamer().EmitValue(Value, Size, L);
9367     return false;
9368   };
9369   return (parseMany(parseOne));
9370 }
9371 
9372 /// parseDirectiveThumb
9373 ///  ::= .thumb
9374 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
9375   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9376       check(!hasThumb(), L, "target does not support Thumb mode"))
9377     return true;
9378 
9379   if (!isThumb())
9380     SwitchMode();
9381 
9382   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9383   return false;
9384 }
9385 
9386 /// parseDirectiveARM
9387 ///  ::= .arm
9388 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
9389   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9390       check(!hasARM(), L, "target does not support ARM mode"))
9391     return true;
9392 
9393   if (isThumb())
9394     SwitchMode();
9395   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9396   return false;
9397 }
9398 
9399 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
9400   // We need to flush the current implicit IT block on a label, because it is
9401   // not legal to branch into an IT block.
9402   flushPendingInstructions(getStreamer());
9403   if (NextSymbolIsThumb) {
9404     getParser().getStreamer().EmitThumbFunc(Symbol);
9405     NextSymbolIsThumb = false;
9406   }
9407 }
9408 
9409 /// parseDirectiveThumbFunc
9410 ///  ::= .thumbfunc symbol_name
9411 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
9412   MCAsmParser &Parser = getParser();
9413   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
9414   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9415 
9416   // Darwin asm has (optionally) function name after .thumb_func direction
9417   // ELF doesn't
9418 
9419   if (IsMachO) {
9420     if (Parser.getTok().is(AsmToken::Identifier) ||
9421         Parser.getTok().is(AsmToken::String)) {
9422       MCSymbol *Func = getParser().getContext().getOrCreateSymbol(
9423           Parser.getTok().getIdentifier());
9424       getParser().getStreamer().EmitThumbFunc(Func);
9425       Parser.Lex();
9426       if (parseToken(AsmToken::EndOfStatement,
9427                      "unexpected token in '.thumb_func' directive"))
9428         return true;
9429       return false;
9430     }
9431   }
9432 
9433   if (parseToken(AsmToken::EndOfStatement,
9434                  "unexpected token in '.thumb_func' directive"))
9435     return true;
9436 
9437   NextSymbolIsThumb = true;
9438   return false;
9439 }
9440 
9441 /// parseDirectiveSyntax
9442 ///  ::= .syntax unified | divided
9443 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
9444   MCAsmParser &Parser = getParser();
9445   const AsmToken &Tok = Parser.getTok();
9446   if (Tok.isNot(AsmToken::Identifier)) {
9447     Error(L, "unexpected token in .syntax directive");
9448     return false;
9449   }
9450 
9451   StringRef Mode = Tok.getString();
9452   Parser.Lex();
9453   if (check(Mode == "divided" || Mode == "DIVIDED", L,
9454             "'.syntax divided' arm assembly not supported") ||
9455       check(Mode != "unified" && Mode != "UNIFIED", L,
9456             "unrecognized syntax mode in .syntax directive") ||
9457       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9458     return true;
9459 
9460   // TODO tell the MC streamer the mode
9461   // getParser().getStreamer().Emit???();
9462   return false;
9463 }
9464 
9465 /// parseDirectiveCode
9466 ///  ::= .code 16 | 32
9467 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
9468   MCAsmParser &Parser = getParser();
9469   const AsmToken &Tok = Parser.getTok();
9470   if (Tok.isNot(AsmToken::Integer))
9471     return Error(L, "unexpected token in .code directive");
9472   int64_t Val = Parser.getTok().getIntVal();
9473   if (Val != 16 && Val != 32) {
9474     Error(L, "invalid operand to .code directive");
9475     return false;
9476   }
9477   Parser.Lex();
9478 
9479   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9480     return true;
9481 
9482   if (Val == 16) {
9483     if (!hasThumb())
9484       return Error(L, "target does not support Thumb mode");
9485 
9486     if (!isThumb())
9487       SwitchMode();
9488     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9489   } else {
9490     if (!hasARM())
9491       return Error(L, "target does not support ARM mode");
9492 
9493     if (isThumb())
9494       SwitchMode();
9495     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9496   }
9497 
9498   return false;
9499 }
9500 
9501 /// parseDirectiveReq
9502 ///  ::= name .req registername
9503 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
9504   MCAsmParser &Parser = getParser();
9505   Parser.Lex(); // Eat the '.req' token.
9506   unsigned Reg;
9507   SMLoc SRegLoc, ERegLoc;
9508   if (check(ParseRegister(Reg, SRegLoc, ERegLoc), SRegLoc,
9509             "register name expected") ||
9510       parseToken(AsmToken::EndOfStatement,
9511                  "unexpected input in .req directive."))
9512     return true;
9513 
9514   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg)
9515     return Error(SRegLoc,
9516                  "redefinition of '" + Name + "' does not match original.");
9517 
9518   return false;
9519 }
9520 
9521 /// parseDirectiveUneq
9522 ///  ::= .unreq registername
9523 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
9524   MCAsmParser &Parser = getParser();
9525   if (Parser.getTok().isNot(AsmToken::Identifier))
9526     return Error(L, "unexpected input in .unreq directive.");
9527   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
9528   Parser.Lex(); // Eat the identifier.
9529   if (parseToken(AsmToken::EndOfStatement,
9530                  "unexpected input in '.unreq' directive"))
9531     return true;
9532   return false;
9533 }
9534 
9535 // After changing arch/CPU, try to put the ARM/Thumb mode back to what it was
9536 // before, if supported by the new target, or emit mapping symbols for the mode
9537 // switch.
9538 void ARMAsmParser::FixModeAfterArchChange(bool WasThumb, SMLoc Loc) {
9539   if (WasThumb != isThumb()) {
9540     if (WasThumb && hasThumb()) {
9541       // Stay in Thumb mode
9542       SwitchMode();
9543     } else if (!WasThumb && hasARM()) {
9544       // Stay in ARM mode
9545       SwitchMode();
9546     } else {
9547       // Mode switch forced, because the new arch doesn't support the old mode.
9548       getParser().getStreamer().EmitAssemblerFlag(isThumb() ? MCAF_Code16
9549                                                             : MCAF_Code32);
9550       // Warn about the implcit mode switch. GAS does not switch modes here,
9551       // but instead stays in the old mode, reporting an error on any following
9552       // instructions as the mode does not exist on the target.
9553       Warning(Loc, Twine("new target does not support ") +
9554                        (WasThumb ? "thumb" : "arm") + " mode, switching to " +
9555                        (!WasThumb ? "thumb" : "arm") + " mode");
9556     }
9557   }
9558 }
9559 
9560 /// parseDirectiveArch
9561 ///  ::= .arch token
9562 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
9563   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
9564   unsigned ID = ARM::parseArch(Arch);
9565 
9566   if (ID == ARM::AK_INVALID)
9567     return Error(L, "Unknown arch name");
9568 
9569   bool WasThumb = isThumb();
9570   Triple T;
9571   MCSubtargetInfo &STI = copySTI();
9572   STI.setDefaultFeatures("", ("+" + ARM::getArchName(ID)).str());
9573   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9574   FixModeAfterArchChange(WasThumb, L);
9575 
9576   getTargetStreamer().emitArch(ID);
9577   return false;
9578 }
9579 
9580 /// parseDirectiveEabiAttr
9581 ///  ::= .eabi_attribute int, int [, "str"]
9582 ///  ::= .eabi_attribute Tag_name, int [, "str"]
9583 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
9584   MCAsmParser &Parser = getParser();
9585   int64_t Tag;
9586   SMLoc TagLoc;
9587   TagLoc = Parser.getTok().getLoc();
9588   if (Parser.getTok().is(AsmToken::Identifier)) {
9589     StringRef Name = Parser.getTok().getIdentifier();
9590     Tag = ARMBuildAttrs::AttrTypeFromString(Name);
9591     if (Tag == -1) {
9592       Error(TagLoc, "attribute name not recognised: " + Name);
9593       return false;
9594     }
9595     Parser.Lex();
9596   } else {
9597     const MCExpr *AttrExpr;
9598 
9599     TagLoc = Parser.getTok().getLoc();
9600     if (Parser.parseExpression(AttrExpr))
9601       return true;
9602 
9603     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
9604     if (check(!CE, TagLoc, "expected numeric constant"))
9605       return true;
9606 
9607     Tag = CE->getValue();
9608   }
9609 
9610   if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9611     return true;
9612 
9613   StringRef StringValue = "";
9614   bool IsStringValue = false;
9615 
9616   int64_t IntegerValue = 0;
9617   bool IsIntegerValue = false;
9618 
9619   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
9620     IsStringValue = true;
9621   else if (Tag == ARMBuildAttrs::compatibility) {
9622     IsStringValue = true;
9623     IsIntegerValue = true;
9624   } else if (Tag < 32 || Tag % 2 == 0)
9625     IsIntegerValue = true;
9626   else if (Tag % 2 == 1)
9627     IsStringValue = true;
9628   else
9629     llvm_unreachable("invalid tag type");
9630 
9631   if (IsIntegerValue) {
9632     const MCExpr *ValueExpr;
9633     SMLoc ValueExprLoc = Parser.getTok().getLoc();
9634     if (Parser.parseExpression(ValueExpr))
9635       return true;
9636 
9637     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
9638     if (!CE)
9639       return Error(ValueExprLoc, "expected numeric constant");
9640     IntegerValue = CE->getValue();
9641   }
9642 
9643   if (Tag == ARMBuildAttrs::compatibility) {
9644     if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9645       return true;
9646   }
9647 
9648   if (IsStringValue) {
9649     if (Parser.getTok().isNot(AsmToken::String))
9650       return Error(Parser.getTok().getLoc(), "bad string constant");
9651 
9652     StringValue = Parser.getTok().getStringContents();
9653     Parser.Lex();
9654   }
9655 
9656   if (Parser.parseToken(AsmToken::EndOfStatement,
9657                         "unexpected token in '.eabi_attribute' directive"))
9658     return true;
9659 
9660   if (IsIntegerValue && IsStringValue) {
9661     assert(Tag == ARMBuildAttrs::compatibility);
9662     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
9663   } else if (IsIntegerValue)
9664     getTargetStreamer().emitAttribute(Tag, IntegerValue);
9665   else if (IsStringValue)
9666     getTargetStreamer().emitTextAttribute(Tag, StringValue);
9667   return false;
9668 }
9669 
9670 /// parseDirectiveCPU
9671 ///  ::= .cpu str
9672 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
9673   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
9674   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
9675 
9676   // FIXME: This is using table-gen data, but should be moved to
9677   // ARMTargetParser once that is table-gen'd.
9678   if (!getSTI().isCPUStringValid(CPU))
9679     return Error(L, "Unknown CPU name");
9680 
9681   bool WasThumb = isThumb();
9682   MCSubtargetInfo &STI = copySTI();
9683   STI.setDefaultFeatures(CPU, "");
9684   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9685   FixModeAfterArchChange(WasThumb, L);
9686 
9687   return false;
9688 }
9689 /// parseDirectiveFPU
9690 ///  ::= .fpu str
9691 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
9692   SMLoc FPUNameLoc = getTok().getLoc();
9693   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
9694 
9695   unsigned ID = ARM::parseFPU(FPU);
9696   std::vector<StringRef> Features;
9697   if (!ARM::getFPUFeatures(ID, Features))
9698     return Error(FPUNameLoc, "Unknown FPU name");
9699 
9700   MCSubtargetInfo &STI = copySTI();
9701   for (auto Feature : Features)
9702     STI.ApplyFeatureFlag(Feature);
9703   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9704 
9705   getTargetStreamer().emitFPU(ID);
9706   return false;
9707 }
9708 
9709 /// parseDirectiveFnStart
9710 ///  ::= .fnstart
9711 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
9712   if (parseToken(AsmToken::EndOfStatement,
9713                  "unexpected token in '.fnstart' directive"))
9714     return true;
9715 
9716   if (UC.hasFnStart()) {
9717     Error(L, ".fnstart starts before the end of previous one");
9718     UC.emitFnStartLocNotes();
9719     return true;
9720   }
9721 
9722   // Reset the unwind directives parser state
9723   UC.reset();
9724 
9725   getTargetStreamer().emitFnStart();
9726 
9727   UC.recordFnStart(L);
9728   return false;
9729 }
9730 
9731 /// parseDirectiveFnEnd
9732 ///  ::= .fnend
9733 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
9734   if (parseToken(AsmToken::EndOfStatement,
9735                  "unexpected token in '.fnend' directive"))
9736     return true;
9737   // Check the ordering of unwind directives
9738   if (!UC.hasFnStart())
9739     return Error(L, ".fnstart must precede .fnend directive");
9740 
9741   // Reset the unwind directives parser state
9742   getTargetStreamer().emitFnEnd();
9743 
9744   UC.reset();
9745   return false;
9746 }
9747 
9748 /// parseDirectiveCantUnwind
9749 ///  ::= .cantunwind
9750 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
9751   if (parseToken(AsmToken::EndOfStatement,
9752                  "unexpected token in '.cantunwind' directive"))
9753     return true;
9754 
9755   UC.recordCantUnwind(L);
9756   // Check the ordering of unwind directives
9757   if (check(!UC.hasFnStart(), L, ".fnstart must precede .cantunwind directive"))
9758     return true;
9759 
9760   if (UC.hasHandlerData()) {
9761     Error(L, ".cantunwind can't be used with .handlerdata directive");
9762     UC.emitHandlerDataLocNotes();
9763     return true;
9764   }
9765   if (UC.hasPersonality()) {
9766     Error(L, ".cantunwind can't be used with .personality directive");
9767     UC.emitPersonalityLocNotes();
9768     return true;
9769   }
9770 
9771   getTargetStreamer().emitCantUnwind();
9772   return false;
9773 }
9774 
9775 /// parseDirectivePersonality
9776 ///  ::= .personality name
9777 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
9778   MCAsmParser &Parser = getParser();
9779   bool HasExistingPersonality = UC.hasPersonality();
9780 
9781   // Parse the name of the personality routine
9782   if (Parser.getTok().isNot(AsmToken::Identifier))
9783     return Error(L, "unexpected input in .personality directive.");
9784   StringRef Name(Parser.getTok().getIdentifier());
9785   Parser.Lex();
9786 
9787   if (parseToken(AsmToken::EndOfStatement,
9788                  "unexpected token in '.personality' directive"))
9789     return true;
9790 
9791   UC.recordPersonality(L);
9792 
9793   // Check the ordering of unwind directives
9794   if (!UC.hasFnStart())
9795     return Error(L, ".fnstart must precede .personality directive");
9796   if (UC.cantUnwind()) {
9797     Error(L, ".personality can't be used with .cantunwind directive");
9798     UC.emitCantUnwindLocNotes();
9799     return true;
9800   }
9801   if (UC.hasHandlerData()) {
9802     Error(L, ".personality must precede .handlerdata directive");
9803     UC.emitHandlerDataLocNotes();
9804     return true;
9805   }
9806   if (HasExistingPersonality) {
9807     Error(L, "multiple personality directives");
9808     UC.emitPersonalityLocNotes();
9809     return true;
9810   }
9811 
9812   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
9813   getTargetStreamer().emitPersonality(PR);
9814   return false;
9815 }
9816 
9817 /// parseDirectiveHandlerData
9818 ///  ::= .handlerdata
9819 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
9820   if (parseToken(AsmToken::EndOfStatement,
9821                  "unexpected token in '.handlerdata' directive"))
9822     return true;
9823 
9824   UC.recordHandlerData(L);
9825   // Check the ordering of unwind directives
9826   if (!UC.hasFnStart())
9827     return Error(L, ".fnstart must precede .personality directive");
9828   if (UC.cantUnwind()) {
9829     Error(L, ".handlerdata can't be used with .cantunwind directive");
9830     UC.emitCantUnwindLocNotes();
9831     return true;
9832   }
9833 
9834   getTargetStreamer().emitHandlerData();
9835   return false;
9836 }
9837 
9838 /// parseDirectiveSetFP
9839 ///  ::= .setfp fpreg, spreg [, offset]
9840 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
9841   MCAsmParser &Parser = getParser();
9842   // Check the ordering of unwind directives
9843   if (check(!UC.hasFnStart(), L, ".fnstart must precede .setfp directive") ||
9844       check(UC.hasHandlerData(), L,
9845             ".setfp must precede .handlerdata directive"))
9846     return true;
9847 
9848   // Parse fpreg
9849   SMLoc FPRegLoc = Parser.getTok().getLoc();
9850   int FPReg = tryParseRegister();
9851 
9852   if (check(FPReg == -1, FPRegLoc, "frame pointer register expected") ||
9853       Parser.parseToken(AsmToken::Comma, "comma expected"))
9854     return true;
9855 
9856   // Parse spreg
9857   SMLoc SPRegLoc = Parser.getTok().getLoc();
9858   int SPReg = tryParseRegister();
9859   if (check(SPReg == -1, SPRegLoc, "stack pointer register expected") ||
9860       check(SPReg != ARM::SP && SPReg != UC.getFPReg(), SPRegLoc,
9861             "register should be either $sp or the latest fp register"))
9862     return true;
9863 
9864   // Update the frame pointer register
9865   UC.saveFPReg(FPReg);
9866 
9867   // Parse offset
9868   int64_t Offset = 0;
9869   if (Parser.parseOptionalToken(AsmToken::Comma)) {
9870     if (Parser.getTok().isNot(AsmToken::Hash) &&
9871         Parser.getTok().isNot(AsmToken::Dollar))
9872       return Error(Parser.getTok().getLoc(), "'#' expected");
9873     Parser.Lex(); // skip hash token.
9874 
9875     const MCExpr *OffsetExpr;
9876     SMLoc ExLoc = Parser.getTok().getLoc();
9877     SMLoc EndLoc;
9878     if (getParser().parseExpression(OffsetExpr, EndLoc))
9879       return Error(ExLoc, "malformed setfp offset");
9880     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9881     if (check(!CE, ExLoc, "setfp offset must be an immediate"))
9882       return true;
9883     Offset = CE->getValue();
9884   }
9885 
9886   if (Parser.parseToken(AsmToken::EndOfStatement))
9887     return true;
9888 
9889   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
9890                                 static_cast<unsigned>(SPReg), Offset);
9891   return false;
9892 }
9893 
9894 /// parseDirective
9895 ///  ::= .pad offset
9896 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
9897   MCAsmParser &Parser = getParser();
9898   // Check the ordering of unwind directives
9899   if (!UC.hasFnStart())
9900     return Error(L, ".fnstart must precede .pad directive");
9901   if (UC.hasHandlerData())
9902     return Error(L, ".pad must precede .handlerdata directive");
9903 
9904   // Parse the offset
9905   if (Parser.getTok().isNot(AsmToken::Hash) &&
9906       Parser.getTok().isNot(AsmToken::Dollar))
9907     return Error(Parser.getTok().getLoc(), "'#' expected");
9908   Parser.Lex(); // skip hash token.
9909 
9910   const MCExpr *OffsetExpr;
9911   SMLoc ExLoc = Parser.getTok().getLoc();
9912   SMLoc EndLoc;
9913   if (getParser().parseExpression(OffsetExpr, EndLoc))
9914     return Error(ExLoc, "malformed pad offset");
9915   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9916   if (!CE)
9917     return Error(ExLoc, "pad offset must be an immediate");
9918 
9919   if (parseToken(AsmToken::EndOfStatement,
9920                  "unexpected token in '.pad' directive"))
9921     return true;
9922 
9923   getTargetStreamer().emitPad(CE->getValue());
9924   return false;
9925 }
9926 
9927 /// parseDirectiveRegSave
9928 ///  ::= .save  { registers }
9929 ///  ::= .vsave { registers }
9930 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
9931   // Check the ordering of unwind directives
9932   if (!UC.hasFnStart())
9933     return Error(L, ".fnstart must precede .save or .vsave directives");
9934   if (UC.hasHandlerData())
9935     return Error(L, ".save or .vsave must precede .handlerdata directive");
9936 
9937   // RAII object to make sure parsed operands are deleted.
9938   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
9939 
9940   // Parse the register list
9941   if (parseRegisterList(Operands) ||
9942       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9943     return true;
9944   ARMOperand &Op = (ARMOperand &)*Operands[0];
9945   if (!IsVector && !Op.isRegList())
9946     return Error(L, ".save expects GPR registers");
9947   if (IsVector && !Op.isDPRRegList())
9948     return Error(L, ".vsave expects DPR registers");
9949 
9950   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
9951   return false;
9952 }
9953 
9954 /// parseDirectiveInst
9955 ///  ::= .inst opcode [, ...]
9956 ///  ::= .inst.n opcode [, ...]
9957 ///  ::= .inst.w opcode [, ...]
9958 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
9959   int Width = 4;
9960 
9961   if (isThumb()) {
9962     switch (Suffix) {
9963     case 'n':
9964       Width = 2;
9965       break;
9966     case 'w':
9967       break;
9968     default:
9969       return Error(Loc, "cannot determine Thumb instruction size, "
9970                         "use inst.n/inst.w instead");
9971     }
9972   } else {
9973     if (Suffix)
9974       return Error(Loc, "width suffixes are invalid in ARM mode");
9975   }
9976 
9977   auto parseOne = [&]() -> bool {
9978     const MCExpr *Expr;
9979     if (getParser().parseExpression(Expr))
9980       return true;
9981     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
9982     if (!Value) {
9983       return Error(Loc, "expected constant expression");
9984     }
9985 
9986     switch (Width) {
9987     case 2:
9988       if (Value->getValue() > 0xffff)
9989         return Error(Loc, "inst.n operand is too big, use inst.w instead");
9990       break;
9991     case 4:
9992       if (Value->getValue() > 0xffffffff)
9993         return Error(Loc, StringRef(Suffix ? "inst.w" : "inst") +
9994                               " operand is too big");
9995       break;
9996     default:
9997       llvm_unreachable("only supported widths are 2 and 4");
9998     }
9999 
10000     getTargetStreamer().emitInst(Value->getValue(), Suffix);
10001     return false;
10002   };
10003 
10004   if (parseOptionalToken(AsmToken::EndOfStatement))
10005     return Error(Loc, "expected expression following directive");
10006   if (parseMany(parseOne))
10007     return true;
10008   return false;
10009 }
10010 
10011 /// parseDirectiveLtorg
10012 ///  ::= .ltorg | .pool
10013 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
10014   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
10015     return true;
10016   getTargetStreamer().emitCurrentConstantPool();
10017   return false;
10018 }
10019 
10020 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
10021   const MCSection *Section = getStreamer().getCurrentSectionOnly();
10022 
10023   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
10024     return true;
10025 
10026   if (!Section) {
10027     getStreamer().InitSections(false);
10028     Section = getStreamer().getCurrentSectionOnly();
10029   }
10030 
10031   assert(Section && "must have section to emit alignment");
10032   if (Section->UseCodeAlign())
10033     getStreamer().EmitCodeAlignment(2);
10034   else
10035     getStreamer().EmitValueToAlignment(2);
10036 
10037   return false;
10038 }
10039 
10040 /// parseDirectivePersonalityIndex
10041 ///   ::= .personalityindex index
10042 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
10043   MCAsmParser &Parser = getParser();
10044   bool HasExistingPersonality = UC.hasPersonality();
10045 
10046   const MCExpr *IndexExpression;
10047   SMLoc IndexLoc = Parser.getTok().getLoc();
10048   if (Parser.parseExpression(IndexExpression) ||
10049       parseToken(AsmToken::EndOfStatement,
10050                  "unexpected token in '.personalityindex' directive")) {
10051     return true;
10052   }
10053 
10054   UC.recordPersonalityIndex(L);
10055 
10056   if (!UC.hasFnStart()) {
10057     return Error(L, ".fnstart must precede .personalityindex directive");
10058   }
10059   if (UC.cantUnwind()) {
10060     Error(L, ".personalityindex cannot be used with .cantunwind");
10061     UC.emitCantUnwindLocNotes();
10062     return true;
10063   }
10064   if (UC.hasHandlerData()) {
10065     Error(L, ".personalityindex must precede .handlerdata directive");
10066     UC.emitHandlerDataLocNotes();
10067     return true;
10068   }
10069   if (HasExistingPersonality) {
10070     Error(L, "multiple personality directives");
10071     UC.emitPersonalityLocNotes();
10072     return true;
10073   }
10074 
10075   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
10076   if (!CE)
10077     return Error(IndexLoc, "index must be a constant number");
10078   if (CE->getValue() < 0 || CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX)
10079     return Error(IndexLoc,
10080                  "personality routine index should be in range [0-3]");
10081 
10082   getTargetStreamer().emitPersonalityIndex(CE->getValue());
10083   return false;
10084 }
10085 
10086 /// parseDirectiveUnwindRaw
10087 ///   ::= .unwind_raw offset, opcode [, opcode...]
10088 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
10089   MCAsmParser &Parser = getParser();
10090   int64_t StackOffset;
10091   const MCExpr *OffsetExpr;
10092   SMLoc OffsetLoc = getLexer().getLoc();
10093 
10094   if (!UC.hasFnStart())
10095     return Error(L, ".fnstart must precede .unwind_raw directives");
10096   if (getParser().parseExpression(OffsetExpr))
10097     return Error(OffsetLoc, "expected expression");
10098 
10099   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10100   if (!CE)
10101     return Error(OffsetLoc, "offset must be a constant");
10102 
10103   StackOffset = CE->getValue();
10104 
10105   if (Parser.parseToken(AsmToken::Comma, "expected comma"))
10106     return true;
10107 
10108   SmallVector<uint8_t, 16> Opcodes;
10109 
10110   auto parseOne = [&]() -> bool {
10111     const MCExpr *OE;
10112     SMLoc OpcodeLoc = getLexer().getLoc();
10113     if (check(getLexer().is(AsmToken::EndOfStatement) ||
10114                   Parser.parseExpression(OE),
10115               OpcodeLoc, "expected opcode expression"))
10116       return true;
10117     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
10118     if (!OC)
10119       return Error(OpcodeLoc, "opcode value must be a constant");
10120     const int64_t Opcode = OC->getValue();
10121     if (Opcode & ~0xff)
10122       return Error(OpcodeLoc, "invalid opcode");
10123     Opcodes.push_back(uint8_t(Opcode));
10124     return false;
10125   };
10126 
10127   // Must have at least 1 element
10128   SMLoc OpcodeLoc = getLexer().getLoc();
10129   if (parseOptionalToken(AsmToken::EndOfStatement))
10130     return Error(OpcodeLoc, "expected opcode expression");
10131   if (parseMany(parseOne))
10132     return true;
10133 
10134   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
10135   return false;
10136 }
10137 
10138 /// parseDirectiveTLSDescSeq
10139 ///   ::= .tlsdescseq tls-variable
10140 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
10141   MCAsmParser &Parser = getParser();
10142 
10143   if (getLexer().isNot(AsmToken::Identifier))
10144     return TokError("expected variable after '.tlsdescseq' directive");
10145 
10146   const MCSymbolRefExpr *SRE =
10147     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
10148                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
10149   Lex();
10150 
10151   if (parseToken(AsmToken::EndOfStatement,
10152                  "unexpected token in '.tlsdescseq' directive"))
10153     return true;
10154 
10155   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
10156   return false;
10157 }
10158 
10159 /// parseDirectiveMovSP
10160 ///  ::= .movsp reg [, #offset]
10161 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
10162   MCAsmParser &Parser = getParser();
10163   if (!UC.hasFnStart())
10164     return Error(L, ".fnstart must precede .movsp directives");
10165   if (UC.getFPReg() != ARM::SP)
10166     return Error(L, "unexpected .movsp directive");
10167 
10168   SMLoc SPRegLoc = Parser.getTok().getLoc();
10169   int SPReg = tryParseRegister();
10170   if (SPReg == -1)
10171     return Error(SPRegLoc, "register expected");
10172   if (SPReg == ARM::SP || SPReg == ARM::PC)
10173     return Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
10174 
10175   int64_t Offset = 0;
10176   if (Parser.parseOptionalToken(AsmToken::Comma)) {
10177     if (Parser.parseToken(AsmToken::Hash, "expected #constant"))
10178       return true;
10179 
10180     const MCExpr *OffsetExpr;
10181     SMLoc OffsetLoc = Parser.getTok().getLoc();
10182 
10183     if (Parser.parseExpression(OffsetExpr))
10184       return Error(OffsetLoc, "malformed offset expression");
10185 
10186     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10187     if (!CE)
10188       return Error(OffsetLoc, "offset must be an immediate constant");
10189 
10190     Offset = CE->getValue();
10191   }
10192 
10193   if (parseToken(AsmToken::EndOfStatement,
10194                  "unexpected token in '.movsp' directive"))
10195     return true;
10196 
10197   getTargetStreamer().emitMovSP(SPReg, Offset);
10198   UC.saveFPReg(SPReg);
10199 
10200   return false;
10201 }
10202 
10203 /// parseDirectiveObjectArch
10204 ///   ::= .object_arch name
10205 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
10206   MCAsmParser &Parser = getParser();
10207   if (getLexer().isNot(AsmToken::Identifier))
10208     return Error(getLexer().getLoc(), "unexpected token");
10209 
10210   StringRef Arch = Parser.getTok().getString();
10211   SMLoc ArchLoc = Parser.getTok().getLoc();
10212   Lex();
10213 
10214   unsigned ID = ARM::parseArch(Arch);
10215 
10216   if (ID == ARM::AK_INVALID)
10217     return Error(ArchLoc, "unknown architecture '" + Arch + "'");
10218   if (parseToken(AsmToken::EndOfStatement))
10219     return true;
10220 
10221   getTargetStreamer().emitObjectArch(ID);
10222   return false;
10223 }
10224 
10225 /// parseDirectiveAlign
10226 ///   ::= .align
10227 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
10228   // NOTE: if this is not the end of the statement, fall back to the target
10229   // agnostic handling for this directive which will correctly handle this.
10230   if (parseOptionalToken(AsmToken::EndOfStatement)) {
10231     // '.align' is target specifically handled to mean 2**2 byte alignment.
10232     const MCSection *Section = getStreamer().getCurrentSectionOnly();
10233     assert(Section && "must have section to emit alignment");
10234     if (Section->UseCodeAlign())
10235       getStreamer().EmitCodeAlignment(4, 0);
10236     else
10237       getStreamer().EmitValueToAlignment(4, 0, 1, 0);
10238     return false;
10239   }
10240   return true;
10241 }
10242 
10243 /// parseDirectiveThumbSet
10244 ///  ::= .thumb_set name, value
10245 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
10246   MCAsmParser &Parser = getParser();
10247 
10248   StringRef Name;
10249   if (check(Parser.parseIdentifier(Name),
10250             "expected identifier after '.thumb_set'") ||
10251       parseToken(AsmToken::Comma, "expected comma after name '" + Name + "'"))
10252     return true;
10253 
10254   MCSymbol *Sym;
10255   const MCExpr *Value;
10256   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
10257                                                Parser, Sym, Value))
10258     return true;
10259 
10260   getTargetStreamer().emitThumbSet(Sym, Value);
10261   return false;
10262 }
10263 
10264 /// Force static initialization.
10265 extern "C" void LLVMInitializeARMAsmParser() {
10266   RegisterMCAsmParser<ARMAsmParser> X(getTheARMLETarget());
10267   RegisterMCAsmParser<ARMAsmParser> Y(getTheARMBETarget());
10268   RegisterMCAsmParser<ARMAsmParser> A(getTheThumbLETarget());
10269   RegisterMCAsmParser<ARMAsmParser> B(getTheThumbBETarget());
10270 }
10271 
10272 #define GET_REGISTER_MATCHER
10273 #define GET_SUBTARGET_FEATURE_NAME
10274 #define GET_MATCHER_IMPLEMENTATION
10275 #include "ARMGenAsmMatcher.inc"
10276 
10277 // FIXME: This structure should be moved inside ARMTargetParser
10278 // when we start to table-generate them, and we can use the ARM
10279 // flags below, that were generated by table-gen.
10280 static const struct {
10281   const unsigned Kind;
10282   const uint64_t ArchCheck;
10283   const FeatureBitset Features;
10284 } Extensions[] = {
10285   { ARM::AEK_CRC, Feature_HasV8, {ARM::FeatureCRC} },
10286   { ARM::AEK_CRYPTO,  Feature_HasV8,
10287     {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10288   { ARM::AEK_FP, Feature_HasV8, {ARM::FeatureFPARMv8} },
10289   { (ARM::AEK_HWDIV | ARM::AEK_HWDIVARM), Feature_HasV7 | Feature_IsNotMClass,
10290     {ARM::FeatureHWDiv, ARM::FeatureHWDivARM} },
10291   { ARM::AEK_MP, Feature_HasV7 | Feature_IsNotMClass, {ARM::FeatureMP} },
10292   { ARM::AEK_SIMD, Feature_HasV8, {ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10293   { ARM::AEK_SEC, Feature_HasV6K, {ARM::FeatureTrustZone} },
10294   // FIXME: Only available in A-class, isel not predicated
10295   { ARM::AEK_VIRT, Feature_HasV7, {ARM::FeatureVirtualization} },
10296   { ARM::AEK_FP16, Feature_HasV8_2a, {ARM::FeatureFPARMv8, ARM::FeatureFullFP16} },
10297   { ARM::AEK_RAS, Feature_HasV8, {ARM::FeatureRAS} },
10298   // FIXME: Unsupported extensions.
10299   { ARM::AEK_OS, Feature_None, {} },
10300   { ARM::AEK_IWMMXT, Feature_None, {} },
10301   { ARM::AEK_IWMMXT2, Feature_None, {} },
10302   { ARM::AEK_MAVERICK, Feature_None, {} },
10303   { ARM::AEK_XSCALE, Feature_None, {} },
10304 };
10305 
10306 /// parseDirectiveArchExtension
10307 ///   ::= .arch_extension [no]feature
10308 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
10309   MCAsmParser &Parser = getParser();
10310 
10311   if (getLexer().isNot(AsmToken::Identifier))
10312     return Error(getLexer().getLoc(), "expected architecture extension name");
10313 
10314   StringRef Name = Parser.getTok().getString();
10315   SMLoc ExtLoc = Parser.getTok().getLoc();
10316   Lex();
10317 
10318   if (parseToken(AsmToken::EndOfStatement,
10319                  "unexpected token in '.arch_extension' directive"))
10320     return true;
10321 
10322   bool EnableFeature = true;
10323   if (Name.startswith_lower("no")) {
10324     EnableFeature = false;
10325     Name = Name.substr(2);
10326   }
10327   unsigned FeatureKind = ARM::parseArchExt(Name);
10328   if (FeatureKind == ARM::AEK_INVALID)
10329     return Error(ExtLoc, "unknown architectural extension: " + Name);
10330 
10331   for (const auto &Extension : Extensions) {
10332     if (Extension.Kind != FeatureKind)
10333       continue;
10334 
10335     if (Extension.Features.none())
10336       return Error(ExtLoc, "unsupported architectural extension: " + Name);
10337 
10338     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck)
10339       return Error(ExtLoc, "architectural extension '" + Name +
10340                                "' is not "
10341                                "allowed for the current base architecture");
10342 
10343     MCSubtargetInfo &STI = copySTI();
10344     FeatureBitset ToggleFeatures = EnableFeature
10345       ? (~STI.getFeatureBits() & Extension.Features)
10346       : ( STI.getFeatureBits() & Extension.Features);
10347 
10348     uint64_t Features =
10349         ComputeAvailableFeatures(STI.ToggleFeature(ToggleFeatures));
10350     setAvailableFeatures(Features);
10351     return false;
10352   }
10353 
10354   return Error(ExtLoc, "unknown architectural extension: " + Name);
10355 }
10356 
10357 // Define this matcher function after the auto-generated include so we
10358 // have the match class enum definitions.
10359 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
10360                                                   unsigned Kind) {
10361   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
10362   // If the kind is a token for a literal immediate, check if our asm
10363   // operand matches. This is for InstAliases which have a fixed-value
10364   // immediate in the syntax.
10365   switch (Kind) {
10366   default: break;
10367   case MCK__35_0:
10368     if (Op.isImm())
10369       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
10370         if (CE->getValue() == 0)
10371           return Match_Success;
10372     break;
10373   case MCK_ModImm:
10374     if (Op.isImm()) {
10375       const MCExpr *SOExpr = Op.getImm();
10376       int64_t Value;
10377       if (!SOExpr->evaluateAsAbsolute(Value))
10378         return Match_Success;
10379       assert((Value >= INT32_MIN && Value <= UINT32_MAX) &&
10380              "expression value must be representable in 32 bits");
10381     }
10382     break;
10383   case MCK_rGPR:
10384     if (hasV8Ops() && Op.isReg() && Op.getReg() == ARM::SP)
10385       return Match_Success;
10386     break;
10387   case MCK_GPRPair:
10388     if (Op.isReg() &&
10389         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
10390       return Match_Success;
10391     break;
10392   }
10393   return Match_InvalidOperand;
10394 }
10395