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 static cl::opt<bool> AddBuildAttributes("arm-add-build-attributes",
71                                         cl::init(false));
72 
73 class ARMOperand;
74 
75 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
76 
77 class UnwindContext {
78   MCAsmParser &Parser;
79 
80   typedef SmallVector<SMLoc, 4> Locs;
81 
82   Locs FnStartLocs;
83   Locs CantUnwindLocs;
84   Locs PersonalityLocs;
85   Locs PersonalityIndexLocs;
86   Locs HandlerDataLocs;
87   int FPReg;
88 
89 public:
90   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
91 
92   bool hasFnStart() const { return !FnStartLocs.empty(); }
93   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
94   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
95   bool hasPersonality() const {
96     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
97   }
98 
99   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
100   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
101   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
102   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
103   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
104 
105   void saveFPReg(int Reg) { FPReg = Reg; }
106   int getFPReg() const { return FPReg; }
107 
108   void emitFnStartLocNotes() const {
109     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
110          FI != FE; ++FI)
111       Parser.Note(*FI, ".fnstart was specified here");
112   }
113   void emitCantUnwindLocNotes() const {
114     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
115                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
116       Parser.Note(*UI, ".cantunwind was specified here");
117   }
118   void emitHandlerDataLocNotes() const {
119     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
120                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
121       Parser.Note(*HI, ".handlerdata was specified here");
122   }
123   void emitPersonalityLocNotes() const {
124     for (Locs::const_iterator PI = PersonalityLocs.begin(),
125                               PE = PersonalityLocs.end(),
126                               PII = PersonalityIndexLocs.begin(),
127                               PIE = PersonalityIndexLocs.end();
128          PI != PE || PII != PIE;) {
129       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
130         Parser.Note(*PI++, ".personality was specified here");
131       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
132         Parser.Note(*PII++, ".personalityindex was specified here");
133       else
134         llvm_unreachable(".personality and .personalityindex cannot be "
135                          "at the same location");
136     }
137   }
138 
139   void reset() {
140     FnStartLocs = Locs();
141     CantUnwindLocs = Locs();
142     PersonalityLocs = Locs();
143     HandlerDataLocs = Locs();
144     PersonalityIndexLocs = Locs();
145     FPReg = ARM::SP;
146   }
147 };
148 
149 class ARMAsmParser : public MCTargetAsmParser {
150   const MCInstrInfo &MII;
151   const MCRegisterInfo *MRI;
152   UnwindContext UC;
153 
154   ARMTargetStreamer &getTargetStreamer() {
155     assert(getParser().getStreamer().getTargetStreamer() &&
156            "do not have a target streamer");
157     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
158     return static_cast<ARMTargetStreamer &>(TS);
159   }
160 
161   // Map of register aliases registers via the .req directive.
162   StringMap<unsigned> RegisterReqs;
163 
164   bool NextSymbolIsThumb;
165 
166   bool useImplicitITThumb() const {
167     return ImplicitItMode == ImplicitItModeTy::Always ||
168            ImplicitItMode == ImplicitItModeTy::ThumbOnly;
169   }
170 
171   bool useImplicitITARM() const {
172     return ImplicitItMode == ImplicitItModeTy::Always ||
173            ImplicitItMode == ImplicitItModeTy::ARMOnly;
174   }
175 
176   struct {
177     ARMCC::CondCodes Cond;    // Condition for IT block.
178     unsigned Mask:4;          // Condition mask for instructions.
179                               // Starting at first 1 (from lsb).
180                               //   '1'  condition as indicated in IT.
181                               //   '0'  inverse of condition (else).
182                               // Count of instructions in IT block is
183                               // 4 - trailingzeroes(mask)
184                               // Note that this does not have the same encoding
185                               // as in the IT instruction, which also depends
186                               // on the low bit of the condition code.
187 
188     unsigned CurPosition;     // Current position in parsing of IT
189                               // block. In range [0,4], with 0 being the IT
190                               // instruction itself. Initialized according to
191                               // count of instructions in block.  ~0U if no
192                               // active IT block.
193 
194     bool IsExplicit;          // true  - The IT instruction was present in the
195                               //         input, we should not modify it.
196                               // false - The IT instruction was added
197                               //         implicitly, we can extend it if that
198                               //         would be legal.
199   } ITState;
200 
201   llvm::SmallVector<MCInst, 4> PendingConditionalInsts;
202 
203   void flushPendingInstructions(MCStreamer &Out) override {
204     if (!inImplicitITBlock()) {
205       assert(PendingConditionalInsts.size() == 0);
206       return;
207     }
208 
209     // Emit the IT instruction
210     unsigned Mask = getITMaskEncoding();
211     MCInst ITInst;
212     ITInst.setOpcode(ARM::t2IT);
213     ITInst.addOperand(MCOperand::createImm(ITState.Cond));
214     ITInst.addOperand(MCOperand::createImm(Mask));
215     Out.EmitInstruction(ITInst, getSTI());
216 
217     // Emit the conditonal instructions
218     assert(PendingConditionalInsts.size() <= 4);
219     for (const MCInst &Inst : PendingConditionalInsts) {
220       Out.EmitInstruction(Inst, getSTI());
221     }
222     PendingConditionalInsts.clear();
223 
224     // Clear the IT state
225     ITState.Mask = 0;
226     ITState.CurPosition = ~0U;
227   }
228 
229   bool inITBlock() { return ITState.CurPosition != ~0U; }
230   bool inExplicitITBlock() { return inITBlock() && ITState.IsExplicit; }
231   bool inImplicitITBlock() { return inITBlock() && !ITState.IsExplicit; }
232   bool lastInITBlock() {
233     return ITState.CurPosition == 4 - countTrailingZeros(ITState.Mask);
234   }
235   void forwardITPosition() {
236     if (!inITBlock()) return;
237     // Move to the next instruction in the IT block, if there is one. If not,
238     // mark the block as done, except for implicit IT blocks, which we leave
239     // open until we find an instruction that can't be added to it.
240     unsigned TZ = countTrailingZeros(ITState.Mask);
241     if (++ITState.CurPosition == 5 - TZ && ITState.IsExplicit)
242       ITState.CurPosition = ~0U; // Done with the IT block after this.
243   }
244 
245   // Rewind the state of the current IT block, removing the last slot from it.
246   void rewindImplicitITPosition() {
247     assert(inImplicitITBlock());
248     assert(ITState.CurPosition > 1);
249     ITState.CurPosition--;
250     unsigned TZ = countTrailingZeros(ITState.Mask);
251     unsigned NewMask = 0;
252     NewMask |= ITState.Mask & (0xC << TZ);
253     NewMask |= 0x2 << TZ;
254     ITState.Mask = NewMask;
255   }
256 
257   // Rewind the state of the current IT block, removing the last slot from it.
258   // If we were at the first slot, this closes the IT block.
259   void discardImplicitITBlock() {
260     assert(inImplicitITBlock());
261     assert(ITState.CurPosition == 1);
262     ITState.CurPosition = ~0U;
263     return;
264   }
265 
266   // Get the encoding of the IT mask, as it will appear in an IT instruction.
267   unsigned getITMaskEncoding() {
268     assert(inITBlock());
269     unsigned Mask = ITState.Mask;
270     unsigned TZ = countTrailingZeros(Mask);
271     if ((ITState.Cond & 1) == 0) {
272       assert(Mask && TZ <= 3 && "illegal IT mask value!");
273       Mask ^= (0xE << TZ) & 0xF;
274     }
275     return Mask;
276   }
277 
278   // Get the condition code corresponding to the current IT block slot.
279   ARMCC::CondCodes currentITCond() {
280     unsigned MaskBit;
281     if (ITState.CurPosition == 1)
282       MaskBit = 1;
283     else
284       MaskBit = (ITState.Mask >> (5 - ITState.CurPosition)) & 1;
285 
286     return MaskBit ? ITState.Cond : ARMCC::getOppositeCondition(ITState.Cond);
287   }
288 
289   // Invert the condition of the current IT block slot without changing any
290   // other slots in the same block.
291   void invertCurrentITCondition() {
292     if (ITState.CurPosition == 1) {
293       ITState.Cond = ARMCC::getOppositeCondition(ITState.Cond);
294     } else {
295       ITState.Mask ^= 1 << (5 - ITState.CurPosition);
296     }
297   }
298 
299   // Returns true if the current IT block is full (all 4 slots used).
300   bool isITBlockFull() {
301     return inITBlock() && (ITState.Mask & 1);
302   }
303 
304   // Extend the current implicit IT block to have one more slot with the given
305   // condition code.
306   void extendImplicitITBlock(ARMCC::CondCodes Cond) {
307     assert(inImplicitITBlock());
308     assert(!isITBlockFull());
309     assert(Cond == ITState.Cond ||
310            Cond == ARMCC::getOppositeCondition(ITState.Cond));
311     unsigned TZ = countTrailingZeros(ITState.Mask);
312     unsigned NewMask = 0;
313     // Keep any existing condition bits.
314     NewMask |= ITState.Mask & (0xE << TZ);
315     // Insert the new condition bit.
316     NewMask |= (Cond == ITState.Cond) << TZ;
317     // Move the trailing 1 down one bit.
318     NewMask |= 1 << (TZ - 1);
319     ITState.Mask = NewMask;
320   }
321 
322   // Create a new implicit IT block with a dummy condition code.
323   void startImplicitITBlock() {
324     assert(!inITBlock());
325     ITState.Cond = ARMCC::AL;
326     ITState.Mask = 8;
327     ITState.CurPosition = 1;
328     ITState.IsExplicit = false;
329     return;
330   }
331 
332   // Create a new explicit IT block with the given condition and mask. The mask
333   // should be in the parsed format, with a 1 implying 't', regardless of the
334   // low bit of the condition.
335   void startExplicitITBlock(ARMCC::CondCodes Cond, unsigned Mask) {
336     assert(!inITBlock());
337     ITState.Cond = Cond;
338     ITState.Mask = Mask;
339     ITState.CurPosition = 0;
340     ITState.IsExplicit = true;
341     return;
342   }
343 
344   void Note(SMLoc L, const Twine &Msg, SMRange Range = None) {
345     return getParser().Note(L, Msg, Range);
346   }
347   bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) {
348     return getParser().Warning(L, Msg, Range);
349   }
350   bool Error(SMLoc L, const Twine &Msg, SMRange Range = None) {
351     return getParser().Error(L, Msg, Range);
352   }
353 
354   bool validatetLDMRegList(const MCInst &Inst, const OperandVector &Operands,
355                            unsigned ListNo, bool IsARPop = false);
356   bool validatetSTMRegList(const MCInst &Inst, const OperandVector &Operands,
357                            unsigned ListNo);
358 
359   int tryParseRegister();
360   bool tryParseRegisterWithWriteBack(OperandVector &);
361   int tryParseShiftRegister(OperandVector &);
362   bool parseRegisterList(OperandVector &);
363   bool parseMemory(OperandVector &);
364   bool parseOperand(OperandVector &, StringRef Mnemonic);
365   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
366   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
367                               unsigned &ShiftAmount);
368   bool parseLiteralValues(unsigned Size, SMLoc L);
369   bool parseDirectiveThumb(SMLoc L);
370   bool parseDirectiveARM(SMLoc L);
371   bool parseDirectiveThumbFunc(SMLoc L);
372   bool parseDirectiveCode(SMLoc L);
373   bool parseDirectiveSyntax(SMLoc L);
374   bool parseDirectiveReq(StringRef Name, SMLoc L);
375   bool parseDirectiveUnreq(SMLoc L);
376   bool parseDirectiveArch(SMLoc L);
377   bool parseDirectiveEabiAttr(SMLoc L);
378   bool parseDirectiveCPU(SMLoc L);
379   bool parseDirectiveFPU(SMLoc L);
380   bool parseDirectiveFnStart(SMLoc L);
381   bool parseDirectiveFnEnd(SMLoc L);
382   bool parseDirectiveCantUnwind(SMLoc L);
383   bool parseDirectivePersonality(SMLoc L);
384   bool parseDirectiveHandlerData(SMLoc L);
385   bool parseDirectiveSetFP(SMLoc L);
386   bool parseDirectivePad(SMLoc L);
387   bool parseDirectiveRegSave(SMLoc L, bool IsVector);
388   bool parseDirectiveInst(SMLoc L, char Suffix = '\0');
389   bool parseDirectiveLtorg(SMLoc L);
390   bool parseDirectiveEven(SMLoc L);
391   bool parseDirectivePersonalityIndex(SMLoc L);
392   bool parseDirectiveUnwindRaw(SMLoc L);
393   bool parseDirectiveTLSDescSeq(SMLoc L);
394   bool parseDirectiveMovSP(SMLoc L);
395   bool parseDirectiveObjectArch(SMLoc L);
396   bool parseDirectiveArchExtension(SMLoc L);
397   bool parseDirectiveAlign(SMLoc L);
398   bool parseDirectiveThumbSet(SMLoc L);
399 
400   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
401                           bool &CarrySetting, unsigned &ProcessorIMod,
402                           StringRef &ITMask);
403   void getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
404                              bool &CanAcceptCarrySet,
405                              bool &CanAcceptPredicationCode);
406 
407   void tryConvertingToTwoOperandForm(StringRef Mnemonic, bool CarrySetting,
408                                      OperandVector &Operands);
409   bool isThumb() const {
410     // FIXME: Can tablegen auto-generate this?
411     return getSTI().getFeatureBits()[ARM::ModeThumb];
412   }
413   bool isThumbOne() const {
414     return isThumb() && !getSTI().getFeatureBits()[ARM::FeatureThumb2];
415   }
416   bool isThumbTwo() const {
417     return isThumb() && getSTI().getFeatureBits()[ARM::FeatureThumb2];
418   }
419   bool hasThumb() const {
420     return getSTI().getFeatureBits()[ARM::HasV4TOps];
421   }
422   bool hasThumb2() const {
423     return getSTI().getFeatureBits()[ARM::FeatureThumb2];
424   }
425   bool hasV6Ops() const {
426     return getSTI().getFeatureBits()[ARM::HasV6Ops];
427   }
428   bool hasV6T2Ops() const {
429     return getSTI().getFeatureBits()[ARM::HasV6T2Ops];
430   }
431   bool hasV6MOps() const {
432     return getSTI().getFeatureBits()[ARM::HasV6MOps];
433   }
434   bool hasV7Ops() const {
435     return getSTI().getFeatureBits()[ARM::HasV7Ops];
436   }
437   bool hasV8Ops() const {
438     return getSTI().getFeatureBits()[ARM::HasV8Ops];
439   }
440   bool hasV8MBaseline() const {
441     return getSTI().getFeatureBits()[ARM::HasV8MBaselineOps];
442   }
443   bool hasV8MMainline() const {
444     return getSTI().getFeatureBits()[ARM::HasV8MMainlineOps];
445   }
446   bool has8MSecExt() const {
447     return getSTI().getFeatureBits()[ARM::Feature8MSecExt];
448   }
449   bool hasARM() const {
450     return !getSTI().getFeatureBits()[ARM::FeatureNoARM];
451   }
452   bool hasDSP() const {
453     return getSTI().getFeatureBits()[ARM::FeatureDSP];
454   }
455   bool hasD16() const {
456     return getSTI().getFeatureBits()[ARM::FeatureD16];
457   }
458   bool hasV8_1aOps() const {
459     return getSTI().getFeatureBits()[ARM::HasV8_1aOps];
460   }
461   bool hasRAS() const {
462     return getSTI().getFeatureBits()[ARM::FeatureRAS];
463   }
464 
465   void SwitchMode() {
466     MCSubtargetInfo &STI = copySTI();
467     uint64_t FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
468     setAvailableFeatures(FB);
469   }
470   void FixModeAfterArchChange(bool WasThumb, SMLoc Loc);
471   bool isMClass() const {
472     return getSTI().getFeatureBits()[ARM::FeatureMClass];
473   }
474 
475   /// @name Auto-generated Match Functions
476   /// {
477 
478 #define GET_ASSEMBLER_HEADER
479 #include "ARMGenAsmMatcher.inc"
480 
481   /// }
482 
483   OperandMatchResultTy parseITCondCode(OperandVector &);
484   OperandMatchResultTy parseCoprocNumOperand(OperandVector &);
485   OperandMatchResultTy parseCoprocRegOperand(OperandVector &);
486   OperandMatchResultTy parseCoprocOptionOperand(OperandVector &);
487   OperandMatchResultTy parseMemBarrierOptOperand(OperandVector &);
488   OperandMatchResultTy parseInstSyncBarrierOptOperand(OperandVector &);
489   OperandMatchResultTy parseProcIFlagsOperand(OperandVector &);
490   OperandMatchResultTy parseMSRMaskOperand(OperandVector &);
491   OperandMatchResultTy parseBankedRegOperand(OperandVector &);
492   OperandMatchResultTy parsePKHImm(OperandVector &O, StringRef Op, int Low,
493                                    int High);
494   OperandMatchResultTy parsePKHLSLImm(OperandVector &O) {
495     return parsePKHImm(O, "lsl", 0, 31);
496   }
497   OperandMatchResultTy parsePKHASRImm(OperandVector &O) {
498     return parsePKHImm(O, "asr", 1, 32);
499   }
500   OperandMatchResultTy parseSetEndImm(OperandVector &);
501   OperandMatchResultTy parseShifterImm(OperandVector &);
502   OperandMatchResultTy parseRotImm(OperandVector &);
503   OperandMatchResultTy parseModImm(OperandVector &);
504   OperandMatchResultTy parseBitfield(OperandVector &);
505   OperandMatchResultTy parsePostIdxReg(OperandVector &);
506   OperandMatchResultTy parseAM3Offset(OperandVector &);
507   OperandMatchResultTy parseFPImm(OperandVector &);
508   OperandMatchResultTy parseVectorList(OperandVector &);
509   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index,
510                                        SMLoc &EndLoc);
511 
512   // Asm Match Converter Methods
513   void cvtThumbMultiply(MCInst &Inst, const OperandVector &);
514   void cvtThumbBranches(MCInst &Inst, const OperandVector &);
515 
516   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
517   bool processInstruction(MCInst &Inst, const OperandVector &Ops, MCStreamer &Out);
518   bool shouldOmitCCOutOperand(StringRef Mnemonic, OperandVector &Operands);
519   bool shouldOmitPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
520   bool isITBlockTerminator(MCInst &Inst) const;
521 
522 public:
523   enum ARMMatchResultTy {
524     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
525     Match_RequiresNotITBlock,
526     Match_RequiresV6,
527     Match_RequiresThumb2,
528     Match_RequiresV8,
529     Match_RequiresFlagSetting,
530 #define GET_OPERAND_DIAGNOSTIC_TYPES
531 #include "ARMGenAsmMatcher.inc"
532 
533   };
534 
535   ARMAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
536                const MCInstrInfo &MII, const MCTargetOptions &Options)
537     : MCTargetAsmParser(Options, STI), MII(MII), UC(Parser) {
538     MCAsmParserExtension::Initialize(Parser);
539 
540     // Cache the MCRegisterInfo.
541     MRI = getContext().getRegisterInfo();
542 
543     // Initialize the set of available features.
544     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
545 
546     // Add build attributes based on the selected target.
547     if (AddBuildAttributes)
548       getTargetStreamer().emitTargetAttributes(STI);
549 
550     // Not in an ITBlock to start with.
551     ITState.CurPosition = ~0U;
552 
553     NextSymbolIsThumb = false;
554   }
555 
556   // Implementation of the MCTargetAsmParser interface:
557   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
558   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
559                         SMLoc NameLoc, OperandVector &Operands) override;
560   bool ParseDirective(AsmToken DirectiveID) override;
561 
562   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
563                                       unsigned Kind) override;
564   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
565 
566   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
567                                OperandVector &Operands, MCStreamer &Out,
568                                uint64_t &ErrorInfo,
569                                bool MatchingInlineAsm) override;
570   unsigned MatchInstruction(OperandVector &Operands, MCInst &Inst,
571                             uint64_t &ErrorInfo, bool MatchingInlineAsm,
572                             bool &EmitInITBlock, MCStreamer &Out);
573   void onLabelParsed(MCSymbol *Symbol) override;
574 };
575 } // end anonymous namespace
576 
577 namespace {
578 
579 /// ARMOperand - Instances of this class represent a parsed ARM machine
580 /// operand.
581 class ARMOperand : public MCParsedAsmOperand {
582   enum KindTy {
583     k_CondCode,
584     k_CCOut,
585     k_ITCondMask,
586     k_CoprocNum,
587     k_CoprocReg,
588     k_CoprocOption,
589     k_Immediate,
590     k_MemBarrierOpt,
591     k_InstSyncBarrierOpt,
592     k_Memory,
593     k_PostIndexRegister,
594     k_MSRMask,
595     k_BankedReg,
596     k_ProcIFlags,
597     k_VectorIndex,
598     k_Register,
599     k_RegisterList,
600     k_DPRRegisterList,
601     k_SPRRegisterList,
602     k_VectorList,
603     k_VectorListAllLanes,
604     k_VectorListIndexed,
605     k_ShiftedRegister,
606     k_ShiftedImmediate,
607     k_ShifterImmediate,
608     k_RotateImmediate,
609     k_ModifiedImmediate,
610     k_ConstantPoolImmediate,
611     k_BitfieldDescriptor,
612     k_Token,
613   } Kind;
614 
615   SMLoc StartLoc, EndLoc, AlignmentLoc;
616   SmallVector<unsigned, 8> Registers;
617 
618   struct CCOp {
619     ARMCC::CondCodes Val;
620   };
621 
622   struct CopOp {
623     unsigned Val;
624   };
625 
626   struct CoprocOptionOp {
627     unsigned Val;
628   };
629 
630   struct ITMaskOp {
631     unsigned Mask:4;
632   };
633 
634   struct MBOptOp {
635     ARM_MB::MemBOpt Val;
636   };
637 
638   struct ISBOptOp {
639     ARM_ISB::InstSyncBOpt Val;
640   };
641 
642   struct IFlagsOp {
643     ARM_PROC::IFlags Val;
644   };
645 
646   struct MMaskOp {
647     unsigned Val;
648   };
649 
650   struct BankedRegOp {
651     unsigned Val;
652   };
653 
654   struct TokOp {
655     const char *Data;
656     unsigned Length;
657   };
658 
659   struct RegOp {
660     unsigned RegNum;
661   };
662 
663   // A vector register list is a sequential list of 1 to 4 registers.
664   struct VectorListOp {
665     unsigned RegNum;
666     unsigned Count;
667     unsigned LaneIndex;
668     bool isDoubleSpaced;
669   };
670 
671   struct VectorIndexOp {
672     unsigned Val;
673   };
674 
675   struct ImmOp {
676     const MCExpr *Val;
677   };
678 
679   /// Combined record for all forms of ARM address expressions.
680   struct MemoryOp {
681     unsigned BaseRegNum;
682     // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
683     // was specified.
684     const MCConstantExpr *OffsetImm;  // Offset immediate value
685     unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
686     ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
687     unsigned ShiftImm;        // shift for OffsetReg.
688     unsigned Alignment;       // 0 = no alignment specified
689     // n = alignment in bytes (2, 4, 8, 16, or 32)
690     unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
691   };
692 
693   struct PostIdxRegOp {
694     unsigned RegNum;
695     bool isAdd;
696     ARM_AM::ShiftOpc ShiftTy;
697     unsigned ShiftImm;
698   };
699 
700   struct ShifterImmOp {
701     bool isASR;
702     unsigned Imm;
703   };
704 
705   struct RegShiftedRegOp {
706     ARM_AM::ShiftOpc ShiftTy;
707     unsigned SrcReg;
708     unsigned ShiftReg;
709     unsigned ShiftImm;
710   };
711 
712   struct RegShiftedImmOp {
713     ARM_AM::ShiftOpc ShiftTy;
714     unsigned SrcReg;
715     unsigned ShiftImm;
716   };
717 
718   struct RotImmOp {
719     unsigned Imm;
720   };
721 
722   struct ModImmOp {
723     unsigned Bits;
724     unsigned Rot;
725   };
726 
727   struct BitfieldOp {
728     unsigned LSB;
729     unsigned Width;
730   };
731 
732   union {
733     struct CCOp CC;
734     struct CopOp Cop;
735     struct CoprocOptionOp CoprocOption;
736     struct MBOptOp MBOpt;
737     struct ISBOptOp ISBOpt;
738     struct ITMaskOp ITMask;
739     struct IFlagsOp IFlags;
740     struct MMaskOp MMask;
741     struct BankedRegOp BankedReg;
742     struct TokOp Tok;
743     struct RegOp Reg;
744     struct VectorListOp VectorList;
745     struct VectorIndexOp VectorIndex;
746     struct ImmOp Imm;
747     struct MemoryOp Memory;
748     struct PostIdxRegOp PostIdxReg;
749     struct ShifterImmOp ShifterImm;
750     struct RegShiftedRegOp RegShiftedReg;
751     struct RegShiftedImmOp RegShiftedImm;
752     struct RotImmOp RotImm;
753     struct ModImmOp ModImm;
754     struct BitfieldOp Bitfield;
755   };
756 
757 public:
758   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
759 
760   /// getStartLoc - Get the location of the first token of this operand.
761   SMLoc getStartLoc() const override { return StartLoc; }
762   /// getEndLoc - Get the location of the last token of this operand.
763   SMLoc getEndLoc() const override { return EndLoc; }
764   /// getLocRange - Get the range between the first and last token of this
765   /// operand.
766   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
767 
768   /// getAlignmentLoc - Get the location of the Alignment token of this operand.
769   SMLoc getAlignmentLoc() const {
770     assert(Kind == k_Memory && "Invalid access!");
771     return AlignmentLoc;
772   }
773 
774   ARMCC::CondCodes getCondCode() const {
775     assert(Kind == k_CondCode && "Invalid access!");
776     return CC.Val;
777   }
778 
779   unsigned getCoproc() const {
780     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
781     return Cop.Val;
782   }
783 
784   StringRef getToken() const {
785     assert(Kind == k_Token && "Invalid access!");
786     return StringRef(Tok.Data, Tok.Length);
787   }
788 
789   unsigned getReg() const override {
790     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
791     return Reg.RegNum;
792   }
793 
794   const SmallVectorImpl<unsigned> &getRegList() const {
795     assert((Kind == k_RegisterList || Kind == k_DPRRegisterList ||
796             Kind == k_SPRRegisterList) && "Invalid access!");
797     return Registers;
798   }
799 
800   const MCExpr *getImm() const {
801     assert(isImm() && "Invalid access!");
802     return Imm.Val;
803   }
804 
805   const MCExpr *getConstantPoolImm() const {
806     assert(isConstantPoolImm() && "Invalid access!");
807     return Imm.Val;
808   }
809 
810   unsigned getVectorIndex() const {
811     assert(Kind == k_VectorIndex && "Invalid access!");
812     return VectorIndex.Val;
813   }
814 
815   ARM_MB::MemBOpt getMemBarrierOpt() const {
816     assert(Kind == k_MemBarrierOpt && "Invalid access!");
817     return MBOpt.Val;
818   }
819 
820   ARM_ISB::InstSyncBOpt getInstSyncBarrierOpt() const {
821     assert(Kind == k_InstSyncBarrierOpt && "Invalid access!");
822     return ISBOpt.Val;
823   }
824 
825   ARM_PROC::IFlags getProcIFlags() const {
826     assert(Kind == k_ProcIFlags && "Invalid access!");
827     return IFlags.Val;
828   }
829 
830   unsigned getMSRMask() const {
831     assert(Kind == k_MSRMask && "Invalid access!");
832     return MMask.Val;
833   }
834 
835   unsigned getBankedReg() const {
836     assert(Kind == k_BankedReg && "Invalid access!");
837     return BankedReg.Val;
838   }
839 
840   bool isCoprocNum() const { return Kind == k_CoprocNum; }
841   bool isCoprocReg() const { return Kind == k_CoprocReg; }
842   bool isCoprocOption() const { return Kind == k_CoprocOption; }
843   bool isCondCode() const { return Kind == k_CondCode; }
844   bool isCCOut() const { return Kind == k_CCOut; }
845   bool isITMask() const { return Kind == k_ITCondMask; }
846   bool isITCondCode() const { return Kind == k_CondCode; }
847   bool isImm() const override {
848     return Kind == k_Immediate;
849   }
850 
851   bool isARMBranchTarget() const {
852     if (!isImm()) return false;
853 
854     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
855       return CE->getValue() % 4 == 0;
856     return true;
857   }
858 
859 
860   bool isThumbBranchTarget() const {
861     if (!isImm()) return false;
862 
863     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
864       return CE->getValue() % 2 == 0;
865     return true;
866   }
867 
868   // checks whether this operand is an unsigned offset which fits is a field
869   // of specified width and scaled by a specific number of bits
870   template<unsigned width, unsigned scale>
871   bool isUnsignedOffset() const {
872     if (!isImm()) return false;
873     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
874     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
875       int64_t Val = CE->getValue();
876       int64_t Align = 1LL << scale;
877       int64_t Max = Align * ((1LL << width) - 1);
878       return ((Val % Align) == 0) && (Val >= 0) && (Val <= Max);
879     }
880     return false;
881   }
882   // checks whether this operand is an signed offset which fits is a field
883   // of specified width and scaled by a specific number of bits
884   template<unsigned width, unsigned scale>
885   bool isSignedOffset() const {
886     if (!isImm()) return false;
887     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
888     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
889       int64_t Val = CE->getValue();
890       int64_t Align = 1LL << scale;
891       int64_t Max = Align * ((1LL << (width-1)) - 1);
892       int64_t Min = -Align * (1LL << (width-1));
893       return ((Val % Align) == 0) && (Val >= Min) && (Val <= Max);
894     }
895     return false;
896   }
897 
898   // checks whether this operand is a memory operand computed as an offset
899   // applied to PC. the offset may have 8 bits of magnitude and is represented
900   // with two bits of shift. textually it may be either [pc, #imm], #imm or
901   // relocable expression...
902   bool isThumbMemPC() const {
903     int64_t Val = 0;
904     if (isImm()) {
905       if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
906       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
907       if (!CE) return false;
908       Val = CE->getValue();
909     }
910     else if (isMem()) {
911       if(!Memory.OffsetImm || Memory.OffsetRegNum) return false;
912       if(Memory.BaseRegNum != ARM::PC) return false;
913       Val = Memory.OffsetImm->getValue();
914     }
915     else return false;
916     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
917   }
918   bool isFPImm() const {
919     if (!isImm()) return false;
920     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
921     if (!CE) return false;
922     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
923     return Val != -1;
924   }
925 
926   template<int64_t N, int64_t M>
927   bool isImmediate() const {
928     if (!isImm()) return false;
929     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
930     if (!CE) return false;
931     int64_t Value = CE->getValue();
932     return Value >= N && Value <= M;
933   }
934   template<int64_t N, int64_t M>
935   bool isImmediateS4() const {
936     if (!isImm()) return false;
937     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
938     if (!CE) return false;
939     int64_t Value = CE->getValue();
940     return ((Value & 3) == 0) && Value >= N && Value <= M;
941   }
942   bool isFBits16() const {
943     return isImmediate<0, 17>();
944   }
945   bool isFBits32() const {
946     return isImmediate<1, 33>();
947   }
948   bool isImm8s4() const {
949     return isImmediateS4<-1020, 1020>();
950   }
951   bool isImm0_1020s4() const {
952     return isImmediateS4<0, 1020>();
953   }
954   bool isImm0_508s4() const {
955     return isImmediateS4<0, 508>();
956   }
957   bool isImm0_508s4Neg() const {
958     if (!isImm()) return false;
959     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
960     if (!CE) return false;
961     int64_t Value = -CE->getValue();
962     // explicitly exclude zero. we want that to use the normal 0_508 version.
963     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
964   }
965   bool isImm0_4095Neg() const {
966     if (!isImm()) return false;
967     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
968     if (!CE) return false;
969     int64_t Value = -CE->getValue();
970     return Value > 0 && Value < 4096;
971   }
972   bool isImm0_7() const {
973     return isImmediate<0, 7>();
974   }
975   bool isImm1_16() const {
976     return isImmediate<1, 16>();
977   }
978   bool isImm1_32() const {
979     return isImmediate<1, 32>();
980   }
981   bool isImm8_255() const {
982     return isImmediate<8, 255>();
983   }
984   bool isImm256_65535Expr() const {
985     if (!isImm()) return false;
986     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
987     // If it's not a constant expression, it'll generate a fixup and be
988     // handled later.
989     if (!CE) return true;
990     int64_t Value = CE->getValue();
991     return Value >= 256 && Value < 65536;
992   }
993   bool isImm0_65535Expr() const {
994     if (!isImm()) return false;
995     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
996     // If it's not a constant expression, it'll generate a fixup and be
997     // handled later.
998     if (!CE) return true;
999     int64_t Value = CE->getValue();
1000     return Value >= 0 && Value < 65536;
1001   }
1002   bool isImm24bit() const {
1003     return isImmediate<0, 0xffffff + 1>();
1004   }
1005   bool isImmThumbSR() const {
1006     return isImmediate<1, 33>();
1007   }
1008   bool isPKHLSLImm() const {
1009     return isImmediate<0, 32>();
1010   }
1011   bool isPKHASRImm() const {
1012     return isImmediate<0, 33>();
1013   }
1014   bool isAdrLabel() const {
1015     // If we have an immediate that's not a constant, treat it as a label
1016     // reference needing a fixup.
1017     if (isImm() && !isa<MCConstantExpr>(getImm()))
1018       return true;
1019 
1020     // If it is a constant, it must fit into a modified immediate encoding.
1021     if (!isImm()) return false;
1022     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1023     if (!CE) return false;
1024     int64_t Value = CE->getValue();
1025     return (ARM_AM::getSOImmVal(Value) != -1 ||
1026             ARM_AM::getSOImmVal(-Value) != -1);
1027   }
1028   bool isT2SOImm() const {
1029     if (!isImm()) return false;
1030     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1031     if (!CE) return false;
1032     int64_t Value = CE->getValue();
1033     return ARM_AM::getT2SOImmVal(Value) != -1;
1034   }
1035   bool isT2SOImmNot() const {
1036     if (!isImm()) return false;
1037     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1038     if (!CE) return false;
1039     int64_t Value = CE->getValue();
1040     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1041       ARM_AM::getT2SOImmVal(~Value) != -1;
1042   }
1043   bool isT2SOImmNeg() const {
1044     if (!isImm()) return false;
1045     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1046     if (!CE) return false;
1047     int64_t Value = CE->getValue();
1048     // Only use this when not representable as a plain so_imm.
1049     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1050       ARM_AM::getT2SOImmVal(-Value) != -1;
1051   }
1052   bool isSetEndImm() 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 == 1 || Value == 0;
1058   }
1059   bool isReg() const override { return Kind == k_Register; }
1060   bool isRegList() const { return Kind == k_RegisterList; }
1061   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
1062   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
1063   bool isToken() const override { return Kind == k_Token; }
1064   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
1065   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
1066   bool isMem() const override { return Kind == k_Memory; }
1067   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
1068   bool isRegShiftedReg() const { return Kind == k_ShiftedRegister; }
1069   bool isRegShiftedImm() const { return Kind == k_ShiftedImmediate; }
1070   bool isRotImm() const { return Kind == k_RotateImmediate; }
1071   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1072   bool isModImmNot() const {
1073     if (!isImm()) return false;
1074     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1075     if (!CE) return false;
1076     int64_t Value = CE->getValue();
1077     return ARM_AM::getSOImmVal(~Value) != -1;
1078   }
1079   bool isModImmNeg() const {
1080     if (!isImm()) return false;
1081     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1082     if (!CE) return false;
1083     int64_t Value = CE->getValue();
1084     return ARM_AM::getSOImmVal(Value) == -1 &&
1085       ARM_AM::getSOImmVal(-Value) != -1;
1086   }
1087   bool isThumbModImmNeg1_7() const {
1088     if (!isImm()) return false;
1089     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1090     if (!CE) return false;
1091     int32_t Value = -(int32_t)CE->getValue();
1092     return 0 < Value && Value < 8;
1093   }
1094   bool isThumbModImmNeg8_255() const {
1095     if (!isImm()) return false;
1096     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1097     if (!CE) return false;
1098     int32_t Value = -(int32_t)CE->getValue();
1099     return 7 < Value && Value < 256;
1100   }
1101   bool isConstantPoolImm() const { return Kind == k_ConstantPoolImmediate; }
1102   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
1103   bool isPostIdxRegShifted() const { return Kind == k_PostIndexRegister; }
1104   bool isPostIdxReg() const {
1105     return Kind == k_PostIndexRegister && PostIdxReg.ShiftTy ==ARM_AM::no_shift;
1106   }
1107   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1108     if (!isMem())
1109       return false;
1110     // No offset of any kind.
1111     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1112      (alignOK || Memory.Alignment == Alignment);
1113   }
1114   bool isMemPCRelImm12() const {
1115     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1116       return false;
1117     // Base register must be PC.
1118     if (Memory.BaseRegNum != ARM::PC)
1119       return false;
1120     // Immediate offset in range [-4095, 4095].
1121     if (!Memory.OffsetImm) return true;
1122     int64_t Val = Memory.OffsetImm->getValue();
1123     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
1124   }
1125   bool isAlignedMemory() const {
1126     return isMemNoOffset(true);
1127   }
1128   bool isAlignedMemoryNone() const {
1129     return isMemNoOffset(false, 0);
1130   }
1131   bool isDupAlignedMemoryNone() const {
1132     return isMemNoOffset(false, 0);
1133   }
1134   bool isAlignedMemory16() const {
1135     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1136       return true;
1137     return isMemNoOffset(false, 0);
1138   }
1139   bool isDupAlignedMemory16() const {
1140     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1141       return true;
1142     return isMemNoOffset(false, 0);
1143   }
1144   bool isAlignedMemory32() const {
1145     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1146       return true;
1147     return isMemNoOffset(false, 0);
1148   }
1149   bool isDupAlignedMemory32() const {
1150     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1151       return true;
1152     return isMemNoOffset(false, 0);
1153   }
1154   bool isAlignedMemory64() const {
1155     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1156       return true;
1157     return isMemNoOffset(false, 0);
1158   }
1159   bool isDupAlignedMemory64() const {
1160     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1161       return true;
1162     return isMemNoOffset(false, 0);
1163   }
1164   bool isAlignedMemory64or128() const {
1165     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1166       return true;
1167     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1168       return true;
1169     return isMemNoOffset(false, 0);
1170   }
1171   bool isDupAlignedMemory64or128() const {
1172     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1173       return true;
1174     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1175       return true;
1176     return isMemNoOffset(false, 0);
1177   }
1178   bool isAlignedMemory64or128or256() const {
1179     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1180       return true;
1181     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1182       return true;
1183     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1184       return true;
1185     return isMemNoOffset(false, 0);
1186   }
1187   bool isAddrMode2() const {
1188     if (!isMem() || Memory.Alignment != 0) return false;
1189     // Check for register offset.
1190     if (Memory.OffsetRegNum) return true;
1191     // Immediate offset in range [-4095, 4095].
1192     if (!Memory.OffsetImm) return true;
1193     int64_t Val = Memory.OffsetImm->getValue();
1194     return Val > -4096 && Val < 4096;
1195   }
1196   bool isAM2OffsetImm() const {
1197     if (!isImm()) return false;
1198     // Immediate offset in range [-4095, 4095].
1199     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1200     if (!CE) return false;
1201     int64_t Val = CE->getValue();
1202     return (Val == INT32_MIN) || (Val > -4096 && Val < 4096);
1203   }
1204   bool isAddrMode3() const {
1205     // If we have an immediate that's not a constant, treat it as a label
1206     // reference needing a fixup. If it is a constant, it's something else
1207     // and we reject it.
1208     if (isImm() && !isa<MCConstantExpr>(getImm()))
1209       return true;
1210     if (!isMem() || Memory.Alignment != 0) return false;
1211     // No shifts are legal for AM3.
1212     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1213     // Check for register offset.
1214     if (Memory.OffsetRegNum) return true;
1215     // Immediate offset in range [-255, 255].
1216     if (!Memory.OffsetImm) return true;
1217     int64_t Val = Memory.OffsetImm->getValue();
1218     // The #-0 offset is encoded as INT32_MIN, and we have to check
1219     // for this too.
1220     return (Val > -256 && Val < 256) || Val == INT32_MIN;
1221   }
1222   bool isAM3Offset() const {
1223     if (Kind != k_Immediate && Kind != k_PostIndexRegister)
1224       return false;
1225     if (Kind == k_PostIndexRegister)
1226       return PostIdxReg.ShiftTy == ARM_AM::no_shift;
1227     // Immediate offset in range [-255, 255].
1228     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1229     if (!CE) return false;
1230     int64_t Val = CE->getValue();
1231     // Special case, #-0 is INT32_MIN.
1232     return (Val > -256 && Val < 256) || Val == INT32_MIN;
1233   }
1234   bool isAddrMode5() const {
1235     // If we have an immediate that's not a constant, treat it as a label
1236     // reference needing a fixup. If it is a constant, it's something else
1237     // and we reject it.
1238     if (isImm() && !isa<MCConstantExpr>(getImm()))
1239       return true;
1240     if (!isMem() || Memory.Alignment != 0) return false;
1241     // Check for register offset.
1242     if (Memory.OffsetRegNum) return false;
1243     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1244     if (!Memory.OffsetImm) return true;
1245     int64_t Val = Memory.OffsetImm->getValue();
1246     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1247       Val == INT32_MIN;
1248   }
1249   bool isAddrMode5FP16() const {
1250     // If we have an immediate that's not a constant, treat it as a label
1251     // reference needing a fixup. If it is a constant, it's something else
1252     // and we reject it.
1253     if (isImm() && !isa<MCConstantExpr>(getImm()))
1254       return true;
1255     if (!isMem() || Memory.Alignment != 0) return false;
1256     // Check for register offset.
1257     if (Memory.OffsetRegNum) return false;
1258     // Immediate offset in range [-510, 510] and a multiple of 2.
1259     if (!Memory.OffsetImm) return true;
1260     int64_t Val = Memory.OffsetImm->getValue();
1261     return (Val >= -510 && Val <= 510 && ((Val & 1) == 0)) || Val == INT32_MIN;
1262   }
1263   bool isMemTBB() const {
1264     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1265         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1266       return false;
1267     return true;
1268   }
1269   bool isMemTBH() const {
1270     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1271         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1272         Memory.Alignment != 0 )
1273       return false;
1274     return true;
1275   }
1276   bool isMemRegOffset() const {
1277     if (!isMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1278       return false;
1279     return true;
1280   }
1281   bool isT2MemRegOffset() const {
1282     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1283         Memory.Alignment != 0 || Memory.BaseRegNum == ARM::PC)
1284       return false;
1285     // Only lsl #{0, 1, 2, 3} allowed.
1286     if (Memory.ShiftType == ARM_AM::no_shift)
1287       return true;
1288     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1289       return false;
1290     return true;
1291   }
1292   bool isMemThumbRR() const {
1293     // Thumb reg+reg addressing is simple. Just two registers, a base and
1294     // an offset. No shifts, negations or any other complicating factors.
1295     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1296         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1297       return false;
1298     return isARMLowRegister(Memory.BaseRegNum) &&
1299       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1300   }
1301   bool isMemThumbRIs4() const {
1302     if (!isMem() || Memory.OffsetRegNum != 0 ||
1303         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1304       return false;
1305     // Immediate offset, multiple of 4 in range [0, 124].
1306     if (!Memory.OffsetImm) return true;
1307     int64_t Val = Memory.OffsetImm->getValue();
1308     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1309   }
1310   bool isMemThumbRIs2() const {
1311     if (!isMem() || Memory.OffsetRegNum != 0 ||
1312         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1313       return false;
1314     // Immediate offset, multiple of 4 in range [0, 62].
1315     if (!Memory.OffsetImm) return true;
1316     int64_t Val = Memory.OffsetImm->getValue();
1317     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1318   }
1319   bool isMemThumbRIs1() const {
1320     if (!isMem() || Memory.OffsetRegNum != 0 ||
1321         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1322       return false;
1323     // Immediate offset in range [0, 31].
1324     if (!Memory.OffsetImm) return true;
1325     int64_t Val = Memory.OffsetImm->getValue();
1326     return Val >= 0 && Val <= 31;
1327   }
1328   bool isMemThumbSPI() const {
1329     if (!isMem() || Memory.OffsetRegNum != 0 ||
1330         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1331       return false;
1332     // Immediate offset, multiple of 4 in range [0, 1020].
1333     if (!Memory.OffsetImm) return true;
1334     int64_t Val = Memory.OffsetImm->getValue();
1335     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1336   }
1337   bool isMemImm8s4Offset() const {
1338     // If we have an immediate that's not a constant, treat it as a label
1339     // reference needing a fixup. If it is a constant, it's something else
1340     // and we reject it.
1341     if (isImm() && !isa<MCConstantExpr>(getImm()))
1342       return true;
1343     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1344       return false;
1345     // Immediate offset a multiple of 4 in range [-1020, 1020].
1346     if (!Memory.OffsetImm) return true;
1347     int64_t Val = Memory.OffsetImm->getValue();
1348     // Special case, #-0 is INT32_MIN.
1349     return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) || Val == INT32_MIN;
1350   }
1351   bool isMemImm0_1020s4Offset() const {
1352     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1353       return false;
1354     // Immediate offset a multiple of 4 in range [0, 1020].
1355     if (!Memory.OffsetImm) return true;
1356     int64_t Val = Memory.OffsetImm->getValue();
1357     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1358   }
1359   bool isMemImm8Offset() const {
1360     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1361       return false;
1362     // Base reg of PC isn't allowed for these encodings.
1363     if (Memory.BaseRegNum == ARM::PC) return false;
1364     // Immediate offset in range [-255, 255].
1365     if (!Memory.OffsetImm) return true;
1366     int64_t Val = Memory.OffsetImm->getValue();
1367     return (Val == INT32_MIN) || (Val > -256 && Val < 256);
1368   }
1369   bool isMemPosImm8Offset() const {
1370     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1371       return false;
1372     // Immediate offset in range [0, 255].
1373     if (!Memory.OffsetImm) return true;
1374     int64_t Val = Memory.OffsetImm->getValue();
1375     return Val >= 0 && Val < 256;
1376   }
1377   bool isMemNegImm8Offset() const {
1378     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1379       return false;
1380     // Base reg of PC isn't allowed for these encodings.
1381     if (Memory.BaseRegNum == ARM::PC) return false;
1382     // Immediate offset in range [-255, -1].
1383     if (!Memory.OffsetImm) return false;
1384     int64_t Val = Memory.OffsetImm->getValue();
1385     return (Val == INT32_MIN) || (Val > -256 && Val < 0);
1386   }
1387   bool isMemUImm12Offset() const {
1388     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1389       return false;
1390     // Immediate offset in range [0, 4095].
1391     if (!Memory.OffsetImm) return true;
1392     int64_t Val = Memory.OffsetImm->getValue();
1393     return (Val >= 0 && Val < 4096);
1394   }
1395   bool isMemImm12Offset() const {
1396     // If we have an immediate that's not a constant, treat it as a label
1397     // reference needing a fixup. If it is a constant, it's something else
1398     // and we reject it.
1399 
1400     if (isImm() && !isa<MCConstantExpr>(getImm()))
1401       return true;
1402 
1403     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1404       return false;
1405     // Immediate offset in range [-4095, 4095].
1406     if (!Memory.OffsetImm) return true;
1407     int64_t Val = Memory.OffsetImm->getValue();
1408     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
1409   }
1410   bool isConstPoolAsmImm() const {
1411     // Delay processing of Constant Pool Immediate, this will turn into
1412     // a constant. Match no other operand
1413     return (isConstantPoolImm());
1414   }
1415   bool isPostIdxImm8() const {
1416     if (!isImm()) return false;
1417     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1418     if (!CE) return false;
1419     int64_t Val = CE->getValue();
1420     return (Val > -256 && Val < 256) || (Val == INT32_MIN);
1421   }
1422   bool isPostIdxImm8s4() const {
1423     if (!isImm()) return false;
1424     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1425     if (!CE) return false;
1426     int64_t Val = CE->getValue();
1427     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
1428       (Val == INT32_MIN);
1429   }
1430 
1431   bool isMSRMask() const { return Kind == k_MSRMask; }
1432   bool isBankedReg() const { return Kind == k_BankedReg; }
1433   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
1434 
1435   // NEON operands.
1436   bool isSingleSpacedVectorList() const {
1437     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
1438   }
1439   bool isDoubleSpacedVectorList() const {
1440     return Kind == k_VectorList && VectorList.isDoubleSpaced;
1441   }
1442   bool isVecListOneD() const {
1443     if (!isSingleSpacedVectorList()) return false;
1444     return VectorList.Count == 1;
1445   }
1446 
1447   bool isVecListDPair() const {
1448     if (!isSingleSpacedVectorList()) return false;
1449     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1450               .contains(VectorList.RegNum));
1451   }
1452 
1453   bool isVecListThreeD() const {
1454     if (!isSingleSpacedVectorList()) return false;
1455     return VectorList.Count == 3;
1456   }
1457 
1458   bool isVecListFourD() const {
1459     if (!isSingleSpacedVectorList()) return false;
1460     return VectorList.Count == 4;
1461   }
1462 
1463   bool isVecListDPairSpaced() const {
1464     if (Kind != k_VectorList) return false;
1465     if (isSingleSpacedVectorList()) return false;
1466     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
1467               .contains(VectorList.RegNum));
1468   }
1469 
1470   bool isVecListThreeQ() const {
1471     if (!isDoubleSpacedVectorList()) return false;
1472     return VectorList.Count == 3;
1473   }
1474 
1475   bool isVecListFourQ() const {
1476     if (!isDoubleSpacedVectorList()) return false;
1477     return VectorList.Count == 4;
1478   }
1479 
1480   bool isSingleSpacedVectorAllLanes() const {
1481     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
1482   }
1483   bool isDoubleSpacedVectorAllLanes() const {
1484     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
1485   }
1486   bool isVecListOneDAllLanes() const {
1487     if (!isSingleSpacedVectorAllLanes()) return false;
1488     return VectorList.Count == 1;
1489   }
1490 
1491   bool isVecListDPairAllLanes() const {
1492     if (!isSingleSpacedVectorAllLanes()) return false;
1493     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1494               .contains(VectorList.RegNum));
1495   }
1496 
1497   bool isVecListDPairSpacedAllLanes() const {
1498     if (!isDoubleSpacedVectorAllLanes()) return false;
1499     return VectorList.Count == 2;
1500   }
1501 
1502   bool isVecListThreeDAllLanes() const {
1503     if (!isSingleSpacedVectorAllLanes()) return false;
1504     return VectorList.Count == 3;
1505   }
1506 
1507   bool isVecListThreeQAllLanes() const {
1508     if (!isDoubleSpacedVectorAllLanes()) return false;
1509     return VectorList.Count == 3;
1510   }
1511 
1512   bool isVecListFourDAllLanes() const {
1513     if (!isSingleSpacedVectorAllLanes()) return false;
1514     return VectorList.Count == 4;
1515   }
1516 
1517   bool isVecListFourQAllLanes() const {
1518     if (!isDoubleSpacedVectorAllLanes()) return false;
1519     return VectorList.Count == 4;
1520   }
1521 
1522   bool isSingleSpacedVectorIndexed() const {
1523     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
1524   }
1525   bool isDoubleSpacedVectorIndexed() const {
1526     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
1527   }
1528   bool isVecListOneDByteIndexed() const {
1529     if (!isSingleSpacedVectorIndexed()) return false;
1530     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
1531   }
1532 
1533   bool isVecListOneDHWordIndexed() const {
1534     if (!isSingleSpacedVectorIndexed()) return false;
1535     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
1536   }
1537 
1538   bool isVecListOneDWordIndexed() const {
1539     if (!isSingleSpacedVectorIndexed()) return false;
1540     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
1541   }
1542 
1543   bool isVecListTwoDByteIndexed() const {
1544     if (!isSingleSpacedVectorIndexed()) return false;
1545     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
1546   }
1547 
1548   bool isVecListTwoDHWordIndexed() const {
1549     if (!isSingleSpacedVectorIndexed()) return false;
1550     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1551   }
1552 
1553   bool isVecListTwoQWordIndexed() const {
1554     if (!isDoubleSpacedVectorIndexed()) return false;
1555     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1556   }
1557 
1558   bool isVecListTwoQHWordIndexed() const {
1559     if (!isDoubleSpacedVectorIndexed()) return false;
1560     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1561   }
1562 
1563   bool isVecListTwoDWordIndexed() const {
1564     if (!isSingleSpacedVectorIndexed()) return false;
1565     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1566   }
1567 
1568   bool isVecListThreeDByteIndexed() const {
1569     if (!isSingleSpacedVectorIndexed()) return false;
1570     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
1571   }
1572 
1573   bool isVecListThreeDHWordIndexed() const {
1574     if (!isSingleSpacedVectorIndexed()) return false;
1575     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1576   }
1577 
1578   bool isVecListThreeQWordIndexed() const {
1579     if (!isDoubleSpacedVectorIndexed()) return false;
1580     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1581   }
1582 
1583   bool isVecListThreeQHWordIndexed() const {
1584     if (!isDoubleSpacedVectorIndexed()) return false;
1585     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1586   }
1587 
1588   bool isVecListThreeDWordIndexed() const {
1589     if (!isSingleSpacedVectorIndexed()) return false;
1590     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1591   }
1592 
1593   bool isVecListFourDByteIndexed() const {
1594     if (!isSingleSpacedVectorIndexed()) return false;
1595     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
1596   }
1597 
1598   bool isVecListFourDHWordIndexed() const {
1599     if (!isSingleSpacedVectorIndexed()) return false;
1600     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1601   }
1602 
1603   bool isVecListFourQWordIndexed() const {
1604     if (!isDoubleSpacedVectorIndexed()) return false;
1605     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1606   }
1607 
1608   bool isVecListFourQHWordIndexed() const {
1609     if (!isDoubleSpacedVectorIndexed()) return false;
1610     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1611   }
1612 
1613   bool isVecListFourDWordIndexed() const {
1614     if (!isSingleSpacedVectorIndexed()) return false;
1615     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1616   }
1617 
1618   bool isVectorIndex8() const {
1619     if (Kind != k_VectorIndex) return false;
1620     return VectorIndex.Val < 8;
1621   }
1622   bool isVectorIndex16() const {
1623     if (Kind != k_VectorIndex) return false;
1624     return VectorIndex.Val < 4;
1625   }
1626   bool isVectorIndex32() const {
1627     if (Kind != k_VectorIndex) return false;
1628     return VectorIndex.Val < 2;
1629   }
1630 
1631   bool isNEONi8splat() const {
1632     if (!isImm()) return false;
1633     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1634     // Must be a constant.
1635     if (!CE) return false;
1636     int64_t Value = CE->getValue();
1637     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
1638     // value.
1639     return Value >= 0 && Value < 256;
1640   }
1641 
1642   bool isNEONi16splat() const {
1643     if (isNEONByteReplicate(2))
1644       return false; // Leave that for bytes replication and forbid by default.
1645     if (!isImm())
1646       return false;
1647     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1648     // Must be a constant.
1649     if (!CE) return false;
1650     unsigned Value = CE->getValue();
1651     return ARM_AM::isNEONi16splat(Value);
1652   }
1653 
1654   bool isNEONi16splatNot() const {
1655     if (!isImm())
1656       return false;
1657     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1658     // Must be a constant.
1659     if (!CE) return false;
1660     unsigned Value = CE->getValue();
1661     return ARM_AM::isNEONi16splat(~Value & 0xffff);
1662   }
1663 
1664   bool isNEONi32splat() const {
1665     if (isNEONByteReplicate(4))
1666       return false; // Leave that for bytes replication and forbid by default.
1667     if (!isImm())
1668       return false;
1669     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1670     // Must be a constant.
1671     if (!CE) return false;
1672     unsigned Value = CE->getValue();
1673     return ARM_AM::isNEONi32splat(Value);
1674   }
1675 
1676   bool isNEONi32splatNot() const {
1677     if (!isImm())
1678       return false;
1679     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1680     // Must be a constant.
1681     if (!CE) return false;
1682     unsigned Value = CE->getValue();
1683     return ARM_AM::isNEONi32splat(~Value);
1684   }
1685 
1686   bool isNEONByteReplicate(unsigned NumBytes) const {
1687     if (!isImm())
1688       return false;
1689     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1690     // Must be a constant.
1691     if (!CE)
1692       return false;
1693     int64_t Value = CE->getValue();
1694     if (!Value)
1695       return false; // Don't bother with zero.
1696 
1697     unsigned char B = Value & 0xff;
1698     for (unsigned i = 1; i < NumBytes; ++i) {
1699       Value >>= 8;
1700       if ((Value & 0xff) != B)
1701         return false;
1702     }
1703     return true;
1704   }
1705   bool isNEONi16ByteReplicate() const { return isNEONByteReplicate(2); }
1706   bool isNEONi32ByteReplicate() const { return isNEONByteReplicate(4); }
1707   bool isNEONi32vmov() const {
1708     if (isNEONByteReplicate(4))
1709       return false; // Let it to be classified as byte-replicate case.
1710     if (!isImm())
1711       return false;
1712     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1713     // Must be a constant.
1714     if (!CE)
1715       return false;
1716     int64_t Value = CE->getValue();
1717     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1718     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1719     // FIXME: This is probably wrong and a copy and paste from previous example
1720     return (Value >= 0 && Value < 256) ||
1721       (Value >= 0x0100 && Value <= 0xff00) ||
1722       (Value >= 0x010000 && Value <= 0xff0000) ||
1723       (Value >= 0x01000000 && Value <= 0xff000000) ||
1724       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1725       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1726   }
1727   bool isNEONi32vmovNeg() const {
1728     if (!isImm()) return false;
1729     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1730     // Must be a constant.
1731     if (!CE) return false;
1732     int64_t Value = ~CE->getValue();
1733     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1734     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1735     // FIXME: This is probably wrong and a copy and paste from previous example
1736     return (Value >= 0 && Value < 256) ||
1737       (Value >= 0x0100 && Value <= 0xff00) ||
1738       (Value >= 0x010000 && Value <= 0xff0000) ||
1739       (Value >= 0x01000000 && Value <= 0xff000000) ||
1740       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1741       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1742   }
1743 
1744   bool isNEONi64splat() const {
1745     if (!isImm()) return false;
1746     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1747     // Must be a constant.
1748     if (!CE) return false;
1749     uint64_t Value = CE->getValue();
1750     // i64 value with each byte being either 0 or 0xff.
1751     for (unsigned i = 0; i < 8; ++i, Value >>= 8)
1752       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
1753     return true;
1754   }
1755 
1756   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
1757     // Add as immediates when possible.  Null MCExpr = 0.
1758     if (!Expr)
1759       Inst.addOperand(MCOperand::createImm(0));
1760     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
1761       Inst.addOperand(MCOperand::createImm(CE->getValue()));
1762     else
1763       Inst.addOperand(MCOperand::createExpr(Expr));
1764   }
1765 
1766   void addARMBranchTargetOperands(MCInst &Inst, unsigned N) const {
1767     assert(N == 1 && "Invalid number of operands!");
1768     addExpr(Inst, getImm());
1769   }
1770 
1771   void addThumbBranchTargetOperands(MCInst &Inst, unsigned N) const {
1772     assert(N == 1 && "Invalid number of operands!");
1773     addExpr(Inst, getImm());
1774   }
1775 
1776   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
1777     assert(N == 2 && "Invalid number of operands!");
1778     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1779     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
1780     Inst.addOperand(MCOperand::createReg(RegNum));
1781   }
1782 
1783   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
1784     assert(N == 1 && "Invalid number of operands!");
1785     Inst.addOperand(MCOperand::createImm(getCoproc()));
1786   }
1787 
1788   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
1789     assert(N == 1 && "Invalid number of operands!");
1790     Inst.addOperand(MCOperand::createImm(getCoproc()));
1791   }
1792 
1793   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
1794     assert(N == 1 && "Invalid number of operands!");
1795     Inst.addOperand(MCOperand::createImm(CoprocOption.Val));
1796   }
1797 
1798   void addITMaskOperands(MCInst &Inst, unsigned N) const {
1799     assert(N == 1 && "Invalid number of operands!");
1800     Inst.addOperand(MCOperand::createImm(ITMask.Mask));
1801   }
1802 
1803   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
1804     assert(N == 1 && "Invalid number of operands!");
1805     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1806   }
1807 
1808   void addCCOutOperands(MCInst &Inst, unsigned N) const {
1809     assert(N == 1 && "Invalid number of operands!");
1810     Inst.addOperand(MCOperand::createReg(getReg()));
1811   }
1812 
1813   void addRegOperands(MCInst &Inst, unsigned N) const {
1814     assert(N == 1 && "Invalid number of operands!");
1815     Inst.addOperand(MCOperand::createReg(getReg()));
1816   }
1817 
1818   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
1819     assert(N == 3 && "Invalid number of operands!");
1820     assert(isRegShiftedReg() &&
1821            "addRegShiftedRegOperands() on non-RegShiftedReg!");
1822     Inst.addOperand(MCOperand::createReg(RegShiftedReg.SrcReg));
1823     Inst.addOperand(MCOperand::createReg(RegShiftedReg.ShiftReg));
1824     Inst.addOperand(MCOperand::createImm(
1825       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
1826   }
1827 
1828   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
1829     assert(N == 2 && "Invalid number of operands!");
1830     assert(isRegShiftedImm() &&
1831            "addRegShiftedImmOperands() on non-RegShiftedImm!");
1832     Inst.addOperand(MCOperand::createReg(RegShiftedImm.SrcReg));
1833     // Shift of #32 is encoded as 0 where permitted
1834     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
1835     Inst.addOperand(MCOperand::createImm(
1836       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
1837   }
1838 
1839   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
1840     assert(N == 1 && "Invalid number of operands!");
1841     Inst.addOperand(MCOperand::createImm((ShifterImm.isASR << 5) |
1842                                          ShifterImm.Imm));
1843   }
1844 
1845   void addRegListOperands(MCInst &Inst, unsigned N) const {
1846     assert(N == 1 && "Invalid number of operands!");
1847     const SmallVectorImpl<unsigned> &RegList = getRegList();
1848     for (SmallVectorImpl<unsigned>::const_iterator
1849            I = RegList.begin(), E = RegList.end(); I != E; ++I)
1850       Inst.addOperand(MCOperand::createReg(*I));
1851   }
1852 
1853   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
1854     addRegListOperands(Inst, N);
1855   }
1856 
1857   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
1858     addRegListOperands(Inst, N);
1859   }
1860 
1861   void addRotImmOperands(MCInst &Inst, unsigned N) const {
1862     assert(N == 1 && "Invalid number of operands!");
1863     // Encoded as val>>3. The printer handles display as 8, 16, 24.
1864     Inst.addOperand(MCOperand::createImm(RotImm.Imm >> 3));
1865   }
1866 
1867   void addModImmOperands(MCInst &Inst, unsigned N) const {
1868     assert(N == 1 && "Invalid number of operands!");
1869 
1870     // Support for fixups (MCFixup)
1871     if (isImm())
1872       return addImmOperands(Inst, N);
1873 
1874     Inst.addOperand(MCOperand::createImm(ModImm.Bits | (ModImm.Rot << 7)));
1875   }
1876 
1877   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
1878     assert(N == 1 && "Invalid number of operands!");
1879     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1880     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
1881     Inst.addOperand(MCOperand::createImm(Enc));
1882   }
1883 
1884   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
1885     assert(N == 1 && "Invalid number of operands!");
1886     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1887     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
1888     Inst.addOperand(MCOperand::createImm(Enc));
1889   }
1890 
1891   void addThumbModImmNeg8_255Operands(MCInst &Inst, unsigned N) const {
1892     assert(N == 1 && "Invalid number of operands!");
1893     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1894     uint32_t Val = -CE->getValue();
1895     Inst.addOperand(MCOperand::createImm(Val));
1896   }
1897 
1898   void addThumbModImmNeg1_7Operands(MCInst &Inst, unsigned N) const {
1899     assert(N == 1 && "Invalid number of operands!");
1900     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1901     uint32_t Val = -CE->getValue();
1902     Inst.addOperand(MCOperand::createImm(Val));
1903   }
1904 
1905   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
1906     assert(N == 1 && "Invalid number of operands!");
1907     // Munge the lsb/width into a bitfield mask.
1908     unsigned lsb = Bitfield.LSB;
1909     unsigned width = Bitfield.Width;
1910     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
1911     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
1912                       (32 - (lsb + width)));
1913     Inst.addOperand(MCOperand::createImm(Mask));
1914   }
1915 
1916   void addImmOperands(MCInst &Inst, unsigned N) const {
1917     assert(N == 1 && "Invalid number of operands!");
1918     addExpr(Inst, getImm());
1919   }
1920 
1921   void addFBits16Operands(MCInst &Inst, unsigned N) const {
1922     assert(N == 1 && "Invalid number of operands!");
1923     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1924     Inst.addOperand(MCOperand::createImm(16 - CE->getValue()));
1925   }
1926 
1927   void addFBits32Operands(MCInst &Inst, unsigned N) const {
1928     assert(N == 1 && "Invalid number of operands!");
1929     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1930     Inst.addOperand(MCOperand::createImm(32 - CE->getValue()));
1931   }
1932 
1933   void addFPImmOperands(MCInst &Inst, unsigned N) const {
1934     assert(N == 1 && "Invalid number of operands!");
1935     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1936     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
1937     Inst.addOperand(MCOperand::createImm(Val));
1938   }
1939 
1940   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
1941     assert(N == 1 && "Invalid number of operands!");
1942     // FIXME: We really want to scale the value here, but the LDRD/STRD
1943     // instruction don't encode operands that way yet.
1944     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1945     Inst.addOperand(MCOperand::createImm(CE->getValue()));
1946   }
1947 
1948   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
1949     assert(N == 1 && "Invalid number of operands!");
1950     // The immediate is scaled by four in the encoding and is stored
1951     // in the MCInst as such. Lop off the low two bits here.
1952     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1953     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
1954   }
1955 
1956   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
1957     assert(N == 1 && "Invalid number of operands!");
1958     // The immediate is scaled by four in the encoding and is stored
1959     // in the MCInst as such. Lop off the low two bits here.
1960     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1961     Inst.addOperand(MCOperand::createImm(-(CE->getValue() / 4)));
1962   }
1963 
1964   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
1965     assert(N == 1 && "Invalid number of operands!");
1966     // The immediate is scaled by four in the encoding and is stored
1967     // in the MCInst as such. Lop off the low two bits here.
1968     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1969     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
1970   }
1971 
1972   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
1973     assert(N == 1 && "Invalid number of operands!");
1974     // The constant encodes as the immediate-1, and we store in the instruction
1975     // the bits as encoded, so subtract off one here.
1976     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1977     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
1978   }
1979 
1980   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
1981     assert(N == 1 && "Invalid number of operands!");
1982     // The constant encodes as the immediate-1, and we store in the instruction
1983     // the bits as encoded, so subtract off one here.
1984     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1985     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
1986   }
1987 
1988   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
1989     assert(N == 1 && "Invalid number of operands!");
1990     // The constant encodes as the immediate, except for 32, which encodes as
1991     // zero.
1992     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1993     unsigned Imm = CE->getValue();
1994     Inst.addOperand(MCOperand::createImm((Imm == 32 ? 0 : Imm)));
1995   }
1996 
1997   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
1998     assert(N == 1 && "Invalid number of operands!");
1999     // An ASR value of 32 encodes as 0, so that's how we want to add it to
2000     // the instruction as well.
2001     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2002     int Val = CE->getValue();
2003     Inst.addOperand(MCOperand::createImm(Val == 32 ? 0 : Val));
2004   }
2005 
2006   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
2007     assert(N == 1 && "Invalid number of operands!");
2008     // The operand is actually a t2_so_imm, but we have its bitwise
2009     // negation in the assembly source, so twiddle it here.
2010     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2011     Inst.addOperand(MCOperand::createImm(~(uint32_t)CE->getValue()));
2012   }
2013 
2014   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
2015     assert(N == 1 && "Invalid number of operands!");
2016     // The operand is actually a t2_so_imm, but we have its
2017     // negation in the assembly source, so twiddle it here.
2018     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2019     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2020   }
2021 
2022   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
2023     assert(N == 1 && "Invalid number of operands!");
2024     // The operand is actually an imm0_4095, but we have its
2025     // negation in the assembly source, so twiddle it here.
2026     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2027     Inst.addOperand(MCOperand::createImm(-CE->getValue()));
2028   }
2029 
2030   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
2031     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
2032       Inst.addOperand(MCOperand::createImm(CE->getValue() >> 2));
2033       return;
2034     }
2035 
2036     const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2037     assert(SR && "Unknown value type!");
2038     Inst.addOperand(MCOperand::createExpr(SR));
2039   }
2040 
2041   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
2042     assert(N == 1 && "Invalid number of operands!");
2043     if (isImm()) {
2044       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2045       if (CE) {
2046         Inst.addOperand(MCOperand::createImm(CE->getValue()));
2047         return;
2048       }
2049 
2050       const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2051 
2052       assert(SR && "Unknown value type!");
2053       Inst.addOperand(MCOperand::createExpr(SR));
2054       return;
2055     }
2056 
2057     assert(isMem()  && "Unknown value type!");
2058     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
2059     Inst.addOperand(MCOperand::createImm(Memory.OffsetImm->getValue()));
2060   }
2061 
2062   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
2063     assert(N == 1 && "Invalid number of operands!");
2064     Inst.addOperand(MCOperand::createImm(unsigned(getMemBarrierOpt())));
2065   }
2066 
2067   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2068     assert(N == 1 && "Invalid number of operands!");
2069     Inst.addOperand(MCOperand::createImm(unsigned(getInstSyncBarrierOpt())));
2070   }
2071 
2072   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
2073     assert(N == 1 && "Invalid number of operands!");
2074     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2075   }
2076 
2077   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
2078     assert(N == 1 && "Invalid number of operands!");
2079     int32_t Imm = Memory.OffsetImm->getValue();
2080     Inst.addOperand(MCOperand::createImm(Imm));
2081   }
2082 
2083   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
2084     assert(N == 1 && "Invalid number of operands!");
2085     assert(isImm() && "Not an immediate!");
2086 
2087     // If we have an immediate that's not a constant, treat it as a label
2088     // reference needing a fixup.
2089     if (!isa<MCConstantExpr>(getImm())) {
2090       Inst.addOperand(MCOperand::createExpr(getImm()));
2091       return;
2092     }
2093 
2094     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2095     int Val = CE->getValue();
2096     Inst.addOperand(MCOperand::createImm(Val));
2097   }
2098 
2099   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
2100     assert(N == 2 && "Invalid number of operands!");
2101     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2102     Inst.addOperand(MCOperand::createImm(Memory.Alignment));
2103   }
2104 
2105   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2106     addAlignedMemoryOperands(Inst, N);
2107   }
2108 
2109   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2110     addAlignedMemoryOperands(Inst, N);
2111   }
2112 
2113   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2114     addAlignedMemoryOperands(Inst, N);
2115   }
2116 
2117   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2118     addAlignedMemoryOperands(Inst, N);
2119   }
2120 
2121   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2122     addAlignedMemoryOperands(Inst, N);
2123   }
2124 
2125   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2126     addAlignedMemoryOperands(Inst, N);
2127   }
2128 
2129   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2130     addAlignedMemoryOperands(Inst, N);
2131   }
2132 
2133   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2134     addAlignedMemoryOperands(Inst, N);
2135   }
2136 
2137   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2138     addAlignedMemoryOperands(Inst, N);
2139   }
2140 
2141   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2142     addAlignedMemoryOperands(Inst, N);
2143   }
2144 
2145   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2146     addAlignedMemoryOperands(Inst, N);
2147   }
2148 
2149   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2150     assert(N == 3 && "Invalid number of operands!");
2151     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2152     if (!Memory.OffsetRegNum) {
2153       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2154       // Special case for #-0
2155       if (Val == INT32_MIN) Val = 0;
2156       if (Val < 0) Val = -Val;
2157       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2158     } else {
2159       // For register offset, we encode the shift type and negation flag
2160       // here.
2161       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2162                               Memory.ShiftImm, Memory.ShiftType);
2163     }
2164     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2165     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2166     Inst.addOperand(MCOperand::createImm(Val));
2167   }
2168 
2169   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2170     assert(N == 2 && "Invalid number of operands!");
2171     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2172     assert(CE && "non-constant AM2OffsetImm operand!");
2173     int32_t Val = CE->getValue();
2174     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2175     // Special case for #-0
2176     if (Val == INT32_MIN) Val = 0;
2177     if (Val < 0) Val = -Val;
2178     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2179     Inst.addOperand(MCOperand::createReg(0));
2180     Inst.addOperand(MCOperand::createImm(Val));
2181   }
2182 
2183   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2184     assert(N == 3 && "Invalid number of operands!");
2185     // If we have an immediate that's not a constant, treat it as a label
2186     // reference needing a fixup. If it is a constant, it's something else
2187     // and we reject it.
2188     if (isImm()) {
2189       Inst.addOperand(MCOperand::createExpr(getImm()));
2190       Inst.addOperand(MCOperand::createReg(0));
2191       Inst.addOperand(MCOperand::createImm(0));
2192       return;
2193     }
2194 
2195     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2196     if (!Memory.OffsetRegNum) {
2197       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2198       // Special case for #-0
2199       if (Val == INT32_MIN) Val = 0;
2200       if (Val < 0) Val = -Val;
2201       Val = ARM_AM::getAM3Opc(AddSub, Val);
2202     } else {
2203       // For register offset, we encode the shift type and negation flag
2204       // here.
2205       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
2206     }
2207     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2208     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2209     Inst.addOperand(MCOperand::createImm(Val));
2210   }
2211 
2212   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
2213     assert(N == 2 && "Invalid number of operands!");
2214     if (Kind == k_PostIndexRegister) {
2215       int32_t Val =
2216         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
2217       Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2218       Inst.addOperand(MCOperand::createImm(Val));
2219       return;
2220     }
2221 
2222     // Constant offset.
2223     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
2224     int32_t Val = CE->getValue();
2225     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2226     // Special case for #-0
2227     if (Val == INT32_MIN) Val = 0;
2228     if (Val < 0) Val = -Val;
2229     Val = ARM_AM::getAM3Opc(AddSub, Val);
2230     Inst.addOperand(MCOperand::createReg(0));
2231     Inst.addOperand(MCOperand::createImm(Val));
2232   }
2233 
2234   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
2235     assert(N == 2 && "Invalid number of operands!");
2236     // If we have an immediate that's not a constant, treat it as a label
2237     // reference needing a fixup. If it is a constant, it's something else
2238     // and we reject it.
2239     if (isImm()) {
2240       Inst.addOperand(MCOperand::createExpr(getImm()));
2241       Inst.addOperand(MCOperand::createImm(0));
2242       return;
2243     }
2244 
2245     // The lower two bits are always zero and as such are not encoded.
2246     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2247     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2248     // Special case for #-0
2249     if (Val == INT32_MIN) Val = 0;
2250     if (Val < 0) Val = -Val;
2251     Val = ARM_AM::getAM5Opc(AddSub, Val);
2252     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2253     Inst.addOperand(MCOperand::createImm(Val));
2254   }
2255 
2256   void addAddrMode5FP16Operands(MCInst &Inst, unsigned N) const {
2257     assert(N == 2 && "Invalid number of operands!");
2258     // If we have an immediate that's not a constant, treat it as a label
2259     // reference needing a fixup. If it is a constant, it's something else
2260     // and we reject it.
2261     if (isImm()) {
2262       Inst.addOperand(MCOperand::createExpr(getImm()));
2263       Inst.addOperand(MCOperand::createImm(0));
2264       return;
2265     }
2266 
2267     // The lower bit is always zero and as such is not encoded.
2268     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 2 : 0;
2269     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2270     // Special case for #-0
2271     if (Val == INT32_MIN) Val = 0;
2272     if (Val < 0) Val = -Val;
2273     Val = ARM_AM::getAM5FP16Opc(AddSub, Val);
2274     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2275     Inst.addOperand(MCOperand::createImm(Val));
2276   }
2277 
2278   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
2279     assert(N == 2 && "Invalid number of operands!");
2280     // If we have an immediate that's not a constant, treat it as a label
2281     // reference needing a fixup. If it is a constant, it's something else
2282     // and we reject it.
2283     if (isImm()) {
2284       Inst.addOperand(MCOperand::createExpr(getImm()));
2285       Inst.addOperand(MCOperand::createImm(0));
2286       return;
2287     }
2288 
2289     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2290     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2291     Inst.addOperand(MCOperand::createImm(Val));
2292   }
2293 
2294   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
2295     assert(N == 2 && "Invalid number of operands!");
2296     // The lower two bits are always zero and as such are not encoded.
2297     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2298     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2299     Inst.addOperand(MCOperand::createImm(Val));
2300   }
2301 
2302   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2303     assert(N == 2 && "Invalid number of operands!");
2304     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2305     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2306     Inst.addOperand(MCOperand::createImm(Val));
2307   }
2308 
2309   void addMemPosImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2310     addMemImm8OffsetOperands(Inst, N);
2311   }
2312 
2313   void addMemNegImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2314     addMemImm8OffsetOperands(Inst, N);
2315   }
2316 
2317   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2318     assert(N == 2 && "Invalid number of operands!");
2319     // If this is an immediate, it's a label reference.
2320     if (isImm()) {
2321       addExpr(Inst, getImm());
2322       Inst.addOperand(MCOperand::createImm(0));
2323       return;
2324     }
2325 
2326     // Otherwise, it's a normal memory reg+offset.
2327     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2328     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2329     Inst.addOperand(MCOperand::createImm(Val));
2330   }
2331 
2332   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2333     assert(N == 2 && "Invalid number of operands!");
2334     // If this is an immediate, it's a label reference.
2335     if (isImm()) {
2336       addExpr(Inst, getImm());
2337       Inst.addOperand(MCOperand::createImm(0));
2338       return;
2339     }
2340 
2341     // Otherwise, it's a normal memory reg+offset.
2342     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2343     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2344     Inst.addOperand(MCOperand::createImm(Val));
2345   }
2346 
2347   void addConstPoolAsmImmOperands(MCInst &Inst, unsigned N) const {
2348     assert(N == 1 && "Invalid number of operands!");
2349     // This is container for the immediate that we will create the constant
2350     // pool from
2351     addExpr(Inst, getConstantPoolImm());
2352     return;
2353   }
2354 
2355   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
2356     assert(N == 2 && "Invalid number of operands!");
2357     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2358     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2359   }
2360 
2361   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
2362     assert(N == 2 && "Invalid number of operands!");
2363     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2364     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2365   }
2366 
2367   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2368     assert(N == 3 && "Invalid number of operands!");
2369     unsigned Val =
2370       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2371                         Memory.ShiftImm, Memory.ShiftType);
2372     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2373     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2374     Inst.addOperand(MCOperand::createImm(Val));
2375   }
2376 
2377   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2378     assert(N == 3 && "Invalid number of operands!");
2379     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2380     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2381     Inst.addOperand(MCOperand::createImm(Memory.ShiftImm));
2382   }
2383 
2384   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
2385     assert(N == 2 && "Invalid number of operands!");
2386     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2387     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2388   }
2389 
2390   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
2391     assert(N == 2 && "Invalid number of operands!");
2392     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2393     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2394     Inst.addOperand(MCOperand::createImm(Val));
2395   }
2396 
2397   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
2398     assert(N == 2 && "Invalid number of operands!");
2399     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
2400     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2401     Inst.addOperand(MCOperand::createImm(Val));
2402   }
2403 
2404   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
2405     assert(N == 2 && "Invalid number of operands!");
2406     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
2407     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2408     Inst.addOperand(MCOperand::createImm(Val));
2409   }
2410 
2411   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
2412     assert(N == 2 && "Invalid number of operands!");
2413     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2414     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2415     Inst.addOperand(MCOperand::createImm(Val));
2416   }
2417 
2418   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
2419     assert(N == 1 && "Invalid number of operands!");
2420     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2421     assert(CE && "non-constant post-idx-imm8 operand!");
2422     int Imm = CE->getValue();
2423     bool isAdd = Imm >= 0;
2424     if (Imm == INT32_MIN) Imm = 0;
2425     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
2426     Inst.addOperand(MCOperand::createImm(Imm));
2427   }
2428 
2429   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
2430     assert(N == 1 && "Invalid number of operands!");
2431     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2432     assert(CE && "non-constant post-idx-imm8s4 operand!");
2433     int Imm = CE->getValue();
2434     bool isAdd = Imm >= 0;
2435     if (Imm == INT32_MIN) Imm = 0;
2436     // Immediate is scaled by 4.
2437     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
2438     Inst.addOperand(MCOperand::createImm(Imm));
2439   }
2440 
2441   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
2442     assert(N == 2 && "Invalid number of operands!");
2443     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2444     Inst.addOperand(MCOperand::createImm(PostIdxReg.isAdd));
2445   }
2446 
2447   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
2448     assert(N == 2 && "Invalid number of operands!");
2449     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2450     // The sign, shift type, and shift amount are encoded in a single operand
2451     // using the AM2 encoding helpers.
2452     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
2453     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
2454                                      PostIdxReg.ShiftTy);
2455     Inst.addOperand(MCOperand::createImm(Imm));
2456   }
2457 
2458   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
2459     assert(N == 1 && "Invalid number of operands!");
2460     Inst.addOperand(MCOperand::createImm(unsigned(getMSRMask())));
2461   }
2462 
2463   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
2464     assert(N == 1 && "Invalid number of operands!");
2465     Inst.addOperand(MCOperand::createImm(unsigned(getBankedReg())));
2466   }
2467 
2468   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
2469     assert(N == 1 && "Invalid number of operands!");
2470     Inst.addOperand(MCOperand::createImm(unsigned(getProcIFlags())));
2471   }
2472 
2473   void addVecListOperands(MCInst &Inst, unsigned N) const {
2474     assert(N == 1 && "Invalid number of operands!");
2475     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2476   }
2477 
2478   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
2479     assert(N == 2 && "Invalid number of operands!");
2480     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2481     Inst.addOperand(MCOperand::createImm(VectorList.LaneIndex));
2482   }
2483 
2484   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
2485     assert(N == 1 && "Invalid number of operands!");
2486     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2487   }
2488 
2489   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
2490     assert(N == 1 && "Invalid number of operands!");
2491     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2492   }
2493 
2494   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
2495     assert(N == 1 && "Invalid number of operands!");
2496     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2497   }
2498 
2499   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
2500     assert(N == 1 && "Invalid number of operands!");
2501     // The immediate encodes the type of constant as well as the value.
2502     // Mask in that this is an i8 splat.
2503     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2504     Inst.addOperand(MCOperand::createImm(CE->getValue() | 0xe00));
2505   }
2506 
2507   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
2508     assert(N == 1 && "Invalid number of operands!");
2509     // The immediate encodes the type of constant as well as the value.
2510     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2511     unsigned Value = CE->getValue();
2512     Value = ARM_AM::encodeNEONi16splat(Value);
2513     Inst.addOperand(MCOperand::createImm(Value));
2514   }
2515 
2516   void addNEONi16splatNotOperands(MCInst &Inst, unsigned N) const {
2517     assert(N == 1 && "Invalid number of operands!");
2518     // The immediate encodes the type of constant as well as the value.
2519     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2520     unsigned Value = CE->getValue();
2521     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
2522     Inst.addOperand(MCOperand::createImm(Value));
2523   }
2524 
2525   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
2526     assert(N == 1 && "Invalid number of operands!");
2527     // The immediate encodes the type of constant as well as the value.
2528     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2529     unsigned Value = CE->getValue();
2530     Value = ARM_AM::encodeNEONi32splat(Value);
2531     Inst.addOperand(MCOperand::createImm(Value));
2532   }
2533 
2534   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
2535     assert(N == 1 && "Invalid number of operands!");
2536     // The immediate encodes the type of constant as well as the value.
2537     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2538     unsigned Value = CE->getValue();
2539     Value = ARM_AM::encodeNEONi32splat(~Value);
2540     Inst.addOperand(MCOperand::createImm(Value));
2541   }
2542 
2543   void addNEONinvByteReplicateOperands(MCInst &Inst, unsigned N) const {
2544     assert(N == 1 && "Invalid number of operands!");
2545     // The immediate encodes the type of constant as well as the value.
2546     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2547     unsigned Value = CE->getValue();
2548     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2549             Inst.getOpcode() == ARM::VMOVv16i8) &&
2550            "All vmvn instructions that wants to replicate non-zero byte "
2551            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2552     unsigned B = ((~Value) & 0xff);
2553     B |= 0xe00; // cmode = 0b1110
2554     Inst.addOperand(MCOperand::createImm(B));
2555   }
2556   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
2557     assert(N == 1 && "Invalid number of operands!");
2558     // The immediate encodes the type of constant as well as the value.
2559     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2560     unsigned Value = CE->getValue();
2561     if (Value >= 256 && Value <= 0xffff)
2562       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2563     else if (Value > 0xffff && Value <= 0xffffff)
2564       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2565     else if (Value > 0xffffff)
2566       Value = (Value >> 24) | 0x600;
2567     Inst.addOperand(MCOperand::createImm(Value));
2568   }
2569 
2570   void addNEONvmovByteReplicateOperands(MCInst &Inst, unsigned N) const {
2571     assert(N == 1 && "Invalid number of operands!");
2572     // The immediate encodes the type of constant as well as the value.
2573     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2574     unsigned Value = CE->getValue();
2575     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2576             Inst.getOpcode() == ARM::VMOVv16i8) &&
2577            "All instructions that wants to replicate non-zero byte "
2578            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2579     unsigned B = Value & 0xff;
2580     B |= 0xe00; // cmode = 0b1110
2581     Inst.addOperand(MCOperand::createImm(B));
2582   }
2583   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
2584     assert(N == 1 && "Invalid number of operands!");
2585     // The immediate encodes the type of constant as well as the value.
2586     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2587     unsigned Value = ~CE->getValue();
2588     if (Value >= 256 && Value <= 0xffff)
2589       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2590     else if (Value > 0xffff && Value <= 0xffffff)
2591       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2592     else if (Value > 0xffffff)
2593       Value = (Value >> 24) | 0x600;
2594     Inst.addOperand(MCOperand::createImm(Value));
2595   }
2596 
2597   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
2598     assert(N == 1 && "Invalid number of operands!");
2599     // The immediate encodes the type of constant as well as the value.
2600     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2601     uint64_t Value = CE->getValue();
2602     unsigned Imm = 0;
2603     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
2604       Imm |= (Value & 1) << i;
2605     }
2606     Inst.addOperand(MCOperand::createImm(Imm | 0x1e00));
2607   }
2608 
2609   void print(raw_ostream &OS) const override;
2610 
2611   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
2612     auto Op = make_unique<ARMOperand>(k_ITCondMask);
2613     Op->ITMask.Mask = Mask;
2614     Op->StartLoc = S;
2615     Op->EndLoc = S;
2616     return Op;
2617   }
2618 
2619   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
2620                                                     SMLoc S) {
2621     auto Op = make_unique<ARMOperand>(k_CondCode);
2622     Op->CC.Val = CC;
2623     Op->StartLoc = S;
2624     Op->EndLoc = S;
2625     return Op;
2626   }
2627 
2628   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
2629     auto Op = make_unique<ARMOperand>(k_CoprocNum);
2630     Op->Cop.Val = CopVal;
2631     Op->StartLoc = S;
2632     Op->EndLoc = S;
2633     return Op;
2634   }
2635 
2636   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
2637     auto Op = make_unique<ARMOperand>(k_CoprocReg);
2638     Op->Cop.Val = CopVal;
2639     Op->StartLoc = S;
2640     Op->EndLoc = S;
2641     return Op;
2642   }
2643 
2644   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
2645                                                         SMLoc E) {
2646     auto Op = make_unique<ARMOperand>(k_CoprocOption);
2647     Op->Cop.Val = Val;
2648     Op->StartLoc = S;
2649     Op->EndLoc = E;
2650     return Op;
2651   }
2652 
2653   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
2654     auto Op = make_unique<ARMOperand>(k_CCOut);
2655     Op->Reg.RegNum = RegNum;
2656     Op->StartLoc = S;
2657     Op->EndLoc = S;
2658     return Op;
2659   }
2660 
2661   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
2662     auto Op = make_unique<ARMOperand>(k_Token);
2663     Op->Tok.Data = Str.data();
2664     Op->Tok.Length = Str.size();
2665     Op->StartLoc = S;
2666     Op->EndLoc = S;
2667     return Op;
2668   }
2669 
2670   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
2671                                                SMLoc E) {
2672     auto Op = make_unique<ARMOperand>(k_Register);
2673     Op->Reg.RegNum = RegNum;
2674     Op->StartLoc = S;
2675     Op->EndLoc = E;
2676     return Op;
2677   }
2678 
2679   static std::unique_ptr<ARMOperand>
2680   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2681                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
2682                         SMLoc E) {
2683     auto Op = make_unique<ARMOperand>(k_ShiftedRegister);
2684     Op->RegShiftedReg.ShiftTy = ShTy;
2685     Op->RegShiftedReg.SrcReg = SrcReg;
2686     Op->RegShiftedReg.ShiftReg = ShiftReg;
2687     Op->RegShiftedReg.ShiftImm = ShiftImm;
2688     Op->StartLoc = S;
2689     Op->EndLoc = E;
2690     return Op;
2691   }
2692 
2693   static std::unique_ptr<ARMOperand>
2694   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2695                          unsigned ShiftImm, SMLoc S, SMLoc E) {
2696     auto Op = make_unique<ARMOperand>(k_ShiftedImmediate);
2697     Op->RegShiftedImm.ShiftTy = ShTy;
2698     Op->RegShiftedImm.SrcReg = SrcReg;
2699     Op->RegShiftedImm.ShiftImm = ShiftImm;
2700     Op->StartLoc = S;
2701     Op->EndLoc = E;
2702     return Op;
2703   }
2704 
2705   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
2706                                                       SMLoc S, SMLoc E) {
2707     auto Op = make_unique<ARMOperand>(k_ShifterImmediate);
2708     Op->ShifterImm.isASR = isASR;
2709     Op->ShifterImm.Imm = Imm;
2710     Op->StartLoc = S;
2711     Op->EndLoc = E;
2712     return Op;
2713   }
2714 
2715   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
2716                                                   SMLoc E) {
2717     auto Op = make_unique<ARMOperand>(k_RotateImmediate);
2718     Op->RotImm.Imm = Imm;
2719     Op->StartLoc = S;
2720     Op->EndLoc = E;
2721     return Op;
2722   }
2723 
2724   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
2725                                                   SMLoc S, SMLoc E) {
2726     auto Op = make_unique<ARMOperand>(k_ModifiedImmediate);
2727     Op->ModImm.Bits = Bits;
2728     Op->ModImm.Rot = Rot;
2729     Op->StartLoc = S;
2730     Op->EndLoc = E;
2731     return Op;
2732   }
2733 
2734   static std::unique_ptr<ARMOperand>
2735   CreateConstantPoolImm(const MCExpr *Val, SMLoc S, SMLoc E) {
2736     auto Op = make_unique<ARMOperand>(k_ConstantPoolImmediate);
2737     Op->Imm.Val = Val;
2738     Op->StartLoc = S;
2739     Op->EndLoc = E;
2740     return Op;
2741   }
2742 
2743   static std::unique_ptr<ARMOperand>
2744   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
2745     auto Op = make_unique<ARMOperand>(k_BitfieldDescriptor);
2746     Op->Bitfield.LSB = LSB;
2747     Op->Bitfield.Width = Width;
2748     Op->StartLoc = S;
2749     Op->EndLoc = E;
2750     return Op;
2751   }
2752 
2753   static std::unique_ptr<ARMOperand>
2754   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
2755                 SMLoc StartLoc, SMLoc EndLoc) {
2756     assert (Regs.size() > 0 && "RegList contains no registers?");
2757     KindTy Kind = k_RegisterList;
2758 
2759     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Regs.front().second))
2760       Kind = k_DPRRegisterList;
2761     else if (ARMMCRegisterClasses[ARM::SPRRegClassID].
2762              contains(Regs.front().second))
2763       Kind = k_SPRRegisterList;
2764 
2765     // Sort based on the register encoding values.
2766     array_pod_sort(Regs.begin(), Regs.end());
2767 
2768     auto Op = make_unique<ARMOperand>(Kind);
2769     for (SmallVectorImpl<std::pair<unsigned, unsigned> >::const_iterator
2770            I = Regs.begin(), E = Regs.end(); I != E; ++I)
2771       Op->Registers.push_back(I->second);
2772     Op->StartLoc = StartLoc;
2773     Op->EndLoc = EndLoc;
2774     return Op;
2775   }
2776 
2777   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
2778                                                       unsigned Count,
2779                                                       bool isDoubleSpaced,
2780                                                       SMLoc S, SMLoc E) {
2781     auto Op = make_unique<ARMOperand>(k_VectorList);
2782     Op->VectorList.RegNum = RegNum;
2783     Op->VectorList.Count = Count;
2784     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2785     Op->StartLoc = S;
2786     Op->EndLoc = E;
2787     return Op;
2788   }
2789 
2790   static std::unique_ptr<ARMOperand>
2791   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
2792                            SMLoc S, SMLoc E) {
2793     auto Op = make_unique<ARMOperand>(k_VectorListAllLanes);
2794     Op->VectorList.RegNum = RegNum;
2795     Op->VectorList.Count = Count;
2796     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2797     Op->StartLoc = S;
2798     Op->EndLoc = E;
2799     return Op;
2800   }
2801 
2802   static std::unique_ptr<ARMOperand>
2803   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
2804                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
2805     auto Op = make_unique<ARMOperand>(k_VectorListIndexed);
2806     Op->VectorList.RegNum = RegNum;
2807     Op->VectorList.Count = Count;
2808     Op->VectorList.LaneIndex = Index;
2809     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2810     Op->StartLoc = S;
2811     Op->EndLoc = E;
2812     return Op;
2813   }
2814 
2815   static std::unique_ptr<ARMOperand>
2816   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
2817     auto Op = make_unique<ARMOperand>(k_VectorIndex);
2818     Op->VectorIndex.Val = Idx;
2819     Op->StartLoc = S;
2820     Op->EndLoc = E;
2821     return Op;
2822   }
2823 
2824   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
2825                                                SMLoc E) {
2826     auto Op = make_unique<ARMOperand>(k_Immediate);
2827     Op->Imm.Val = Val;
2828     Op->StartLoc = S;
2829     Op->EndLoc = E;
2830     return Op;
2831   }
2832 
2833   static std::unique_ptr<ARMOperand>
2834   CreateMem(unsigned BaseRegNum, const MCConstantExpr *OffsetImm,
2835             unsigned OffsetRegNum, ARM_AM::ShiftOpc ShiftType,
2836             unsigned ShiftImm, unsigned Alignment, bool isNegative, SMLoc S,
2837             SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
2838     auto Op = make_unique<ARMOperand>(k_Memory);
2839     Op->Memory.BaseRegNum = BaseRegNum;
2840     Op->Memory.OffsetImm = OffsetImm;
2841     Op->Memory.OffsetRegNum = OffsetRegNum;
2842     Op->Memory.ShiftType = ShiftType;
2843     Op->Memory.ShiftImm = ShiftImm;
2844     Op->Memory.Alignment = Alignment;
2845     Op->Memory.isNegative = isNegative;
2846     Op->StartLoc = S;
2847     Op->EndLoc = E;
2848     Op->AlignmentLoc = AlignmentLoc;
2849     return Op;
2850   }
2851 
2852   static std::unique_ptr<ARMOperand>
2853   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
2854                    unsigned ShiftImm, SMLoc S, SMLoc E) {
2855     auto Op = make_unique<ARMOperand>(k_PostIndexRegister);
2856     Op->PostIdxReg.RegNum = RegNum;
2857     Op->PostIdxReg.isAdd = isAdd;
2858     Op->PostIdxReg.ShiftTy = ShiftTy;
2859     Op->PostIdxReg.ShiftImm = ShiftImm;
2860     Op->StartLoc = S;
2861     Op->EndLoc = E;
2862     return Op;
2863   }
2864 
2865   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
2866                                                          SMLoc S) {
2867     auto Op = make_unique<ARMOperand>(k_MemBarrierOpt);
2868     Op->MBOpt.Val = Opt;
2869     Op->StartLoc = S;
2870     Op->EndLoc = S;
2871     return Op;
2872   }
2873 
2874   static std::unique_ptr<ARMOperand>
2875   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
2876     auto Op = make_unique<ARMOperand>(k_InstSyncBarrierOpt);
2877     Op->ISBOpt.Val = Opt;
2878     Op->StartLoc = S;
2879     Op->EndLoc = S;
2880     return Op;
2881   }
2882 
2883   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
2884                                                       SMLoc S) {
2885     auto Op = make_unique<ARMOperand>(k_ProcIFlags);
2886     Op->IFlags.Val = IFlags;
2887     Op->StartLoc = S;
2888     Op->EndLoc = S;
2889     return Op;
2890   }
2891 
2892   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
2893     auto Op = make_unique<ARMOperand>(k_MSRMask);
2894     Op->MMask.Val = MMask;
2895     Op->StartLoc = S;
2896     Op->EndLoc = S;
2897     return Op;
2898   }
2899 
2900   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
2901     auto Op = make_unique<ARMOperand>(k_BankedReg);
2902     Op->BankedReg.Val = Reg;
2903     Op->StartLoc = S;
2904     Op->EndLoc = S;
2905     return Op;
2906   }
2907 };
2908 
2909 } // end anonymous namespace.
2910 
2911 void ARMOperand::print(raw_ostream &OS) const {
2912   switch (Kind) {
2913   case k_CondCode:
2914     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
2915     break;
2916   case k_CCOut:
2917     OS << "<ccout " << getReg() << ">";
2918     break;
2919   case k_ITCondMask: {
2920     static const char *const MaskStr[] = {
2921       "()", "(t)", "(e)", "(tt)", "(et)", "(te)", "(ee)", "(ttt)", "(ett)",
2922       "(tet)", "(eet)", "(tte)", "(ete)", "(tee)", "(eee)"
2923     };
2924     assert((ITMask.Mask & 0xf) == ITMask.Mask);
2925     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
2926     break;
2927   }
2928   case k_CoprocNum:
2929     OS << "<coprocessor number: " << getCoproc() << ">";
2930     break;
2931   case k_CoprocReg:
2932     OS << "<coprocessor register: " << getCoproc() << ">";
2933     break;
2934   case k_CoprocOption:
2935     OS << "<coprocessor option: " << CoprocOption.Val << ">";
2936     break;
2937   case k_MSRMask:
2938     OS << "<mask: " << getMSRMask() << ">";
2939     break;
2940   case k_BankedReg:
2941     OS << "<banked reg: " << getBankedReg() << ">";
2942     break;
2943   case k_Immediate:
2944     OS << *getImm();
2945     break;
2946   case k_MemBarrierOpt:
2947     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
2948     break;
2949   case k_InstSyncBarrierOpt:
2950     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
2951     break;
2952   case k_Memory:
2953     OS << "<memory "
2954        << " base:" << Memory.BaseRegNum;
2955     OS << ">";
2956     break;
2957   case k_PostIndexRegister:
2958     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
2959        << PostIdxReg.RegNum;
2960     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
2961       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
2962          << PostIdxReg.ShiftImm;
2963     OS << ">";
2964     break;
2965   case k_ProcIFlags: {
2966     OS << "<ARM_PROC::";
2967     unsigned IFlags = getProcIFlags();
2968     for (int i=2; i >= 0; --i)
2969       if (IFlags & (1 << i))
2970         OS << ARM_PROC::IFlagsToString(1 << i);
2971     OS << ">";
2972     break;
2973   }
2974   case k_Register:
2975     OS << "<register " << getReg() << ">";
2976     break;
2977   case k_ShifterImmediate:
2978     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
2979        << " #" << ShifterImm.Imm << ">";
2980     break;
2981   case k_ShiftedRegister:
2982     OS << "<so_reg_reg "
2983        << RegShiftedReg.SrcReg << " "
2984        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy)
2985        << " " << RegShiftedReg.ShiftReg << ">";
2986     break;
2987   case k_ShiftedImmediate:
2988     OS << "<so_reg_imm "
2989        << RegShiftedImm.SrcReg << " "
2990        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy)
2991        << " #" << RegShiftedImm.ShiftImm << ">";
2992     break;
2993   case k_RotateImmediate:
2994     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
2995     break;
2996   case k_ModifiedImmediate:
2997     OS << "<mod_imm #" << ModImm.Bits << ", #"
2998        <<  ModImm.Rot << ")>";
2999     break;
3000   case k_ConstantPoolImmediate:
3001     OS << "<constant_pool_imm #" << *getConstantPoolImm();
3002     break;
3003   case k_BitfieldDescriptor:
3004     OS << "<bitfield " << "lsb: " << Bitfield.LSB
3005        << ", width: " << Bitfield.Width << ">";
3006     break;
3007   case k_RegisterList:
3008   case k_DPRRegisterList:
3009   case k_SPRRegisterList: {
3010     OS << "<register_list ";
3011 
3012     const SmallVectorImpl<unsigned> &RegList = getRegList();
3013     for (SmallVectorImpl<unsigned>::const_iterator
3014            I = RegList.begin(), E = RegList.end(); I != E; ) {
3015       OS << *I;
3016       if (++I < E) OS << ", ";
3017     }
3018 
3019     OS << ">";
3020     break;
3021   }
3022   case k_VectorList:
3023     OS << "<vector_list " << VectorList.Count << " * "
3024        << VectorList.RegNum << ">";
3025     break;
3026   case k_VectorListAllLanes:
3027     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
3028        << VectorList.RegNum << ">";
3029     break;
3030   case k_VectorListIndexed:
3031     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
3032        << VectorList.Count << " * " << VectorList.RegNum << ">";
3033     break;
3034   case k_Token:
3035     OS << "'" << getToken() << "'";
3036     break;
3037   case k_VectorIndex:
3038     OS << "<vectorindex " << getVectorIndex() << ">";
3039     break;
3040   }
3041 }
3042 
3043 /// @name Auto-generated Match Functions
3044 /// {
3045 
3046 static unsigned MatchRegisterName(StringRef Name);
3047 
3048 /// }
3049 
3050 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
3051                                  SMLoc &StartLoc, SMLoc &EndLoc) {
3052   const AsmToken &Tok = getParser().getTok();
3053   StartLoc = Tok.getLoc();
3054   EndLoc = Tok.getEndLoc();
3055   RegNo = tryParseRegister();
3056 
3057   return (RegNo == (unsigned)-1);
3058 }
3059 
3060 /// Try to parse a register name.  The token must be an Identifier when called,
3061 /// and if it is a register name the token is eaten and the register number is
3062 /// returned.  Otherwise return -1.
3063 ///
3064 int ARMAsmParser::tryParseRegister() {
3065   MCAsmParser &Parser = getParser();
3066   const AsmToken &Tok = Parser.getTok();
3067   if (Tok.isNot(AsmToken::Identifier)) return -1;
3068 
3069   std::string lowerCase = Tok.getString().lower();
3070   unsigned RegNum = MatchRegisterName(lowerCase);
3071   if (!RegNum) {
3072     RegNum = StringSwitch<unsigned>(lowerCase)
3073       .Case("r13", ARM::SP)
3074       .Case("r14", ARM::LR)
3075       .Case("r15", ARM::PC)
3076       .Case("ip", ARM::R12)
3077       // Additional register name aliases for 'gas' compatibility.
3078       .Case("a1", ARM::R0)
3079       .Case("a2", ARM::R1)
3080       .Case("a3", ARM::R2)
3081       .Case("a4", ARM::R3)
3082       .Case("v1", ARM::R4)
3083       .Case("v2", ARM::R5)
3084       .Case("v3", ARM::R6)
3085       .Case("v4", ARM::R7)
3086       .Case("v5", ARM::R8)
3087       .Case("v6", ARM::R9)
3088       .Case("v7", ARM::R10)
3089       .Case("v8", ARM::R11)
3090       .Case("sb", ARM::R9)
3091       .Case("sl", ARM::R10)
3092       .Case("fp", ARM::R11)
3093       .Default(0);
3094   }
3095   if (!RegNum) {
3096     // Check for aliases registered via .req. Canonicalize to lower case.
3097     // That's more consistent since register names are case insensitive, and
3098     // it's how the original entry was passed in from MC/MCParser/AsmParser.
3099     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
3100     // If no match, return failure.
3101     if (Entry == RegisterReqs.end())
3102       return -1;
3103     Parser.Lex(); // Eat identifier token.
3104     return Entry->getValue();
3105   }
3106 
3107   // Some FPUs only have 16 D registers, so D16-D31 are invalid
3108   if (hasD16() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
3109     return -1;
3110 
3111   Parser.Lex(); // Eat identifier token.
3112 
3113   return RegNum;
3114 }
3115 
3116 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
3117 // If a recoverable error occurs, return 1. If an irrecoverable error
3118 // occurs, return -1. An irrecoverable error is one where tokens have been
3119 // consumed in the process of trying to parse the shifter (i.e., when it is
3120 // indeed a shifter operand, but malformed).
3121 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
3122   MCAsmParser &Parser = getParser();
3123   SMLoc S = Parser.getTok().getLoc();
3124   const AsmToken &Tok = Parser.getTok();
3125   if (Tok.isNot(AsmToken::Identifier))
3126     return -1;
3127 
3128   std::string lowerCase = Tok.getString().lower();
3129   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
3130       .Case("asl", ARM_AM::lsl)
3131       .Case("lsl", ARM_AM::lsl)
3132       .Case("lsr", ARM_AM::lsr)
3133       .Case("asr", ARM_AM::asr)
3134       .Case("ror", ARM_AM::ror)
3135       .Case("rrx", ARM_AM::rrx)
3136       .Default(ARM_AM::no_shift);
3137 
3138   if (ShiftTy == ARM_AM::no_shift)
3139     return 1;
3140 
3141   Parser.Lex(); // Eat the operator.
3142 
3143   // The source register for the shift has already been added to the
3144   // operand list, so we need to pop it off and combine it into the shifted
3145   // register operand instead.
3146   std::unique_ptr<ARMOperand> PrevOp(
3147       (ARMOperand *)Operands.pop_back_val().release());
3148   if (!PrevOp->isReg())
3149     return Error(PrevOp->getStartLoc(), "shift must be of a register");
3150   int SrcReg = PrevOp->getReg();
3151 
3152   SMLoc EndLoc;
3153   int64_t Imm = 0;
3154   int ShiftReg = 0;
3155   if (ShiftTy == ARM_AM::rrx) {
3156     // RRX Doesn't have an explicit shift amount. The encoder expects
3157     // the shift register to be the same as the source register. Seems odd,
3158     // but OK.
3159     ShiftReg = SrcReg;
3160   } else {
3161     // Figure out if this is shifted by a constant or a register (for non-RRX).
3162     if (Parser.getTok().is(AsmToken::Hash) ||
3163         Parser.getTok().is(AsmToken::Dollar)) {
3164       Parser.Lex(); // Eat hash.
3165       SMLoc ImmLoc = Parser.getTok().getLoc();
3166       const MCExpr *ShiftExpr = nullptr;
3167       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
3168         Error(ImmLoc, "invalid immediate shift value");
3169         return -1;
3170       }
3171       // The expression must be evaluatable as an immediate.
3172       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
3173       if (!CE) {
3174         Error(ImmLoc, "invalid immediate shift value");
3175         return -1;
3176       }
3177       // Range check the immediate.
3178       // lsl, ror: 0 <= imm <= 31
3179       // lsr, asr: 0 <= imm <= 32
3180       Imm = CE->getValue();
3181       if (Imm < 0 ||
3182           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
3183           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
3184         Error(ImmLoc, "immediate shift value out of range");
3185         return -1;
3186       }
3187       // shift by zero is a nop. Always send it through as lsl.
3188       // ('as' compatibility)
3189       if (Imm == 0)
3190         ShiftTy = ARM_AM::lsl;
3191     } else if (Parser.getTok().is(AsmToken::Identifier)) {
3192       SMLoc L = Parser.getTok().getLoc();
3193       EndLoc = Parser.getTok().getEndLoc();
3194       ShiftReg = tryParseRegister();
3195       if (ShiftReg == -1) {
3196         Error(L, "expected immediate or register in shift operand");
3197         return -1;
3198       }
3199     } else {
3200       Error(Parser.getTok().getLoc(),
3201             "expected immediate or register in shift operand");
3202       return -1;
3203     }
3204   }
3205 
3206   if (ShiftReg && ShiftTy != ARM_AM::rrx)
3207     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
3208                                                          ShiftReg, Imm,
3209                                                          S, EndLoc));
3210   else
3211     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
3212                                                           S, EndLoc));
3213 
3214   return 0;
3215 }
3216 
3217 
3218 /// Try to parse a register name.  The token must be an Identifier when called.
3219 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
3220 /// if there is a "writeback". 'true' if it's not a register.
3221 ///
3222 /// TODO this is likely to change to allow different register types and or to
3223 /// parse for a specific register type.
3224 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
3225   MCAsmParser &Parser = getParser();
3226   const AsmToken &RegTok = Parser.getTok();
3227   int RegNo = tryParseRegister();
3228   if (RegNo == -1)
3229     return true;
3230 
3231   Operands.push_back(ARMOperand::CreateReg(RegNo, RegTok.getLoc(),
3232                                            RegTok.getEndLoc()));
3233 
3234   const AsmToken &ExclaimTok = Parser.getTok();
3235   if (ExclaimTok.is(AsmToken::Exclaim)) {
3236     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
3237                                                ExclaimTok.getLoc()));
3238     Parser.Lex(); // Eat exclaim token
3239     return false;
3240   }
3241 
3242   // Also check for an index operand. This is only legal for vector registers,
3243   // but that'll get caught OK in operand matching, so we don't need to
3244   // explicitly filter everything else out here.
3245   if (Parser.getTok().is(AsmToken::LBrac)) {
3246     SMLoc SIdx = Parser.getTok().getLoc();
3247     Parser.Lex(); // Eat left bracket token.
3248 
3249     const MCExpr *ImmVal;
3250     if (getParser().parseExpression(ImmVal))
3251       return true;
3252     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
3253     if (!MCE)
3254       return TokError("immediate value expected for vector index");
3255 
3256     if (Parser.getTok().isNot(AsmToken::RBrac))
3257       return Error(Parser.getTok().getLoc(), "']' expected");
3258 
3259     SMLoc E = Parser.getTok().getEndLoc();
3260     Parser.Lex(); // Eat right bracket token.
3261 
3262     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
3263                                                      SIdx, E,
3264                                                      getContext()));
3265   }
3266 
3267   return false;
3268 }
3269 
3270 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
3271 /// instruction with a symbolic operand name.
3272 /// We accept "crN" syntax for GAS compatibility.
3273 /// <operand-name> ::= <prefix><number>
3274 /// If CoprocOp is 'c', then:
3275 ///   <prefix> ::= c | cr
3276 /// If CoprocOp is 'p', then :
3277 ///   <prefix> ::= p
3278 /// <number> ::= integer in range [0, 15]
3279 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
3280   // Use the same layout as the tablegen'erated register name matcher. Ugly,
3281   // but efficient.
3282   if (Name.size() < 2 || Name[0] != CoprocOp)
3283     return -1;
3284   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
3285 
3286   switch (Name.size()) {
3287   default: return -1;
3288   case 1:
3289     switch (Name[0]) {
3290     default:  return -1;
3291     case '0': return 0;
3292     case '1': return 1;
3293     case '2': return 2;
3294     case '3': return 3;
3295     case '4': return 4;
3296     case '5': return 5;
3297     case '6': return 6;
3298     case '7': return 7;
3299     case '8': return 8;
3300     case '9': return 9;
3301     }
3302   case 2:
3303     if (Name[0] != '1')
3304       return -1;
3305     switch (Name[1]) {
3306     default:  return -1;
3307     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
3308     // However, old cores (v5/v6) did use them in that way.
3309     case '0': return 10;
3310     case '1': return 11;
3311     case '2': return 12;
3312     case '3': return 13;
3313     case '4': return 14;
3314     case '5': return 15;
3315     }
3316   }
3317 }
3318 
3319 /// parseITCondCode - Try to parse a condition code for an IT instruction.
3320 OperandMatchResultTy
3321 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
3322   MCAsmParser &Parser = getParser();
3323   SMLoc S = Parser.getTok().getLoc();
3324   const AsmToken &Tok = Parser.getTok();
3325   if (!Tok.is(AsmToken::Identifier))
3326     return MatchOperand_NoMatch;
3327   unsigned CC = StringSwitch<unsigned>(Tok.getString().lower())
3328     .Case("eq", ARMCC::EQ)
3329     .Case("ne", ARMCC::NE)
3330     .Case("hs", ARMCC::HS)
3331     .Case("cs", ARMCC::HS)
3332     .Case("lo", ARMCC::LO)
3333     .Case("cc", ARMCC::LO)
3334     .Case("mi", ARMCC::MI)
3335     .Case("pl", ARMCC::PL)
3336     .Case("vs", ARMCC::VS)
3337     .Case("vc", ARMCC::VC)
3338     .Case("hi", ARMCC::HI)
3339     .Case("ls", ARMCC::LS)
3340     .Case("ge", ARMCC::GE)
3341     .Case("lt", ARMCC::LT)
3342     .Case("gt", ARMCC::GT)
3343     .Case("le", ARMCC::LE)
3344     .Case("al", ARMCC::AL)
3345     .Default(~0U);
3346   if (CC == ~0U)
3347     return MatchOperand_NoMatch;
3348   Parser.Lex(); // Eat the token.
3349 
3350   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
3351 
3352   return MatchOperand_Success;
3353 }
3354 
3355 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
3356 /// token must be an Identifier when called, and if it is a coprocessor
3357 /// number, the token is eaten and the operand is added to the operand list.
3358 OperandMatchResultTy
3359 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
3360   MCAsmParser &Parser = getParser();
3361   SMLoc S = Parser.getTok().getLoc();
3362   const AsmToken &Tok = Parser.getTok();
3363   if (Tok.isNot(AsmToken::Identifier))
3364     return MatchOperand_NoMatch;
3365 
3366   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
3367   if (Num == -1)
3368     return MatchOperand_NoMatch;
3369   // ARMv7 and v8 don't allow cp10/cp11 due to VFP/NEON specific instructions
3370   if ((hasV7Ops() || hasV8Ops()) && (Num == 10 || Num == 11))
3371     return MatchOperand_NoMatch;
3372 
3373   Parser.Lex(); // Eat identifier token.
3374   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
3375   return MatchOperand_Success;
3376 }
3377 
3378 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
3379 /// token must be an Identifier when called, and if it is a coprocessor
3380 /// number, the token is eaten and the operand is added to the operand list.
3381 OperandMatchResultTy
3382 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
3383   MCAsmParser &Parser = getParser();
3384   SMLoc S = Parser.getTok().getLoc();
3385   const AsmToken &Tok = Parser.getTok();
3386   if (Tok.isNot(AsmToken::Identifier))
3387     return MatchOperand_NoMatch;
3388 
3389   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
3390   if (Reg == -1)
3391     return MatchOperand_NoMatch;
3392 
3393   Parser.Lex(); // Eat identifier token.
3394   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
3395   return MatchOperand_Success;
3396 }
3397 
3398 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
3399 /// coproc_option : '{' imm0_255 '}'
3400 OperandMatchResultTy
3401 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
3402   MCAsmParser &Parser = getParser();
3403   SMLoc S = Parser.getTok().getLoc();
3404 
3405   // If this isn't a '{', this isn't a coprocessor immediate operand.
3406   if (Parser.getTok().isNot(AsmToken::LCurly))
3407     return MatchOperand_NoMatch;
3408   Parser.Lex(); // Eat the '{'
3409 
3410   const MCExpr *Expr;
3411   SMLoc Loc = Parser.getTok().getLoc();
3412   if (getParser().parseExpression(Expr)) {
3413     Error(Loc, "illegal expression");
3414     return MatchOperand_ParseFail;
3415   }
3416   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
3417   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
3418     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
3419     return MatchOperand_ParseFail;
3420   }
3421   int Val = CE->getValue();
3422 
3423   // Check for and consume the closing '}'
3424   if (Parser.getTok().isNot(AsmToken::RCurly))
3425     return MatchOperand_ParseFail;
3426   SMLoc E = Parser.getTok().getEndLoc();
3427   Parser.Lex(); // Eat the '}'
3428 
3429   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
3430   return MatchOperand_Success;
3431 }
3432 
3433 // For register list parsing, we need to map from raw GPR register numbering
3434 // to the enumeration values. The enumeration values aren't sorted by
3435 // register number due to our using "sp", "lr" and "pc" as canonical names.
3436 static unsigned getNextRegister(unsigned Reg) {
3437   // If this is a GPR, we need to do it manually, otherwise we can rely
3438   // on the sort ordering of the enumeration since the other reg-classes
3439   // are sane.
3440   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3441     return Reg + 1;
3442   switch(Reg) {
3443   default: llvm_unreachable("Invalid GPR number!");
3444   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
3445   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
3446   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
3447   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
3448   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
3449   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
3450   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
3451   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
3452   }
3453 }
3454 
3455 // Return the low-subreg of a given Q register.
3456 static unsigned getDRegFromQReg(unsigned QReg) {
3457   switch (QReg) {
3458   default: llvm_unreachable("expected a Q register!");
3459   case ARM::Q0:  return ARM::D0;
3460   case ARM::Q1:  return ARM::D2;
3461   case ARM::Q2:  return ARM::D4;
3462   case ARM::Q3:  return ARM::D6;
3463   case ARM::Q4:  return ARM::D8;
3464   case ARM::Q5:  return ARM::D10;
3465   case ARM::Q6:  return ARM::D12;
3466   case ARM::Q7:  return ARM::D14;
3467   case ARM::Q8:  return ARM::D16;
3468   case ARM::Q9:  return ARM::D18;
3469   case ARM::Q10: return ARM::D20;
3470   case ARM::Q11: return ARM::D22;
3471   case ARM::Q12: return ARM::D24;
3472   case ARM::Q13: return ARM::D26;
3473   case ARM::Q14: return ARM::D28;
3474   case ARM::Q15: return ARM::D30;
3475   }
3476 }
3477 
3478 /// Parse a register list.
3479 bool ARMAsmParser::parseRegisterList(OperandVector &Operands) {
3480   MCAsmParser &Parser = getParser();
3481   if (Parser.getTok().isNot(AsmToken::LCurly))
3482     return TokError("Token is not a Left Curly Brace");
3483   SMLoc S = Parser.getTok().getLoc();
3484   Parser.Lex(); // Eat '{' token.
3485   SMLoc RegLoc = Parser.getTok().getLoc();
3486 
3487   // Check the first register in the list to see what register class
3488   // this is a list of.
3489   int Reg = tryParseRegister();
3490   if (Reg == -1)
3491     return Error(RegLoc, "register expected");
3492 
3493   // The reglist instructions have at most 16 registers, so reserve
3494   // space for that many.
3495   int EReg = 0;
3496   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
3497 
3498   // Allow Q regs and just interpret them as the two D sub-registers.
3499   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3500     Reg = getDRegFromQReg(Reg);
3501     EReg = MRI->getEncodingValue(Reg);
3502     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3503     ++Reg;
3504   }
3505   const MCRegisterClass *RC;
3506   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3507     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
3508   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
3509     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
3510   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
3511     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
3512   else
3513     return Error(RegLoc, "invalid register in register list");
3514 
3515   // Store the register.
3516   EReg = MRI->getEncodingValue(Reg);
3517   Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3518 
3519   // This starts immediately after the first register token in the list,
3520   // so we can see either a comma or a minus (range separator) as a legal
3521   // next token.
3522   while (Parser.getTok().is(AsmToken::Comma) ||
3523          Parser.getTok().is(AsmToken::Minus)) {
3524     if (Parser.getTok().is(AsmToken::Minus)) {
3525       Parser.Lex(); // Eat the minus.
3526       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3527       int EndReg = tryParseRegister();
3528       if (EndReg == -1)
3529         return Error(AfterMinusLoc, "register expected");
3530       // Allow Q regs and just interpret them as the two D sub-registers.
3531       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3532         EndReg = getDRegFromQReg(EndReg) + 1;
3533       // If the register is the same as the start reg, there's nothing
3534       // more to do.
3535       if (Reg == EndReg)
3536         continue;
3537       // The register must be in the same register class as the first.
3538       if (!RC->contains(EndReg))
3539         return Error(AfterMinusLoc, "invalid register in register list");
3540       // Ranges must go from low to high.
3541       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
3542         return Error(AfterMinusLoc, "bad range in register list");
3543 
3544       // Add all the registers in the range to the register list.
3545       while (Reg != EndReg) {
3546         Reg = getNextRegister(Reg);
3547         EReg = MRI->getEncodingValue(Reg);
3548         Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3549       }
3550       continue;
3551     }
3552     Parser.Lex(); // Eat the comma.
3553     RegLoc = Parser.getTok().getLoc();
3554     int OldReg = Reg;
3555     const AsmToken RegTok = Parser.getTok();
3556     Reg = tryParseRegister();
3557     if (Reg == -1)
3558       return Error(RegLoc, "register expected");
3559     // Allow Q regs and just interpret them as the two D sub-registers.
3560     bool isQReg = false;
3561     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3562       Reg = getDRegFromQReg(Reg);
3563       isQReg = true;
3564     }
3565     // The register must be in the same register class as the first.
3566     if (!RC->contains(Reg))
3567       return Error(RegLoc, "invalid register in register list");
3568     // List must be monotonically increasing.
3569     if (MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
3570       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3571         Warning(RegLoc, "register list not in ascending order");
3572       else
3573         return Error(RegLoc, "register list not in ascending order");
3574     }
3575     if (MRI->getEncodingValue(Reg) == MRI->getEncodingValue(OldReg)) {
3576       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
3577               ") in register list");
3578       continue;
3579     }
3580     // VFP register lists must also be contiguous.
3581     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
3582         Reg != OldReg + 1)
3583       return Error(RegLoc, "non-contiguous register range");
3584     EReg = MRI->getEncodingValue(Reg);
3585     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3586     if (isQReg) {
3587       EReg = MRI->getEncodingValue(++Reg);
3588       Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3589     }
3590   }
3591 
3592   if (Parser.getTok().isNot(AsmToken::RCurly))
3593     return Error(Parser.getTok().getLoc(), "'}' expected");
3594   SMLoc E = Parser.getTok().getEndLoc();
3595   Parser.Lex(); // Eat '}' token.
3596 
3597   // Push the register list operand.
3598   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
3599 
3600   // The ARM system instruction variants for LDM/STM have a '^' token here.
3601   if (Parser.getTok().is(AsmToken::Caret)) {
3602     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
3603     Parser.Lex(); // Eat '^' token.
3604   }
3605 
3606   return false;
3607 }
3608 
3609 // Helper function to parse the lane index for vector lists.
3610 OperandMatchResultTy ARMAsmParser::
3611 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
3612   MCAsmParser &Parser = getParser();
3613   Index = 0; // Always return a defined index value.
3614   if (Parser.getTok().is(AsmToken::LBrac)) {
3615     Parser.Lex(); // Eat the '['.
3616     if (Parser.getTok().is(AsmToken::RBrac)) {
3617       // "Dn[]" is the 'all lanes' syntax.
3618       LaneKind = AllLanes;
3619       EndLoc = Parser.getTok().getEndLoc();
3620       Parser.Lex(); // Eat the ']'.
3621       return MatchOperand_Success;
3622     }
3623 
3624     // There's an optional '#' token here. Normally there wouldn't be, but
3625     // inline assemble puts one in, and it's friendly to accept that.
3626     if (Parser.getTok().is(AsmToken::Hash))
3627       Parser.Lex(); // Eat '#' or '$'.
3628 
3629     const MCExpr *LaneIndex;
3630     SMLoc Loc = Parser.getTok().getLoc();
3631     if (getParser().parseExpression(LaneIndex)) {
3632       Error(Loc, "illegal expression");
3633       return MatchOperand_ParseFail;
3634     }
3635     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
3636     if (!CE) {
3637       Error(Loc, "lane index must be empty or an integer");
3638       return MatchOperand_ParseFail;
3639     }
3640     if (Parser.getTok().isNot(AsmToken::RBrac)) {
3641       Error(Parser.getTok().getLoc(), "']' expected");
3642       return MatchOperand_ParseFail;
3643     }
3644     EndLoc = Parser.getTok().getEndLoc();
3645     Parser.Lex(); // Eat the ']'.
3646     int64_t Val = CE->getValue();
3647 
3648     // FIXME: Make this range check context sensitive for .8, .16, .32.
3649     if (Val < 0 || Val > 7) {
3650       Error(Parser.getTok().getLoc(), "lane index out of range");
3651       return MatchOperand_ParseFail;
3652     }
3653     Index = Val;
3654     LaneKind = IndexedLane;
3655     return MatchOperand_Success;
3656   }
3657   LaneKind = NoLanes;
3658   return MatchOperand_Success;
3659 }
3660 
3661 // parse a vector register list
3662 OperandMatchResultTy
3663 ARMAsmParser::parseVectorList(OperandVector &Operands) {
3664   MCAsmParser &Parser = getParser();
3665   VectorLaneTy LaneKind;
3666   unsigned LaneIndex;
3667   SMLoc S = Parser.getTok().getLoc();
3668   // As an extension (to match gas), support a plain D register or Q register
3669   // (without encosing curly braces) as a single or double entry list,
3670   // respectively.
3671   if (Parser.getTok().is(AsmToken::Identifier)) {
3672     SMLoc E = Parser.getTok().getEndLoc();
3673     int Reg = tryParseRegister();
3674     if (Reg == -1)
3675       return MatchOperand_NoMatch;
3676     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
3677       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3678       if (Res != MatchOperand_Success)
3679         return Res;
3680       switch (LaneKind) {
3681       case NoLanes:
3682         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
3683         break;
3684       case AllLanes:
3685         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
3686                                                                 S, E));
3687         break;
3688       case IndexedLane:
3689         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
3690                                                                LaneIndex,
3691                                                                false, S, E));
3692         break;
3693       }
3694       return MatchOperand_Success;
3695     }
3696     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3697       Reg = getDRegFromQReg(Reg);
3698       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3699       if (Res != MatchOperand_Success)
3700         return Res;
3701       switch (LaneKind) {
3702       case NoLanes:
3703         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3704                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3705         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
3706         break;
3707       case AllLanes:
3708         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3709                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3710         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
3711                                                                 S, E));
3712         break;
3713       case IndexedLane:
3714         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
3715                                                                LaneIndex,
3716                                                                false, S, E));
3717         break;
3718       }
3719       return MatchOperand_Success;
3720     }
3721     Error(S, "vector register expected");
3722     return MatchOperand_ParseFail;
3723   }
3724 
3725   if (Parser.getTok().isNot(AsmToken::LCurly))
3726     return MatchOperand_NoMatch;
3727 
3728   Parser.Lex(); // Eat '{' token.
3729   SMLoc RegLoc = Parser.getTok().getLoc();
3730 
3731   int Reg = tryParseRegister();
3732   if (Reg == -1) {
3733     Error(RegLoc, "register expected");
3734     return MatchOperand_ParseFail;
3735   }
3736   unsigned Count = 1;
3737   int Spacing = 0;
3738   unsigned FirstReg = Reg;
3739   // The list is of D registers, but we also allow Q regs and just interpret
3740   // them as the two D sub-registers.
3741   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3742     FirstReg = Reg = getDRegFromQReg(Reg);
3743     Spacing = 1; // double-spacing requires explicit D registers, otherwise
3744                  // it's ambiguous with four-register single spaced.
3745     ++Reg;
3746     ++Count;
3747   }
3748 
3749   SMLoc E;
3750   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
3751     return MatchOperand_ParseFail;
3752 
3753   while (Parser.getTok().is(AsmToken::Comma) ||
3754          Parser.getTok().is(AsmToken::Minus)) {
3755     if (Parser.getTok().is(AsmToken::Minus)) {
3756       if (!Spacing)
3757         Spacing = 1; // Register range implies a single spaced list.
3758       else if (Spacing == 2) {
3759         Error(Parser.getTok().getLoc(),
3760               "sequential registers in double spaced list");
3761         return MatchOperand_ParseFail;
3762       }
3763       Parser.Lex(); // Eat the minus.
3764       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3765       int EndReg = tryParseRegister();
3766       if (EndReg == -1) {
3767         Error(AfterMinusLoc, "register expected");
3768         return MatchOperand_ParseFail;
3769       }
3770       // Allow Q regs and just interpret them as the two D sub-registers.
3771       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3772         EndReg = getDRegFromQReg(EndReg) + 1;
3773       // If the register is the same as the start reg, there's nothing
3774       // more to do.
3775       if (Reg == EndReg)
3776         continue;
3777       // The register must be in the same register class as the first.
3778       if (!ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg)) {
3779         Error(AfterMinusLoc, "invalid register in register list");
3780         return MatchOperand_ParseFail;
3781       }
3782       // Ranges must go from low to high.
3783       if (Reg > EndReg) {
3784         Error(AfterMinusLoc, "bad range in register list");
3785         return MatchOperand_ParseFail;
3786       }
3787       // Parse the lane specifier if present.
3788       VectorLaneTy NextLaneKind;
3789       unsigned NextLaneIndex;
3790       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3791           MatchOperand_Success)
3792         return MatchOperand_ParseFail;
3793       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3794         Error(AfterMinusLoc, "mismatched lane index in register list");
3795         return MatchOperand_ParseFail;
3796       }
3797 
3798       // Add all the registers in the range to the register list.
3799       Count += EndReg - Reg;
3800       Reg = EndReg;
3801       continue;
3802     }
3803     Parser.Lex(); // Eat the comma.
3804     RegLoc = Parser.getTok().getLoc();
3805     int OldReg = Reg;
3806     Reg = tryParseRegister();
3807     if (Reg == -1) {
3808       Error(RegLoc, "register expected");
3809       return MatchOperand_ParseFail;
3810     }
3811     // vector register lists must be contiguous.
3812     // It's OK to use the enumeration values directly here rather, as the
3813     // VFP register classes have the enum sorted properly.
3814     //
3815     // The list is of D registers, but we also allow Q regs and just interpret
3816     // them as the two D sub-registers.
3817     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3818       if (!Spacing)
3819         Spacing = 1; // Register range implies a single spaced list.
3820       else if (Spacing == 2) {
3821         Error(RegLoc,
3822               "invalid register in double-spaced list (must be 'D' register')");
3823         return MatchOperand_ParseFail;
3824       }
3825       Reg = getDRegFromQReg(Reg);
3826       if (Reg != OldReg + 1) {
3827         Error(RegLoc, "non-contiguous register range");
3828         return MatchOperand_ParseFail;
3829       }
3830       ++Reg;
3831       Count += 2;
3832       // Parse the lane specifier if present.
3833       VectorLaneTy NextLaneKind;
3834       unsigned NextLaneIndex;
3835       SMLoc LaneLoc = Parser.getTok().getLoc();
3836       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3837           MatchOperand_Success)
3838         return MatchOperand_ParseFail;
3839       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3840         Error(LaneLoc, "mismatched lane index in register list");
3841         return MatchOperand_ParseFail;
3842       }
3843       continue;
3844     }
3845     // Normal D register.
3846     // Figure out the register spacing (single or double) of the list if
3847     // we don't know it already.
3848     if (!Spacing)
3849       Spacing = 1 + (Reg == OldReg + 2);
3850 
3851     // Just check that it's contiguous and keep going.
3852     if (Reg != OldReg + Spacing) {
3853       Error(RegLoc, "non-contiguous register range");
3854       return MatchOperand_ParseFail;
3855     }
3856     ++Count;
3857     // Parse the lane specifier if present.
3858     VectorLaneTy NextLaneKind;
3859     unsigned NextLaneIndex;
3860     SMLoc EndLoc = Parser.getTok().getLoc();
3861     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
3862       return MatchOperand_ParseFail;
3863     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3864       Error(EndLoc, "mismatched lane index in register list");
3865       return MatchOperand_ParseFail;
3866     }
3867   }
3868 
3869   if (Parser.getTok().isNot(AsmToken::RCurly)) {
3870     Error(Parser.getTok().getLoc(), "'}' expected");
3871     return MatchOperand_ParseFail;
3872   }
3873   E = Parser.getTok().getEndLoc();
3874   Parser.Lex(); // Eat '}' token.
3875 
3876   switch (LaneKind) {
3877   case NoLanes:
3878     // Two-register operands have been converted to the
3879     // composite register classes.
3880     if (Count == 2) {
3881       const MCRegisterClass *RC = (Spacing == 1) ?
3882         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
3883         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
3884       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
3885     }
3886 
3887     Operands.push_back(ARMOperand::CreateVectorList(FirstReg, Count,
3888                                                     (Spacing == 2), S, E));
3889     break;
3890   case AllLanes:
3891     // Two-register operands have been converted to the
3892     // composite register classes.
3893     if (Count == 2) {
3894       const MCRegisterClass *RC = (Spacing == 1) ?
3895         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
3896         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
3897       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
3898     }
3899     Operands.push_back(ARMOperand::CreateVectorListAllLanes(FirstReg, Count,
3900                                                             (Spacing == 2),
3901                                                             S, E));
3902     break;
3903   case IndexedLane:
3904     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
3905                                                            LaneIndex,
3906                                                            (Spacing == 2),
3907                                                            S, E));
3908     break;
3909   }
3910   return MatchOperand_Success;
3911 }
3912 
3913 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
3914 OperandMatchResultTy
3915 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
3916   MCAsmParser &Parser = getParser();
3917   SMLoc S = Parser.getTok().getLoc();
3918   const AsmToken &Tok = Parser.getTok();
3919   unsigned Opt;
3920 
3921   if (Tok.is(AsmToken::Identifier)) {
3922     StringRef OptStr = Tok.getString();
3923 
3924     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
3925       .Case("sy",    ARM_MB::SY)
3926       .Case("st",    ARM_MB::ST)
3927       .Case("ld",    ARM_MB::LD)
3928       .Case("sh",    ARM_MB::ISH)
3929       .Case("ish",   ARM_MB::ISH)
3930       .Case("shst",  ARM_MB::ISHST)
3931       .Case("ishst", ARM_MB::ISHST)
3932       .Case("ishld", ARM_MB::ISHLD)
3933       .Case("nsh",   ARM_MB::NSH)
3934       .Case("un",    ARM_MB::NSH)
3935       .Case("nshst", ARM_MB::NSHST)
3936       .Case("nshld", ARM_MB::NSHLD)
3937       .Case("unst",  ARM_MB::NSHST)
3938       .Case("osh",   ARM_MB::OSH)
3939       .Case("oshst", ARM_MB::OSHST)
3940       .Case("oshld", ARM_MB::OSHLD)
3941       .Default(~0U);
3942 
3943     // ishld, oshld, nshld and ld are only available from ARMv8.
3944     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
3945                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
3946       Opt = ~0U;
3947 
3948     if (Opt == ~0U)
3949       return MatchOperand_NoMatch;
3950 
3951     Parser.Lex(); // Eat identifier token.
3952   } else if (Tok.is(AsmToken::Hash) ||
3953              Tok.is(AsmToken::Dollar) ||
3954              Tok.is(AsmToken::Integer)) {
3955     if (Parser.getTok().isNot(AsmToken::Integer))
3956       Parser.Lex(); // Eat '#' or '$'.
3957     SMLoc Loc = Parser.getTok().getLoc();
3958 
3959     const MCExpr *MemBarrierID;
3960     if (getParser().parseExpression(MemBarrierID)) {
3961       Error(Loc, "illegal expression");
3962       return MatchOperand_ParseFail;
3963     }
3964 
3965     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
3966     if (!CE) {
3967       Error(Loc, "constant expression expected");
3968       return MatchOperand_ParseFail;
3969     }
3970 
3971     int Val = CE->getValue();
3972     if (Val & ~0xf) {
3973       Error(Loc, "immediate value out of range");
3974       return MatchOperand_ParseFail;
3975     }
3976 
3977     Opt = ARM_MB::RESERVED_0 + Val;
3978   } else
3979     return MatchOperand_ParseFail;
3980 
3981   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
3982   return MatchOperand_Success;
3983 }
3984 
3985 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
3986 OperandMatchResultTy
3987 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
3988   MCAsmParser &Parser = getParser();
3989   SMLoc S = Parser.getTok().getLoc();
3990   const AsmToken &Tok = Parser.getTok();
3991   unsigned Opt;
3992 
3993   if (Tok.is(AsmToken::Identifier)) {
3994     StringRef OptStr = Tok.getString();
3995 
3996     if (OptStr.equals_lower("sy"))
3997       Opt = ARM_ISB::SY;
3998     else
3999       return MatchOperand_NoMatch;
4000 
4001     Parser.Lex(); // Eat identifier token.
4002   } else if (Tok.is(AsmToken::Hash) ||
4003              Tok.is(AsmToken::Dollar) ||
4004              Tok.is(AsmToken::Integer)) {
4005     if (Parser.getTok().isNot(AsmToken::Integer))
4006       Parser.Lex(); // Eat '#' or '$'.
4007     SMLoc Loc = Parser.getTok().getLoc();
4008 
4009     const MCExpr *ISBarrierID;
4010     if (getParser().parseExpression(ISBarrierID)) {
4011       Error(Loc, "illegal expression");
4012       return MatchOperand_ParseFail;
4013     }
4014 
4015     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
4016     if (!CE) {
4017       Error(Loc, "constant expression expected");
4018       return MatchOperand_ParseFail;
4019     }
4020 
4021     int Val = CE->getValue();
4022     if (Val & ~0xf) {
4023       Error(Loc, "immediate value out of range");
4024       return MatchOperand_ParseFail;
4025     }
4026 
4027     Opt = ARM_ISB::RESERVED_0 + Val;
4028   } else
4029     return MatchOperand_ParseFail;
4030 
4031   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
4032           (ARM_ISB::InstSyncBOpt)Opt, S));
4033   return MatchOperand_Success;
4034 }
4035 
4036 
4037 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
4038 OperandMatchResultTy
4039 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
4040   MCAsmParser &Parser = getParser();
4041   SMLoc S = Parser.getTok().getLoc();
4042   const AsmToken &Tok = Parser.getTok();
4043   if (!Tok.is(AsmToken::Identifier))
4044     return MatchOperand_NoMatch;
4045   StringRef IFlagsStr = Tok.getString();
4046 
4047   // An iflags string of "none" is interpreted to mean that none of the AIF
4048   // bits are set.  Not a terribly useful instruction, but a valid encoding.
4049   unsigned IFlags = 0;
4050   if (IFlagsStr != "none") {
4051         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
4052       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1))
4053         .Case("a", ARM_PROC::A)
4054         .Case("i", ARM_PROC::I)
4055         .Case("f", ARM_PROC::F)
4056         .Default(~0U);
4057 
4058       // If some specific iflag is already set, it means that some letter is
4059       // present more than once, this is not acceptable.
4060       if (Flag == ~0U || (IFlags & Flag))
4061         return MatchOperand_NoMatch;
4062 
4063       IFlags |= Flag;
4064     }
4065   }
4066 
4067   Parser.Lex(); // Eat identifier token.
4068   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
4069   return MatchOperand_Success;
4070 }
4071 
4072 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
4073 OperandMatchResultTy
4074 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
4075   MCAsmParser &Parser = getParser();
4076   SMLoc S = Parser.getTok().getLoc();
4077   const AsmToken &Tok = Parser.getTok();
4078   if (!Tok.is(AsmToken::Identifier))
4079     return MatchOperand_NoMatch;
4080   StringRef Mask = Tok.getString();
4081 
4082   if (isMClass()) {
4083     // See ARMv6-M 10.1.1
4084     std::string Name = Mask.lower();
4085     unsigned FlagsVal = StringSwitch<unsigned>(Name)
4086       // Note: in the documentation:
4087       //  ARM deprecates using MSR APSR without a _<bits> qualifier as an alias
4088       //  for MSR APSR_nzcvq.
4089       // but we do make it an alias here.  This is so to get the "mask encoding"
4090       // bits correct on MSR APSR writes.
4091       //
4092       // FIXME: Note the 0xc00 "mask encoding" bits version of the registers
4093       // should really only be allowed when writing a special register.  Note
4094       // they get dropped in the MRS instruction reading a special register as
4095       // the SYSm field is only 8 bits.
4096       .Case("apsr", 0x800)
4097       .Case("apsr_nzcvq", 0x800)
4098       .Case("apsr_g", 0x400)
4099       .Case("apsr_nzcvqg", 0xc00)
4100       .Case("iapsr", 0x801)
4101       .Case("iapsr_nzcvq", 0x801)
4102       .Case("iapsr_g", 0x401)
4103       .Case("iapsr_nzcvqg", 0xc01)
4104       .Case("eapsr", 0x802)
4105       .Case("eapsr_nzcvq", 0x802)
4106       .Case("eapsr_g", 0x402)
4107       .Case("eapsr_nzcvqg", 0xc02)
4108       .Case("xpsr", 0x803)
4109       .Case("xpsr_nzcvq", 0x803)
4110       .Case("xpsr_g", 0x403)
4111       .Case("xpsr_nzcvqg", 0xc03)
4112       .Case("ipsr", 0x805)
4113       .Case("epsr", 0x806)
4114       .Case("iepsr", 0x807)
4115       .Case("msp", 0x808)
4116       .Case("psp", 0x809)
4117       .Case("primask", 0x810)
4118       .Case("basepri", 0x811)
4119       .Case("basepri_max", 0x812)
4120       .Case("faultmask", 0x813)
4121       .Case("control", 0x814)
4122       .Case("msplim", 0x80a)
4123       .Case("psplim", 0x80b)
4124       .Case("msp_ns", 0x888)
4125       .Case("psp_ns", 0x889)
4126       .Case("msplim_ns", 0x88a)
4127       .Case("psplim_ns", 0x88b)
4128       .Case("primask_ns", 0x890)
4129       .Case("basepri_ns", 0x891)
4130       .Case("basepri_max_ns", 0x892)
4131       .Case("faultmask_ns", 0x893)
4132       .Case("control_ns", 0x894)
4133       .Case("sp_ns", 0x898)
4134       .Default(~0U);
4135 
4136     if (FlagsVal == ~0U)
4137       return MatchOperand_NoMatch;
4138 
4139     if (!hasDSP() && (FlagsVal & 0x400))
4140       // The _g and _nzcvqg versions are only valid if the DSP extension is
4141       // available.
4142       return MatchOperand_NoMatch;
4143 
4144     if (!hasV7Ops() && FlagsVal >= 0x811 && FlagsVal <= 0x813)
4145       // basepri, basepri_max and faultmask only valid for V7m.
4146       return MatchOperand_NoMatch;
4147 
4148     if (!has8MSecExt() && (FlagsVal == 0x80a || FlagsVal == 0x80b ||
4149                              (FlagsVal > 0x814 && FlagsVal < 0xc00)))
4150       return MatchOperand_NoMatch;
4151 
4152     if (!hasV8MMainline() && (FlagsVal == 0x88a || FlagsVal == 0x88b ||
4153                               (FlagsVal > 0x890 && FlagsVal <= 0x893)))
4154       return MatchOperand_NoMatch;
4155 
4156     Parser.Lex(); // Eat identifier token.
4157     Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4158     return MatchOperand_Success;
4159   }
4160 
4161   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
4162   size_t Start = 0, Next = Mask.find('_');
4163   StringRef Flags = "";
4164   std::string SpecReg = Mask.slice(Start, Next).lower();
4165   if (Next != StringRef::npos)
4166     Flags = Mask.slice(Next+1, Mask.size());
4167 
4168   // FlagsVal contains the complete mask:
4169   // 3-0: Mask
4170   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4171   unsigned FlagsVal = 0;
4172 
4173   if (SpecReg == "apsr") {
4174     FlagsVal = StringSwitch<unsigned>(Flags)
4175     .Case("nzcvq",  0x8) // same as CPSR_f
4176     .Case("g",      0x4) // same as CPSR_s
4177     .Case("nzcvqg", 0xc) // same as CPSR_fs
4178     .Default(~0U);
4179 
4180     if (FlagsVal == ~0U) {
4181       if (!Flags.empty())
4182         return MatchOperand_NoMatch;
4183       else
4184         FlagsVal = 8; // No flag
4185     }
4186   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
4187     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
4188     if (Flags == "all" || Flags == "")
4189       Flags = "fc";
4190     for (int i = 0, e = Flags.size(); i != e; ++i) {
4191       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
4192       .Case("c", 1)
4193       .Case("x", 2)
4194       .Case("s", 4)
4195       .Case("f", 8)
4196       .Default(~0U);
4197 
4198       // If some specific flag is already set, it means that some letter is
4199       // present more than once, this is not acceptable.
4200       if (Flag == ~0U || (FlagsVal & Flag))
4201         return MatchOperand_NoMatch;
4202       FlagsVal |= Flag;
4203     }
4204   } else // No match for special register.
4205     return MatchOperand_NoMatch;
4206 
4207   // Special register without flags is NOT equivalent to "fc" flags.
4208   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
4209   // two lines would enable gas compatibility at the expense of breaking
4210   // round-tripping.
4211   //
4212   // if (!FlagsVal)
4213   //  FlagsVal = 0x9;
4214 
4215   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4216   if (SpecReg == "spsr")
4217     FlagsVal |= 16;
4218 
4219   Parser.Lex(); // Eat identifier token.
4220   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4221   return MatchOperand_Success;
4222 }
4223 
4224 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
4225 /// use in the MRS/MSR instructions added to support virtualization.
4226 OperandMatchResultTy
4227 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
4228   MCAsmParser &Parser = getParser();
4229   SMLoc S = Parser.getTok().getLoc();
4230   const AsmToken &Tok = Parser.getTok();
4231   if (!Tok.is(AsmToken::Identifier))
4232     return MatchOperand_NoMatch;
4233   StringRef RegName = Tok.getString();
4234 
4235   // The values here come from B9.2.3 of the ARM ARM, where bits 4-0 are SysM
4236   // and bit 5 is R.
4237   unsigned Encoding = StringSwitch<unsigned>(RegName.lower())
4238                           .Case("r8_usr", 0x00)
4239                           .Case("r9_usr", 0x01)
4240                           .Case("r10_usr", 0x02)
4241                           .Case("r11_usr", 0x03)
4242                           .Case("r12_usr", 0x04)
4243                           .Case("sp_usr", 0x05)
4244                           .Case("lr_usr", 0x06)
4245                           .Case("r8_fiq", 0x08)
4246                           .Case("r9_fiq", 0x09)
4247                           .Case("r10_fiq", 0x0a)
4248                           .Case("r11_fiq", 0x0b)
4249                           .Case("r12_fiq", 0x0c)
4250                           .Case("sp_fiq", 0x0d)
4251                           .Case("lr_fiq", 0x0e)
4252                           .Case("lr_irq", 0x10)
4253                           .Case("sp_irq", 0x11)
4254                           .Case("lr_svc", 0x12)
4255                           .Case("sp_svc", 0x13)
4256                           .Case("lr_abt", 0x14)
4257                           .Case("sp_abt", 0x15)
4258                           .Case("lr_und", 0x16)
4259                           .Case("sp_und", 0x17)
4260                           .Case("lr_mon", 0x1c)
4261                           .Case("sp_mon", 0x1d)
4262                           .Case("elr_hyp", 0x1e)
4263                           .Case("sp_hyp", 0x1f)
4264                           .Case("spsr_fiq", 0x2e)
4265                           .Case("spsr_irq", 0x30)
4266                           .Case("spsr_svc", 0x32)
4267                           .Case("spsr_abt", 0x34)
4268                           .Case("spsr_und", 0x36)
4269                           .Case("spsr_mon", 0x3c)
4270                           .Case("spsr_hyp", 0x3e)
4271                           .Default(~0U);
4272 
4273   if (Encoding == ~0U)
4274     return MatchOperand_NoMatch;
4275 
4276   Parser.Lex(); // Eat identifier token.
4277   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
4278   return MatchOperand_Success;
4279 }
4280 
4281 OperandMatchResultTy
4282 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
4283                           int High) {
4284   MCAsmParser &Parser = getParser();
4285   const AsmToken &Tok = Parser.getTok();
4286   if (Tok.isNot(AsmToken::Identifier)) {
4287     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4288     return MatchOperand_ParseFail;
4289   }
4290   StringRef ShiftName = Tok.getString();
4291   std::string LowerOp = Op.lower();
4292   std::string UpperOp = Op.upper();
4293   if (ShiftName != LowerOp && ShiftName != UpperOp) {
4294     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4295     return MatchOperand_ParseFail;
4296   }
4297   Parser.Lex(); // Eat shift type token.
4298 
4299   // There must be a '#' and a shift amount.
4300   if (Parser.getTok().isNot(AsmToken::Hash) &&
4301       Parser.getTok().isNot(AsmToken::Dollar)) {
4302     Error(Parser.getTok().getLoc(), "'#' expected");
4303     return MatchOperand_ParseFail;
4304   }
4305   Parser.Lex(); // Eat hash token.
4306 
4307   const MCExpr *ShiftAmount;
4308   SMLoc Loc = Parser.getTok().getLoc();
4309   SMLoc EndLoc;
4310   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4311     Error(Loc, "illegal expression");
4312     return MatchOperand_ParseFail;
4313   }
4314   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4315   if (!CE) {
4316     Error(Loc, "constant expression expected");
4317     return MatchOperand_ParseFail;
4318   }
4319   int Val = CE->getValue();
4320   if (Val < Low || Val > High) {
4321     Error(Loc, "immediate value out of range");
4322     return MatchOperand_ParseFail;
4323   }
4324 
4325   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
4326 
4327   return MatchOperand_Success;
4328 }
4329 
4330 OperandMatchResultTy
4331 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
4332   MCAsmParser &Parser = getParser();
4333   const AsmToken &Tok = Parser.getTok();
4334   SMLoc S = Tok.getLoc();
4335   if (Tok.isNot(AsmToken::Identifier)) {
4336     Error(S, "'be' or 'le' operand expected");
4337     return MatchOperand_ParseFail;
4338   }
4339   int Val = StringSwitch<int>(Tok.getString().lower())
4340     .Case("be", 1)
4341     .Case("le", 0)
4342     .Default(-1);
4343   Parser.Lex(); // Eat the token.
4344 
4345   if (Val == -1) {
4346     Error(S, "'be' or 'le' operand expected");
4347     return MatchOperand_ParseFail;
4348   }
4349   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
4350                                                                   getContext()),
4351                                            S, Tok.getEndLoc()));
4352   return MatchOperand_Success;
4353 }
4354 
4355 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
4356 /// instructions. Legal values are:
4357 ///     lsl #n  'n' in [0,31]
4358 ///     asr #n  'n' in [1,32]
4359 ///             n == 32 encoded as n == 0.
4360 OperandMatchResultTy
4361 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
4362   MCAsmParser &Parser = getParser();
4363   const AsmToken &Tok = Parser.getTok();
4364   SMLoc S = Tok.getLoc();
4365   if (Tok.isNot(AsmToken::Identifier)) {
4366     Error(S, "shift operator 'asr' or 'lsl' expected");
4367     return MatchOperand_ParseFail;
4368   }
4369   StringRef ShiftName = Tok.getString();
4370   bool isASR;
4371   if (ShiftName == "lsl" || ShiftName == "LSL")
4372     isASR = false;
4373   else if (ShiftName == "asr" || ShiftName == "ASR")
4374     isASR = true;
4375   else {
4376     Error(S, "shift operator 'asr' or 'lsl' expected");
4377     return MatchOperand_ParseFail;
4378   }
4379   Parser.Lex(); // Eat the operator.
4380 
4381   // A '#' and a shift amount.
4382   if (Parser.getTok().isNot(AsmToken::Hash) &&
4383       Parser.getTok().isNot(AsmToken::Dollar)) {
4384     Error(Parser.getTok().getLoc(), "'#' expected");
4385     return MatchOperand_ParseFail;
4386   }
4387   Parser.Lex(); // Eat hash token.
4388   SMLoc ExLoc = Parser.getTok().getLoc();
4389 
4390   const MCExpr *ShiftAmount;
4391   SMLoc EndLoc;
4392   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4393     Error(ExLoc, "malformed shift expression");
4394     return MatchOperand_ParseFail;
4395   }
4396   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4397   if (!CE) {
4398     Error(ExLoc, "shift amount must be an immediate");
4399     return MatchOperand_ParseFail;
4400   }
4401 
4402   int64_t Val = CE->getValue();
4403   if (isASR) {
4404     // Shift amount must be in [1,32]
4405     if (Val < 1 || Val > 32) {
4406       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
4407       return MatchOperand_ParseFail;
4408     }
4409     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
4410     if (isThumb() && Val == 32) {
4411       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
4412       return MatchOperand_ParseFail;
4413     }
4414     if (Val == 32) Val = 0;
4415   } else {
4416     // Shift amount must be in [1,32]
4417     if (Val < 0 || Val > 31) {
4418       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
4419       return MatchOperand_ParseFail;
4420     }
4421   }
4422 
4423   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
4424 
4425   return MatchOperand_Success;
4426 }
4427 
4428 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
4429 /// of instructions. Legal values are:
4430 ///     ror #n  'n' in {0, 8, 16, 24}
4431 OperandMatchResultTy
4432 ARMAsmParser::parseRotImm(OperandVector &Operands) {
4433   MCAsmParser &Parser = getParser();
4434   const AsmToken &Tok = Parser.getTok();
4435   SMLoc S = Tok.getLoc();
4436   if (Tok.isNot(AsmToken::Identifier))
4437     return MatchOperand_NoMatch;
4438   StringRef ShiftName = Tok.getString();
4439   if (ShiftName != "ror" && ShiftName != "ROR")
4440     return MatchOperand_NoMatch;
4441   Parser.Lex(); // Eat the operator.
4442 
4443   // A '#' and a rotate amount.
4444   if (Parser.getTok().isNot(AsmToken::Hash) &&
4445       Parser.getTok().isNot(AsmToken::Dollar)) {
4446     Error(Parser.getTok().getLoc(), "'#' expected");
4447     return MatchOperand_ParseFail;
4448   }
4449   Parser.Lex(); // Eat hash token.
4450   SMLoc ExLoc = Parser.getTok().getLoc();
4451 
4452   const MCExpr *ShiftAmount;
4453   SMLoc EndLoc;
4454   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4455     Error(ExLoc, "malformed rotate expression");
4456     return MatchOperand_ParseFail;
4457   }
4458   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4459   if (!CE) {
4460     Error(ExLoc, "rotate amount must be an immediate");
4461     return MatchOperand_ParseFail;
4462   }
4463 
4464   int64_t Val = CE->getValue();
4465   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
4466   // normally, zero is represented in asm by omitting the rotate operand
4467   // entirely.
4468   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
4469     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
4470     return MatchOperand_ParseFail;
4471   }
4472 
4473   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
4474 
4475   return MatchOperand_Success;
4476 }
4477 
4478 OperandMatchResultTy
4479 ARMAsmParser::parseModImm(OperandVector &Operands) {
4480   MCAsmParser &Parser = getParser();
4481   MCAsmLexer &Lexer = getLexer();
4482   int64_t Imm1, Imm2;
4483 
4484   SMLoc S = Parser.getTok().getLoc();
4485 
4486   // 1) A mod_imm operand can appear in the place of a register name:
4487   //   add r0, #mod_imm
4488   //   add r0, r0, #mod_imm
4489   // to correctly handle the latter, we bail out as soon as we see an
4490   // identifier.
4491   //
4492   // 2) Similarly, we do not want to parse into complex operands:
4493   //   mov r0, #mod_imm
4494   //   mov r0, :lower16:(_foo)
4495   if (Parser.getTok().is(AsmToken::Identifier) ||
4496       Parser.getTok().is(AsmToken::Colon))
4497     return MatchOperand_NoMatch;
4498 
4499   // Hash (dollar) is optional as per the ARMARM
4500   if (Parser.getTok().is(AsmToken::Hash) ||
4501       Parser.getTok().is(AsmToken::Dollar)) {
4502     // Avoid parsing into complex operands (#:)
4503     if (Lexer.peekTok().is(AsmToken::Colon))
4504       return MatchOperand_NoMatch;
4505 
4506     // Eat the hash (dollar)
4507     Parser.Lex();
4508   }
4509 
4510   SMLoc Sx1, Ex1;
4511   Sx1 = Parser.getTok().getLoc();
4512   const MCExpr *Imm1Exp;
4513   if (getParser().parseExpression(Imm1Exp, Ex1)) {
4514     Error(Sx1, "malformed expression");
4515     return MatchOperand_ParseFail;
4516   }
4517 
4518   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
4519 
4520   if (CE) {
4521     // Immediate must fit within 32-bits
4522     Imm1 = CE->getValue();
4523     int Enc = ARM_AM::getSOImmVal(Imm1);
4524     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
4525       // We have a match!
4526       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
4527                                                   (Enc & 0xF00) >> 7,
4528                                                   Sx1, Ex1));
4529       return MatchOperand_Success;
4530     }
4531 
4532     // We have parsed an immediate which is not for us, fallback to a plain
4533     // immediate. This can happen for instruction aliases. For an example,
4534     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
4535     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
4536     // instruction with a mod_imm operand. The alias is defined such that the
4537     // parser method is shared, that's why we have to do this here.
4538     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
4539       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4540       return MatchOperand_Success;
4541     }
4542   } else {
4543     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
4544     // MCFixup). Fallback to a plain immediate.
4545     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4546     return MatchOperand_Success;
4547   }
4548 
4549   // From this point onward, we expect the input to be a (#bits, #rot) pair
4550   if (Parser.getTok().isNot(AsmToken::Comma)) {
4551     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
4552     return MatchOperand_ParseFail;
4553   }
4554 
4555   if (Imm1 & ~0xFF) {
4556     Error(Sx1, "immediate operand must a number in the range [0, 255]");
4557     return MatchOperand_ParseFail;
4558   }
4559 
4560   // Eat the comma
4561   Parser.Lex();
4562 
4563   // Repeat for #rot
4564   SMLoc Sx2, Ex2;
4565   Sx2 = Parser.getTok().getLoc();
4566 
4567   // Eat the optional hash (dollar)
4568   if (Parser.getTok().is(AsmToken::Hash) ||
4569       Parser.getTok().is(AsmToken::Dollar))
4570     Parser.Lex();
4571 
4572   const MCExpr *Imm2Exp;
4573   if (getParser().parseExpression(Imm2Exp, Ex2)) {
4574     Error(Sx2, "malformed expression");
4575     return MatchOperand_ParseFail;
4576   }
4577 
4578   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
4579 
4580   if (CE) {
4581     Imm2 = CE->getValue();
4582     if (!(Imm2 & ~0x1E)) {
4583       // We have a match!
4584       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
4585       return MatchOperand_Success;
4586     }
4587     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
4588     return MatchOperand_ParseFail;
4589   } else {
4590     Error(Sx2, "constant expression expected");
4591     return MatchOperand_ParseFail;
4592   }
4593 }
4594 
4595 OperandMatchResultTy
4596 ARMAsmParser::parseBitfield(OperandVector &Operands) {
4597   MCAsmParser &Parser = getParser();
4598   SMLoc S = Parser.getTok().getLoc();
4599   // The bitfield descriptor is really two operands, the LSB and the width.
4600   if (Parser.getTok().isNot(AsmToken::Hash) &&
4601       Parser.getTok().isNot(AsmToken::Dollar)) {
4602     Error(Parser.getTok().getLoc(), "'#' expected");
4603     return MatchOperand_ParseFail;
4604   }
4605   Parser.Lex(); // Eat hash token.
4606 
4607   const MCExpr *LSBExpr;
4608   SMLoc E = Parser.getTok().getLoc();
4609   if (getParser().parseExpression(LSBExpr)) {
4610     Error(E, "malformed immediate expression");
4611     return MatchOperand_ParseFail;
4612   }
4613   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
4614   if (!CE) {
4615     Error(E, "'lsb' operand must be an immediate");
4616     return MatchOperand_ParseFail;
4617   }
4618 
4619   int64_t LSB = CE->getValue();
4620   // The LSB must be in the range [0,31]
4621   if (LSB < 0 || LSB > 31) {
4622     Error(E, "'lsb' operand must be in the range [0,31]");
4623     return MatchOperand_ParseFail;
4624   }
4625   E = Parser.getTok().getLoc();
4626 
4627   // Expect another immediate operand.
4628   if (Parser.getTok().isNot(AsmToken::Comma)) {
4629     Error(Parser.getTok().getLoc(), "too few operands");
4630     return MatchOperand_ParseFail;
4631   }
4632   Parser.Lex(); // Eat hash token.
4633   if (Parser.getTok().isNot(AsmToken::Hash) &&
4634       Parser.getTok().isNot(AsmToken::Dollar)) {
4635     Error(Parser.getTok().getLoc(), "'#' expected");
4636     return MatchOperand_ParseFail;
4637   }
4638   Parser.Lex(); // Eat hash token.
4639 
4640   const MCExpr *WidthExpr;
4641   SMLoc EndLoc;
4642   if (getParser().parseExpression(WidthExpr, EndLoc)) {
4643     Error(E, "malformed immediate expression");
4644     return MatchOperand_ParseFail;
4645   }
4646   CE = dyn_cast<MCConstantExpr>(WidthExpr);
4647   if (!CE) {
4648     Error(E, "'width' operand must be an immediate");
4649     return MatchOperand_ParseFail;
4650   }
4651 
4652   int64_t Width = CE->getValue();
4653   // The LSB must be in the range [1,32-lsb]
4654   if (Width < 1 || Width > 32 - LSB) {
4655     Error(E, "'width' operand must be in the range [1,32-lsb]");
4656     return MatchOperand_ParseFail;
4657   }
4658 
4659   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
4660 
4661   return MatchOperand_Success;
4662 }
4663 
4664 OperandMatchResultTy
4665 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
4666   // Check for a post-index addressing register operand. Specifically:
4667   // postidx_reg := '+' register {, shift}
4668   //              | '-' register {, shift}
4669   //              | register {, shift}
4670 
4671   // This method must return MatchOperand_NoMatch without consuming any tokens
4672   // in the case where there is no match, as other alternatives take other
4673   // parse methods.
4674   MCAsmParser &Parser = getParser();
4675   AsmToken Tok = Parser.getTok();
4676   SMLoc S = Tok.getLoc();
4677   bool haveEaten = false;
4678   bool isAdd = true;
4679   if (Tok.is(AsmToken::Plus)) {
4680     Parser.Lex(); // Eat the '+' token.
4681     haveEaten = true;
4682   } else if (Tok.is(AsmToken::Minus)) {
4683     Parser.Lex(); // Eat the '-' token.
4684     isAdd = false;
4685     haveEaten = true;
4686   }
4687 
4688   SMLoc E = Parser.getTok().getEndLoc();
4689   int Reg = tryParseRegister();
4690   if (Reg == -1) {
4691     if (!haveEaten)
4692       return MatchOperand_NoMatch;
4693     Error(Parser.getTok().getLoc(), "register expected");
4694     return MatchOperand_ParseFail;
4695   }
4696 
4697   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
4698   unsigned ShiftImm = 0;
4699   if (Parser.getTok().is(AsmToken::Comma)) {
4700     Parser.Lex(); // Eat the ','.
4701     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
4702       return MatchOperand_ParseFail;
4703 
4704     // FIXME: Only approximates end...may include intervening whitespace.
4705     E = Parser.getTok().getLoc();
4706   }
4707 
4708   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
4709                                                   ShiftImm, S, E));
4710 
4711   return MatchOperand_Success;
4712 }
4713 
4714 OperandMatchResultTy
4715 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
4716   // Check for a post-index addressing register operand. Specifically:
4717   // am3offset := '+' register
4718   //              | '-' register
4719   //              | register
4720   //              | # imm
4721   //              | # + imm
4722   //              | # - imm
4723 
4724   // This method must return MatchOperand_NoMatch without consuming any tokens
4725   // in the case where there is no match, as other alternatives take other
4726   // parse methods.
4727   MCAsmParser &Parser = getParser();
4728   AsmToken Tok = Parser.getTok();
4729   SMLoc S = Tok.getLoc();
4730 
4731   // Do immediates first, as we always parse those if we have a '#'.
4732   if (Parser.getTok().is(AsmToken::Hash) ||
4733       Parser.getTok().is(AsmToken::Dollar)) {
4734     Parser.Lex(); // Eat '#' or '$'.
4735     // Explicitly look for a '-', as we need to encode negative zero
4736     // differently.
4737     bool isNegative = Parser.getTok().is(AsmToken::Minus);
4738     const MCExpr *Offset;
4739     SMLoc E;
4740     if (getParser().parseExpression(Offset, E))
4741       return MatchOperand_ParseFail;
4742     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4743     if (!CE) {
4744       Error(S, "constant expression expected");
4745       return MatchOperand_ParseFail;
4746     }
4747     // Negative zero is encoded as the flag value INT32_MIN.
4748     int32_t Val = CE->getValue();
4749     if (isNegative && Val == 0)
4750       Val = INT32_MIN;
4751 
4752     Operands.push_back(
4753       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
4754 
4755     return MatchOperand_Success;
4756   }
4757 
4758 
4759   bool haveEaten = false;
4760   bool isAdd = true;
4761   if (Tok.is(AsmToken::Plus)) {
4762     Parser.Lex(); // Eat the '+' token.
4763     haveEaten = true;
4764   } else if (Tok.is(AsmToken::Minus)) {
4765     Parser.Lex(); // Eat the '-' token.
4766     isAdd = false;
4767     haveEaten = true;
4768   }
4769 
4770   Tok = Parser.getTok();
4771   int Reg = tryParseRegister();
4772   if (Reg == -1) {
4773     if (!haveEaten)
4774       return MatchOperand_NoMatch;
4775     Error(Tok.getLoc(), "register expected");
4776     return MatchOperand_ParseFail;
4777   }
4778 
4779   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
4780                                                   0, S, Tok.getEndLoc()));
4781 
4782   return MatchOperand_Success;
4783 }
4784 
4785 /// Convert parsed operands to MCInst.  Needed here because this instruction
4786 /// only has two register operands, but multiplication is commutative so
4787 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
4788 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
4789                                     const OperandVector &Operands) {
4790   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
4791   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
4792   // If we have a three-operand form, make sure to set Rn to be the operand
4793   // that isn't the same as Rd.
4794   unsigned RegOp = 4;
4795   if (Operands.size() == 6 &&
4796       ((ARMOperand &)*Operands[4]).getReg() ==
4797           ((ARMOperand &)*Operands[3]).getReg())
4798     RegOp = 5;
4799   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
4800   Inst.addOperand(Inst.getOperand(0));
4801   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
4802 }
4803 
4804 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
4805                                     const OperandVector &Operands) {
4806   int CondOp = -1, ImmOp = -1;
4807   switch(Inst.getOpcode()) {
4808     case ARM::tB:
4809     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
4810 
4811     case ARM::t2B:
4812     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
4813 
4814     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
4815   }
4816   // first decide whether or not the branch should be conditional
4817   // by looking at it's location relative to an IT block
4818   if(inITBlock()) {
4819     // inside an IT block we cannot have any conditional branches. any
4820     // such instructions needs to be converted to unconditional form
4821     switch(Inst.getOpcode()) {
4822       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
4823       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
4824     }
4825   } else {
4826     // outside IT blocks we can only have unconditional branches with AL
4827     // condition code or conditional branches with non-AL condition code
4828     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
4829     switch(Inst.getOpcode()) {
4830       case ARM::tB:
4831       case ARM::tBcc:
4832         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc);
4833         break;
4834       case ARM::t2B:
4835       case ARM::t2Bcc:
4836         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
4837         break;
4838     }
4839   }
4840 
4841   // now decide on encoding size based on branch target range
4842   switch(Inst.getOpcode()) {
4843     // classify tB as either t2B or t1B based on range of immediate operand
4844     case ARM::tB: {
4845       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4846       if (!op.isSignedOffset<11, 1>() && isThumb() && hasV8MBaseline())
4847         Inst.setOpcode(ARM::t2B);
4848       break;
4849     }
4850     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
4851     case ARM::tBcc: {
4852       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4853       if (!op.isSignedOffset<8, 1>() && isThumb() && hasV8MBaseline())
4854         Inst.setOpcode(ARM::t2Bcc);
4855       break;
4856     }
4857   }
4858   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
4859   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
4860 }
4861 
4862 /// Parse an ARM memory expression, return false if successful else return true
4863 /// or an error.  The first token must be a '[' when called.
4864 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
4865   MCAsmParser &Parser = getParser();
4866   SMLoc S, E;
4867   if (Parser.getTok().isNot(AsmToken::LBrac))
4868     return TokError("Token is not a Left Bracket");
4869   S = Parser.getTok().getLoc();
4870   Parser.Lex(); // Eat left bracket token.
4871 
4872   const AsmToken &BaseRegTok = Parser.getTok();
4873   int BaseRegNum = tryParseRegister();
4874   if (BaseRegNum == -1)
4875     return Error(BaseRegTok.getLoc(), "register expected");
4876 
4877   // The next token must either be a comma, a colon or a closing bracket.
4878   const AsmToken &Tok = Parser.getTok();
4879   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
4880       !Tok.is(AsmToken::RBrac))
4881     return Error(Tok.getLoc(), "malformed memory operand");
4882 
4883   if (Tok.is(AsmToken::RBrac)) {
4884     E = Tok.getEndLoc();
4885     Parser.Lex(); // Eat right bracket token.
4886 
4887     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4888                                              ARM_AM::no_shift, 0, 0, false,
4889                                              S, E));
4890 
4891     // If there's a pre-indexing writeback marker, '!', just add it as a token
4892     // operand. It's rather odd, but syntactically valid.
4893     if (Parser.getTok().is(AsmToken::Exclaim)) {
4894       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4895       Parser.Lex(); // Eat the '!'.
4896     }
4897 
4898     return false;
4899   }
4900 
4901   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
4902          "Lost colon or comma in memory operand?!");
4903   if (Tok.is(AsmToken::Comma)) {
4904     Parser.Lex(); // Eat the comma.
4905   }
4906 
4907   // If we have a ':', it's an alignment specifier.
4908   if (Parser.getTok().is(AsmToken::Colon)) {
4909     Parser.Lex(); // Eat the ':'.
4910     E = Parser.getTok().getLoc();
4911     SMLoc AlignmentLoc = Tok.getLoc();
4912 
4913     const MCExpr *Expr;
4914     if (getParser().parseExpression(Expr))
4915      return true;
4916 
4917     // The expression has to be a constant. Memory references with relocations
4918     // don't come through here, as they use the <label> forms of the relevant
4919     // instructions.
4920     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4921     if (!CE)
4922       return Error (E, "constant expression expected");
4923 
4924     unsigned Align = 0;
4925     switch (CE->getValue()) {
4926     default:
4927       return Error(E,
4928                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
4929     case 16:  Align = 2; break;
4930     case 32:  Align = 4; break;
4931     case 64:  Align = 8; break;
4932     case 128: Align = 16; break;
4933     case 256: Align = 32; break;
4934     }
4935 
4936     // Now we should have the closing ']'
4937     if (Parser.getTok().isNot(AsmToken::RBrac))
4938       return Error(Parser.getTok().getLoc(), "']' expected");
4939     E = Parser.getTok().getEndLoc();
4940     Parser.Lex(); // Eat right bracket token.
4941 
4942     // Don't worry about range checking the value here. That's handled by
4943     // the is*() predicates.
4944     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4945                                              ARM_AM::no_shift, 0, Align,
4946                                              false, S, E, AlignmentLoc));
4947 
4948     // If there's a pre-indexing writeback marker, '!', just add it as a token
4949     // operand.
4950     if (Parser.getTok().is(AsmToken::Exclaim)) {
4951       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4952       Parser.Lex(); // Eat the '!'.
4953     }
4954 
4955     return false;
4956   }
4957 
4958   // If we have a '#', it's an immediate offset, else assume it's a register
4959   // offset. Be friendly and also accept a plain integer (without a leading
4960   // hash) for gas compatibility.
4961   if (Parser.getTok().is(AsmToken::Hash) ||
4962       Parser.getTok().is(AsmToken::Dollar) ||
4963       Parser.getTok().is(AsmToken::Integer)) {
4964     if (Parser.getTok().isNot(AsmToken::Integer))
4965       Parser.Lex(); // Eat '#' or '$'.
4966     E = Parser.getTok().getLoc();
4967 
4968     bool isNegative = getParser().getTok().is(AsmToken::Minus);
4969     const MCExpr *Offset;
4970     if (getParser().parseExpression(Offset))
4971      return true;
4972 
4973     // The expression has to be a constant. Memory references with relocations
4974     // don't come through here, as they use the <label> forms of the relevant
4975     // instructions.
4976     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4977     if (!CE)
4978       return Error (E, "constant expression expected");
4979 
4980     // If the constant was #-0, represent it as INT32_MIN.
4981     int32_t Val = CE->getValue();
4982     if (isNegative && Val == 0)
4983       CE = MCConstantExpr::create(INT32_MIN, getContext());
4984 
4985     // Now we should have the closing ']'
4986     if (Parser.getTok().isNot(AsmToken::RBrac))
4987       return Error(Parser.getTok().getLoc(), "']' expected");
4988     E = Parser.getTok().getEndLoc();
4989     Parser.Lex(); // Eat right bracket token.
4990 
4991     // Don't worry about range checking the value here. That's handled by
4992     // the is*() predicates.
4993     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
4994                                              ARM_AM::no_shift, 0, 0,
4995                                              false, S, E));
4996 
4997     // If there's a pre-indexing writeback marker, '!', just add it as a token
4998     // operand.
4999     if (Parser.getTok().is(AsmToken::Exclaim)) {
5000       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5001       Parser.Lex(); // Eat the '!'.
5002     }
5003 
5004     return false;
5005   }
5006 
5007   // The register offset is optionally preceded by a '+' or '-'
5008   bool isNegative = false;
5009   if (Parser.getTok().is(AsmToken::Minus)) {
5010     isNegative = true;
5011     Parser.Lex(); // Eat the '-'.
5012   } else if (Parser.getTok().is(AsmToken::Plus)) {
5013     // Nothing to do.
5014     Parser.Lex(); // Eat the '+'.
5015   }
5016 
5017   E = Parser.getTok().getLoc();
5018   int OffsetRegNum = tryParseRegister();
5019   if (OffsetRegNum == -1)
5020     return Error(E, "register expected");
5021 
5022   // If there's a shift operator, handle it.
5023   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
5024   unsigned ShiftImm = 0;
5025   if (Parser.getTok().is(AsmToken::Comma)) {
5026     Parser.Lex(); // Eat the ','.
5027     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
5028       return true;
5029   }
5030 
5031   // Now we should have the closing ']'
5032   if (Parser.getTok().isNot(AsmToken::RBrac))
5033     return Error(Parser.getTok().getLoc(), "']' expected");
5034   E = Parser.getTok().getEndLoc();
5035   Parser.Lex(); // Eat right bracket token.
5036 
5037   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
5038                                            ShiftType, ShiftImm, 0, isNegative,
5039                                            S, E));
5040 
5041   // If there's a pre-indexing writeback marker, '!', just add it as a token
5042   // operand.
5043   if (Parser.getTok().is(AsmToken::Exclaim)) {
5044     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5045     Parser.Lex(); // Eat the '!'.
5046   }
5047 
5048   return false;
5049 }
5050 
5051 /// parseMemRegOffsetShift - one of these two:
5052 ///   ( lsl | lsr | asr | ror ) , # shift_amount
5053 ///   rrx
5054 /// return true if it parses a shift otherwise it returns false.
5055 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
5056                                           unsigned &Amount) {
5057   MCAsmParser &Parser = getParser();
5058   SMLoc Loc = Parser.getTok().getLoc();
5059   const AsmToken &Tok = Parser.getTok();
5060   if (Tok.isNot(AsmToken::Identifier))
5061     return true;
5062   StringRef ShiftName = Tok.getString();
5063   if (ShiftName == "lsl" || ShiftName == "LSL" ||
5064       ShiftName == "asl" || ShiftName == "ASL")
5065     St = ARM_AM::lsl;
5066   else if (ShiftName == "lsr" || ShiftName == "LSR")
5067     St = ARM_AM::lsr;
5068   else if (ShiftName == "asr" || ShiftName == "ASR")
5069     St = ARM_AM::asr;
5070   else if (ShiftName == "ror" || ShiftName == "ROR")
5071     St = ARM_AM::ror;
5072   else if (ShiftName == "rrx" || ShiftName == "RRX")
5073     St = ARM_AM::rrx;
5074   else
5075     return Error(Loc, "illegal shift operator");
5076   Parser.Lex(); // Eat shift type token.
5077 
5078   // rrx stands alone.
5079   Amount = 0;
5080   if (St != ARM_AM::rrx) {
5081     Loc = Parser.getTok().getLoc();
5082     // A '#' and a shift amount.
5083     const AsmToken &HashTok = Parser.getTok();
5084     if (HashTok.isNot(AsmToken::Hash) &&
5085         HashTok.isNot(AsmToken::Dollar))
5086       return Error(HashTok.getLoc(), "'#' expected");
5087     Parser.Lex(); // Eat hash token.
5088 
5089     const MCExpr *Expr;
5090     if (getParser().parseExpression(Expr))
5091       return true;
5092     // Range check the immediate.
5093     // lsl, ror: 0 <= imm <= 31
5094     // lsr, asr: 0 <= imm <= 32
5095     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5096     if (!CE)
5097       return Error(Loc, "shift amount must be an immediate");
5098     int64_t Imm = CE->getValue();
5099     if (Imm < 0 ||
5100         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
5101         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
5102       return Error(Loc, "immediate shift value out of range");
5103     // If <ShiftTy> #0, turn it into a no_shift.
5104     if (Imm == 0)
5105       St = ARM_AM::lsl;
5106     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
5107     if (Imm == 32)
5108       Imm = 0;
5109     Amount = Imm;
5110   }
5111 
5112   return false;
5113 }
5114 
5115 /// parseFPImm - A floating point immediate expression operand.
5116 OperandMatchResultTy
5117 ARMAsmParser::parseFPImm(OperandVector &Operands) {
5118   MCAsmParser &Parser = getParser();
5119   // Anything that can accept a floating point constant as an operand
5120   // needs to go through here, as the regular parseExpression is
5121   // integer only.
5122   //
5123   // This routine still creates a generic Immediate operand, containing
5124   // a bitcast of the 64-bit floating point value. The various operands
5125   // that accept floats can check whether the value is valid for them
5126   // via the standard is*() predicates.
5127 
5128   SMLoc S = Parser.getTok().getLoc();
5129 
5130   if (Parser.getTok().isNot(AsmToken::Hash) &&
5131       Parser.getTok().isNot(AsmToken::Dollar))
5132     return MatchOperand_NoMatch;
5133 
5134   // Disambiguate the VMOV forms that can accept an FP immediate.
5135   // vmov.f32 <sreg>, #imm
5136   // vmov.f64 <dreg>, #imm
5137   // vmov.f32 <dreg>, #imm  @ vector f32x2
5138   // vmov.f32 <qreg>, #imm  @ vector f32x4
5139   //
5140   // There are also the NEON VMOV instructions which expect an
5141   // integer constant. Make sure we don't try to parse an FPImm
5142   // for these:
5143   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
5144   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
5145   bool isVmovf = TyOp.isToken() &&
5146                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64" ||
5147                   TyOp.getToken() == ".f16");
5148   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
5149   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
5150                                          Mnemonic.getToken() == "fconsts");
5151   if (!(isVmovf || isFconst))
5152     return MatchOperand_NoMatch;
5153 
5154   Parser.Lex(); // Eat '#' or '$'.
5155 
5156   // Handle negation, as that still comes through as a separate token.
5157   bool isNegative = false;
5158   if (Parser.getTok().is(AsmToken::Minus)) {
5159     isNegative = true;
5160     Parser.Lex();
5161   }
5162   const AsmToken &Tok = Parser.getTok();
5163   SMLoc Loc = Tok.getLoc();
5164   if (Tok.is(AsmToken::Real) && isVmovf) {
5165     APFloat RealVal(APFloat::IEEEsingle(), Tok.getString());
5166     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
5167     // If we had a '-' in front, toggle the sign bit.
5168     IntVal ^= (uint64_t)isNegative << 31;
5169     Parser.Lex(); // Eat the token.
5170     Operands.push_back(ARMOperand::CreateImm(
5171           MCConstantExpr::create(IntVal, getContext()),
5172           S, Parser.getTok().getLoc()));
5173     return MatchOperand_Success;
5174   }
5175   // Also handle plain integers. Instructions which allow floating point
5176   // immediates also allow a raw encoded 8-bit value.
5177   if (Tok.is(AsmToken::Integer) && isFconst) {
5178     int64_t Val = Tok.getIntVal();
5179     Parser.Lex(); // Eat the token.
5180     if (Val > 255 || Val < 0) {
5181       Error(Loc, "encoded floating point value out of range");
5182       return MatchOperand_ParseFail;
5183     }
5184     float RealVal = ARM_AM::getFPImmFloat(Val);
5185     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
5186 
5187     Operands.push_back(ARMOperand::CreateImm(
5188         MCConstantExpr::create(Val, getContext()), S,
5189         Parser.getTok().getLoc()));
5190     return MatchOperand_Success;
5191   }
5192 
5193   Error(Loc, "invalid floating point immediate");
5194   return MatchOperand_ParseFail;
5195 }
5196 
5197 /// Parse a arm instruction operand.  For now this parses the operand regardless
5198 /// of the mnemonic.
5199 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
5200   MCAsmParser &Parser = getParser();
5201   SMLoc S, E;
5202 
5203   // Check if the current operand has a custom associated parser, if so, try to
5204   // custom parse the operand, or fallback to the general approach.
5205   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
5206   if (ResTy == MatchOperand_Success)
5207     return false;
5208   // If there wasn't a custom match, try the generic matcher below. Otherwise,
5209   // there was a match, but an error occurred, in which case, just return that
5210   // the operand parsing failed.
5211   if (ResTy == MatchOperand_ParseFail)
5212     return true;
5213 
5214   switch (getLexer().getKind()) {
5215   default:
5216     Error(Parser.getTok().getLoc(), "unexpected token in operand");
5217     return true;
5218   case AsmToken::Identifier: {
5219     // If we've seen a branch mnemonic, the next operand must be a label.  This
5220     // is true even if the label is a register name.  So "br r1" means branch to
5221     // label "r1".
5222     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
5223     if (!ExpectLabel) {
5224       if (!tryParseRegisterWithWriteBack(Operands))
5225         return false;
5226       int Res = tryParseShiftRegister(Operands);
5227       if (Res == 0) // success
5228         return false;
5229       else if (Res == -1) // irrecoverable error
5230         return true;
5231       // If this is VMRS, check for the apsr_nzcv operand.
5232       if (Mnemonic == "vmrs" &&
5233           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
5234         S = Parser.getTok().getLoc();
5235         Parser.Lex();
5236         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
5237         return false;
5238       }
5239     }
5240 
5241     // Fall though for the Identifier case that is not a register or a
5242     // special name.
5243   }
5244   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
5245   case AsmToken::Integer: // things like 1f and 2b as a branch targets
5246   case AsmToken::String:  // quoted label names.
5247   case AsmToken::Dot: {   // . as a branch target
5248     // This was not a register so parse other operands that start with an
5249     // identifier (like labels) as expressions and create them as immediates.
5250     const MCExpr *IdVal;
5251     S = Parser.getTok().getLoc();
5252     if (getParser().parseExpression(IdVal))
5253       return true;
5254     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5255     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
5256     return false;
5257   }
5258   case AsmToken::LBrac:
5259     return parseMemory(Operands);
5260   case AsmToken::LCurly:
5261     return parseRegisterList(Operands);
5262   case AsmToken::Dollar:
5263   case AsmToken::Hash: {
5264     // #42 -> immediate.
5265     S = Parser.getTok().getLoc();
5266     Parser.Lex();
5267 
5268     if (Parser.getTok().isNot(AsmToken::Colon)) {
5269       bool isNegative = Parser.getTok().is(AsmToken::Minus);
5270       const MCExpr *ImmVal;
5271       if (getParser().parseExpression(ImmVal))
5272         return true;
5273       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
5274       if (CE) {
5275         int32_t Val = CE->getValue();
5276         if (isNegative && Val == 0)
5277           ImmVal = MCConstantExpr::create(INT32_MIN, getContext());
5278       }
5279       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5280       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
5281 
5282       // There can be a trailing '!' on operands that we want as a separate
5283       // '!' Token operand. Handle that here. For example, the compatibility
5284       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
5285       if (Parser.getTok().is(AsmToken::Exclaim)) {
5286         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
5287                                                    Parser.getTok().getLoc()));
5288         Parser.Lex(); // Eat exclaim token
5289       }
5290       return false;
5291     }
5292     // w/ a ':' after the '#', it's just like a plain ':'.
5293     LLVM_FALLTHROUGH;
5294   }
5295   case AsmToken::Colon: {
5296     S = Parser.getTok().getLoc();
5297     // ":lower16:" and ":upper16:" expression prefixes
5298     // FIXME: Check it's an expression prefix,
5299     // e.g. (FOO - :lower16:BAR) isn't legal.
5300     ARMMCExpr::VariantKind RefKind;
5301     if (parsePrefix(RefKind))
5302       return true;
5303 
5304     const MCExpr *SubExprVal;
5305     if (getParser().parseExpression(SubExprVal))
5306       return true;
5307 
5308     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
5309                                               getContext());
5310     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5311     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
5312     return false;
5313   }
5314   case AsmToken::Equal: {
5315     S = Parser.getTok().getLoc();
5316     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
5317       return Error(S, "unexpected token in operand");
5318     Parser.Lex(); // Eat '='
5319     const MCExpr *SubExprVal;
5320     if (getParser().parseExpression(SubExprVal))
5321       return true;
5322     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5323 
5324     // execute-only: we assume that assembly programmers know what they are
5325     // doing and allow literal pool creation here
5326     Operands.push_back(ARMOperand::CreateConstantPoolImm(SubExprVal, S, E));
5327     return false;
5328   }
5329   }
5330 }
5331 
5332 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
5333 //  :lower16: and :upper16:.
5334 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
5335   MCAsmParser &Parser = getParser();
5336   RefKind = ARMMCExpr::VK_ARM_None;
5337 
5338   // consume an optional '#' (GNU compatibility)
5339   if (getLexer().is(AsmToken::Hash))
5340     Parser.Lex();
5341 
5342   // :lower16: and :upper16: modifiers
5343   assert(getLexer().is(AsmToken::Colon) && "expected a :");
5344   Parser.Lex(); // Eat ':'
5345 
5346   if (getLexer().isNot(AsmToken::Identifier)) {
5347     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
5348     return true;
5349   }
5350 
5351   enum {
5352     COFF = (1 << MCObjectFileInfo::IsCOFF),
5353     ELF = (1 << MCObjectFileInfo::IsELF),
5354     MACHO = (1 << MCObjectFileInfo::IsMachO),
5355     WASM = (1 << MCObjectFileInfo::IsWasm),
5356   };
5357   static const struct PrefixEntry {
5358     const char *Spelling;
5359     ARMMCExpr::VariantKind VariantKind;
5360     uint8_t SupportedFormats;
5361   } PrefixEntries[] = {
5362     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
5363     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
5364   };
5365 
5366   StringRef IDVal = Parser.getTok().getIdentifier();
5367 
5368   const auto &Prefix =
5369       std::find_if(std::begin(PrefixEntries), std::end(PrefixEntries),
5370                    [&IDVal](const PrefixEntry &PE) {
5371                       return PE.Spelling == IDVal;
5372                    });
5373   if (Prefix == std::end(PrefixEntries)) {
5374     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
5375     return true;
5376   }
5377 
5378   uint8_t CurrentFormat;
5379   switch (getContext().getObjectFileInfo()->getObjectFileType()) {
5380   case MCObjectFileInfo::IsMachO:
5381     CurrentFormat = MACHO;
5382     break;
5383   case MCObjectFileInfo::IsELF:
5384     CurrentFormat = ELF;
5385     break;
5386   case MCObjectFileInfo::IsCOFF:
5387     CurrentFormat = COFF;
5388     break;
5389   case MCObjectFileInfo::IsWasm:
5390     CurrentFormat = WASM;
5391     break;
5392   }
5393 
5394   if (~Prefix->SupportedFormats & CurrentFormat) {
5395     Error(Parser.getTok().getLoc(),
5396           "cannot represent relocation in the current file format");
5397     return true;
5398   }
5399 
5400   RefKind = Prefix->VariantKind;
5401   Parser.Lex();
5402 
5403   if (getLexer().isNot(AsmToken::Colon)) {
5404     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
5405     return true;
5406   }
5407   Parser.Lex(); // Eat the last ':'
5408 
5409   return false;
5410 }
5411 
5412 /// \brief Given a mnemonic, split out possible predication code and carry
5413 /// setting letters to form a canonical mnemonic and flags.
5414 //
5415 // FIXME: Would be nice to autogen this.
5416 // FIXME: This is a bit of a maze of special cases.
5417 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
5418                                       unsigned &PredicationCode,
5419                                       bool &CarrySetting,
5420                                       unsigned &ProcessorIMod,
5421                                       StringRef &ITMask) {
5422   PredicationCode = ARMCC::AL;
5423   CarrySetting = false;
5424   ProcessorIMod = 0;
5425 
5426   // Ignore some mnemonics we know aren't predicated forms.
5427   //
5428   // FIXME: Would be nice to autogen this.
5429   if ((Mnemonic == "movs" && isThumb()) ||
5430       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
5431       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
5432       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
5433       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
5434       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
5435       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
5436       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
5437       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
5438       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
5439       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
5440       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
5441       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
5442       Mnemonic.startswith("vsel") || Mnemonic == "vins" || Mnemonic == "vmovx" ||
5443       Mnemonic == "bxns"  || Mnemonic == "blxns")
5444     return Mnemonic;
5445 
5446   // First, split out any predication code. Ignore mnemonics we know aren't
5447   // predicated but do have a carry-set and so weren't caught above.
5448   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
5449       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
5450       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
5451       Mnemonic != "sbcs" && Mnemonic != "rscs") {
5452     unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
5453       .Case("eq", ARMCC::EQ)
5454       .Case("ne", ARMCC::NE)
5455       .Case("hs", ARMCC::HS)
5456       .Case("cs", ARMCC::HS)
5457       .Case("lo", ARMCC::LO)
5458       .Case("cc", ARMCC::LO)
5459       .Case("mi", ARMCC::MI)
5460       .Case("pl", ARMCC::PL)
5461       .Case("vs", ARMCC::VS)
5462       .Case("vc", ARMCC::VC)
5463       .Case("hi", ARMCC::HI)
5464       .Case("ls", ARMCC::LS)
5465       .Case("ge", ARMCC::GE)
5466       .Case("lt", ARMCC::LT)
5467       .Case("gt", ARMCC::GT)
5468       .Case("le", ARMCC::LE)
5469       .Case("al", ARMCC::AL)
5470       .Default(~0U);
5471     if (CC != ~0U) {
5472       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
5473       PredicationCode = CC;
5474     }
5475   }
5476 
5477   // Next, determine if we have a carry setting bit. We explicitly ignore all
5478   // the instructions we know end in 's'.
5479   if (Mnemonic.endswith("s") &&
5480       !(Mnemonic == "cps" || Mnemonic == "mls" ||
5481         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
5482         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
5483         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
5484         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
5485         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
5486         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
5487         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
5488         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
5489         Mnemonic == "bxns" || Mnemonic == "blxns" ||
5490         (Mnemonic == "movs" && isThumb()))) {
5491     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
5492     CarrySetting = true;
5493   }
5494 
5495   // The "cps" instruction can have a interrupt mode operand which is glued into
5496   // the mnemonic. Check if this is the case, split it and parse the imod op
5497   if (Mnemonic.startswith("cps")) {
5498     // Split out any imod code.
5499     unsigned IMod =
5500       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
5501       .Case("ie", ARM_PROC::IE)
5502       .Case("id", ARM_PROC::ID)
5503       .Default(~0U);
5504     if (IMod != ~0U) {
5505       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
5506       ProcessorIMod = IMod;
5507     }
5508   }
5509 
5510   // The "it" instruction has the condition mask on the end of the mnemonic.
5511   if (Mnemonic.startswith("it")) {
5512     ITMask = Mnemonic.slice(2, Mnemonic.size());
5513     Mnemonic = Mnemonic.slice(0, 2);
5514   }
5515 
5516   return Mnemonic;
5517 }
5518 
5519 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
5520 /// inclusion of carry set or predication code operands.
5521 //
5522 // FIXME: It would be nice to autogen this.
5523 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
5524                                          bool &CanAcceptCarrySet,
5525                                          bool &CanAcceptPredicationCode) {
5526   CanAcceptCarrySet =
5527       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5528       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
5529       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
5530       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
5531       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
5532       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
5533       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
5534       (!isThumb() &&
5535        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
5536         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
5537 
5538   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
5539       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
5540       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
5541       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
5542       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
5543       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
5544       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
5545       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
5546       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
5547       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
5548       (FullInst.startswith("vmull") && FullInst.endswith(".p64")) ||
5549       Mnemonic == "vmovx" || Mnemonic == "vins") {
5550     // These mnemonics are never predicable
5551     CanAcceptPredicationCode = false;
5552   } else if (!isThumb()) {
5553     // Some instructions are only predicable in Thumb mode
5554     CanAcceptPredicationCode =
5555         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
5556         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
5557         Mnemonic != "dmb" && Mnemonic != "dsb" && Mnemonic != "isb" &&
5558         Mnemonic != "pld" && Mnemonic != "pli" && Mnemonic != "pldw" &&
5559         Mnemonic != "ldc2" && Mnemonic != "ldc2l" && Mnemonic != "stc2" &&
5560         Mnemonic != "stc2l" && !Mnemonic.startswith("rfe") &&
5561         !Mnemonic.startswith("srs");
5562   } else if (isThumbOne()) {
5563     if (hasV6MOps())
5564       CanAcceptPredicationCode = Mnemonic != "movs";
5565     else
5566       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
5567   } else
5568     CanAcceptPredicationCode = true;
5569 }
5570 
5571 // \brief Some Thumb instructions have two operand forms that are not
5572 // available as three operand, convert to two operand form if possible.
5573 //
5574 // FIXME: We would really like to be able to tablegen'erate this.
5575 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
5576                                                  bool CarrySetting,
5577                                                  OperandVector &Operands) {
5578   if (Operands.size() != 6)
5579     return;
5580 
5581   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5582         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
5583   if (!Op3.isReg() || !Op4.isReg())
5584     return;
5585 
5586   auto Op3Reg = Op3.getReg();
5587   auto Op4Reg = Op4.getReg();
5588 
5589   // For most Thumb2 cases we just generate the 3 operand form and reduce
5590   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
5591   // won't accept SP or PC so we do the transformation here taking care
5592   // with immediate range in the 'add sp, sp #imm' case.
5593   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
5594   if (isThumbTwo()) {
5595     if (Mnemonic != "add")
5596       return;
5597     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
5598                         (Op5.isReg() && Op5.getReg() == ARM::PC);
5599     if (!TryTransform) {
5600       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
5601                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
5602                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
5603                        Op5.isImm() && !Op5.isImm0_508s4());
5604     }
5605     if (!TryTransform)
5606       return;
5607   } else if (!isThumbOne())
5608     return;
5609 
5610   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
5611         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5612         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
5613         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
5614     return;
5615 
5616   // If first 2 operands of a 3 operand instruction are the same
5617   // then transform to 2 operand version of the same instruction
5618   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
5619   bool Transform = Op3Reg == Op4Reg;
5620 
5621   // For communtative operations, we might be able to transform if we swap
5622   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
5623   // as tADDrsp.
5624   const ARMOperand *LastOp = &Op5;
5625   bool Swap = false;
5626   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
5627       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
5628        Mnemonic == "and" || Mnemonic == "eor" ||
5629        Mnemonic == "adc" || Mnemonic == "orr")) {
5630     Swap = true;
5631     LastOp = &Op4;
5632     Transform = true;
5633   }
5634 
5635   // If both registers are the same then remove one of them from
5636   // the operand list, with certain exceptions.
5637   if (Transform) {
5638     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
5639     // 2 operand forms don't exist.
5640     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
5641         LastOp->isReg())
5642       Transform = false;
5643 
5644     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
5645     // 3-bits because the ARMARM says not to.
5646     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
5647       Transform = false;
5648   }
5649 
5650   if (Transform) {
5651     if (Swap)
5652       std::swap(Op4, Op5);
5653     Operands.erase(Operands.begin() + 3);
5654   }
5655 }
5656 
5657 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
5658                                           OperandVector &Operands) {
5659   // FIXME: This is all horribly hacky. We really need a better way to deal
5660   // with optional operands like this in the matcher table.
5661 
5662   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
5663   // another does not. Specifically, the MOVW instruction does not. So we
5664   // special case it here and remove the defaulted (non-setting) cc_out
5665   // operand if that's the instruction we're trying to match.
5666   //
5667   // We do this as post-processing of the explicit operands rather than just
5668   // conditionally adding the cc_out in the first place because we need
5669   // to check the type of the parsed immediate operand.
5670   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
5671       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
5672       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
5673       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5674     return true;
5675 
5676   // Register-register 'add' for thumb does not have a cc_out operand
5677   // when there are only two register operands.
5678   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
5679       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5680       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5681       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5682     return true;
5683   // Register-register 'add' for thumb does not have a cc_out operand
5684   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
5685   // have to check the immediate range here since Thumb2 has a variant
5686   // that can handle a different range and has a cc_out operand.
5687   if (((isThumb() && Mnemonic == "add") ||
5688        (isThumbTwo() && Mnemonic == "sub")) &&
5689       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5690       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5691       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
5692       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5693       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
5694        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
5695     return true;
5696   // For Thumb2, add/sub immediate does not have a cc_out operand for the
5697   // imm0_4095 variant. That's the least-preferred variant when
5698   // selecting via the generic "add" mnemonic, so to know that we
5699   // should remove the cc_out operand, we have to explicitly check that
5700   // it's not one of the other variants. Ugh.
5701   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
5702       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5703       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5704       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5705     // Nest conditions rather than one big 'if' statement for readability.
5706     //
5707     // If both registers are low, we're in an IT block, and the immediate is
5708     // in range, we should use encoding T1 instead, which has a cc_out.
5709     if (inITBlock() &&
5710         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
5711         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
5712         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
5713       return false;
5714     // Check against T3. If the second register is the PC, this is an
5715     // alternate form of ADR, which uses encoding T4, so check for that too.
5716     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
5717         static_cast<ARMOperand &>(*Operands[5]).isT2SOImm())
5718       return false;
5719 
5720     // Otherwise, we use encoding T4, which does not have a cc_out
5721     // operand.
5722     return true;
5723   }
5724 
5725   // The thumb2 multiply instruction doesn't have a CCOut register, so
5726   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
5727   // use the 16-bit encoding or not.
5728   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
5729       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5730       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5731       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5732       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
5733       // If the registers aren't low regs, the destination reg isn't the
5734       // same as one of the source regs, or the cc_out operand is zero
5735       // outside of an IT block, we have to use the 32-bit encoding, so
5736       // remove the cc_out operand.
5737       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5738        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5739        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
5740        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5741                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
5742                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5743                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
5744     return true;
5745 
5746   // Also check the 'mul' syntax variant that doesn't specify an explicit
5747   // destination register.
5748   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
5749       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5750       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5751       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5752       // If the registers aren't low regs  or the cc_out operand is zero
5753       // outside of an IT block, we have to use the 32-bit encoding, so
5754       // remove the cc_out operand.
5755       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5756        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5757        !inITBlock()))
5758     return true;
5759 
5760 
5761 
5762   // Register-register 'add/sub' for thumb does not have a cc_out operand
5763   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
5764   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
5765   // right, this will result in better diagnostics (which operand is off)
5766   // anyway.
5767   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
5768       (Operands.size() == 5 || Operands.size() == 6) &&
5769       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5770       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
5771       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5772       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
5773        (Operands.size() == 6 &&
5774         static_cast<ARMOperand &>(*Operands[5]).isImm())))
5775     return true;
5776 
5777   return false;
5778 }
5779 
5780 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
5781                                               OperandVector &Operands) {
5782   // VRINT{Z, R, X} have a predicate operand in VFP, but not in NEON
5783   unsigned RegIdx = 3;
5784   if ((Mnemonic == "vrintz" || Mnemonic == "vrintx" || Mnemonic == "vrintr") &&
5785       (static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32" ||
5786        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f16")) {
5787     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
5788         (static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32" ||
5789          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f16"))
5790       RegIdx = 4;
5791 
5792     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
5793         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
5794              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
5795          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
5796              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
5797       return true;
5798   }
5799   return false;
5800 }
5801 
5802 static bool isDataTypeToken(StringRef Tok) {
5803   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
5804     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
5805     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
5806     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
5807     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
5808     Tok == ".f" || Tok == ".d";
5809 }
5810 
5811 // FIXME: This bit should probably be handled via an explicit match class
5812 // in the .td files that matches the suffix instead of having it be
5813 // a literal string token the way it is now.
5814 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
5815   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
5816 }
5817 static void applyMnemonicAliases(StringRef &Mnemonic, uint64_t Features,
5818                                  unsigned VariantID);
5819 
5820 static bool RequiresVFPRegListValidation(StringRef Inst,
5821                                          bool &AcceptSinglePrecisionOnly,
5822                                          bool &AcceptDoublePrecisionOnly) {
5823   if (Inst.size() < 7)
5824     return false;
5825 
5826   if (Inst.startswith("fldm") || Inst.startswith("fstm")) {
5827     StringRef AddressingMode = Inst.substr(4, 2);
5828     if (AddressingMode == "ia" || AddressingMode == "db" ||
5829         AddressingMode == "ea" || AddressingMode == "fd") {
5830       AcceptSinglePrecisionOnly = Inst[6] == 's';
5831       AcceptDoublePrecisionOnly = Inst[6] == 'd' || Inst[6] == 'x';
5832       return true;
5833     }
5834   }
5835 
5836   return false;
5837 }
5838 
5839 /// Parse an arm instruction mnemonic followed by its operands.
5840 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
5841                                     SMLoc NameLoc, OperandVector &Operands) {
5842   MCAsmParser &Parser = getParser();
5843   // FIXME: Can this be done via tablegen in some fashion?
5844   bool RequireVFPRegisterListCheck;
5845   bool AcceptSinglePrecisionOnly;
5846   bool AcceptDoublePrecisionOnly;
5847   RequireVFPRegisterListCheck =
5848     RequiresVFPRegListValidation(Name, AcceptSinglePrecisionOnly,
5849                                  AcceptDoublePrecisionOnly);
5850 
5851   // Apply mnemonic aliases before doing anything else, as the destination
5852   // mnemonic may include suffices and we want to handle them normally.
5853   // The generic tblgen'erated code does this later, at the start of
5854   // MatchInstructionImpl(), but that's too late for aliases that include
5855   // any sort of suffix.
5856   uint64_t AvailableFeatures = getAvailableFeatures();
5857   unsigned AssemblerDialect = getParser().getAssemblerDialect();
5858   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
5859 
5860   // First check for the ARM-specific .req directive.
5861   if (Parser.getTok().is(AsmToken::Identifier) &&
5862       Parser.getTok().getIdentifier() == ".req") {
5863     parseDirectiveReq(Name, NameLoc);
5864     // We always return 'error' for this, as we're done with this
5865     // statement and don't need to match the 'instruction."
5866     return true;
5867   }
5868 
5869   // Create the leading tokens for the mnemonic, split by '.' characters.
5870   size_t Start = 0, Next = Name.find('.');
5871   StringRef Mnemonic = Name.slice(Start, Next);
5872 
5873   // Split out the predication code and carry setting flag from the mnemonic.
5874   unsigned PredicationCode;
5875   unsigned ProcessorIMod;
5876   bool CarrySetting;
5877   StringRef ITMask;
5878   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
5879                            ProcessorIMod, ITMask);
5880 
5881   // In Thumb1, only the branch (B) instruction can be predicated.
5882   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
5883     return Error(NameLoc, "conditional execution not supported in Thumb1");
5884   }
5885 
5886   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
5887 
5888   // Handle the IT instruction ITMask. Convert it to a bitmask. This
5889   // is the mask as it will be for the IT encoding if the conditional
5890   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
5891   // where the conditional bit0 is zero, the instruction post-processing
5892   // will adjust the mask accordingly.
5893   if (Mnemonic == "it") {
5894     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
5895     if (ITMask.size() > 3) {
5896       return Error(Loc, "too many conditions on IT instruction");
5897     }
5898     unsigned Mask = 8;
5899     for (unsigned i = ITMask.size(); i != 0; --i) {
5900       char pos = ITMask[i - 1];
5901       if (pos != 't' && pos != 'e') {
5902         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
5903       }
5904       Mask >>= 1;
5905       if (ITMask[i - 1] == 't')
5906         Mask |= 8;
5907     }
5908     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
5909   }
5910 
5911   // FIXME: This is all a pretty gross hack. We should automatically handle
5912   // optional operands like this via tblgen.
5913 
5914   // Next, add the CCOut and ConditionCode operands, if needed.
5915   //
5916   // For mnemonics which can ever incorporate a carry setting bit or predication
5917   // code, our matching model involves us always generating CCOut and
5918   // ConditionCode operands to match the mnemonic "as written" and then we let
5919   // the matcher deal with finding the right instruction or generating an
5920   // appropriate error.
5921   bool CanAcceptCarrySet, CanAcceptPredicationCode;
5922   getMnemonicAcceptInfo(Mnemonic, Name, CanAcceptCarrySet, CanAcceptPredicationCode);
5923 
5924   // If we had a carry-set on an instruction that can't do that, issue an
5925   // error.
5926   if (!CanAcceptCarrySet && CarrySetting) {
5927     return Error(NameLoc, "instruction '" + Mnemonic +
5928                  "' can not set flags, but 's' suffix specified");
5929   }
5930   // If we had a predication code on an instruction that can't do that, issue an
5931   // error.
5932   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
5933     return Error(NameLoc, "instruction '" + Mnemonic +
5934                  "' is not predicable, but condition code specified");
5935   }
5936 
5937   // Add the carry setting operand, if necessary.
5938   if (CanAcceptCarrySet) {
5939     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
5940     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
5941                                                Loc));
5942   }
5943 
5944   // Add the predication code operand, if necessary.
5945   if (CanAcceptPredicationCode) {
5946     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
5947                                       CarrySetting);
5948     Operands.push_back(ARMOperand::CreateCondCode(
5949                          ARMCC::CondCodes(PredicationCode), Loc));
5950   }
5951 
5952   // Add the processor imod operand, if necessary.
5953   if (ProcessorIMod) {
5954     Operands.push_back(ARMOperand::CreateImm(
5955           MCConstantExpr::create(ProcessorIMod, getContext()),
5956                                  NameLoc, NameLoc));
5957   } else if (Mnemonic == "cps" && isMClass()) {
5958     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
5959   }
5960 
5961   // Add the remaining tokens in the mnemonic.
5962   while (Next != StringRef::npos) {
5963     Start = Next;
5964     Next = Name.find('.', Start + 1);
5965     StringRef ExtraToken = Name.slice(Start, Next);
5966 
5967     // Some NEON instructions have an optional datatype suffix that is
5968     // completely ignored. Check for that.
5969     if (isDataTypeToken(ExtraToken) &&
5970         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
5971       continue;
5972 
5973     // For for ARM mode generate an error if the .n qualifier is used.
5974     if (ExtraToken == ".n" && !isThumb()) {
5975       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5976       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
5977                    "arm mode");
5978     }
5979 
5980     // The .n qualifier is always discarded as that is what the tables
5981     // and matcher expect.  In ARM mode the .w qualifier has no effect,
5982     // so discard it to avoid errors that can be caused by the matcher.
5983     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
5984       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5985       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
5986     }
5987   }
5988 
5989   // Read the remaining operands.
5990   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5991     // Read the first operand.
5992     if (parseOperand(Operands, Mnemonic)) {
5993       return true;
5994     }
5995 
5996     while (parseOptionalToken(AsmToken::Comma)) {
5997       // Parse and remember the operand.
5998       if (parseOperand(Operands, Mnemonic)) {
5999         return true;
6000       }
6001     }
6002   }
6003 
6004   if (parseToken(AsmToken::EndOfStatement, "unexpected token in argument list"))
6005     return true;
6006 
6007   if (RequireVFPRegisterListCheck) {
6008     ARMOperand &Op = static_cast<ARMOperand &>(*Operands.back());
6009     if (AcceptSinglePrecisionOnly && !Op.isSPRRegList())
6010       return Error(Op.getStartLoc(),
6011                    "VFP/Neon single precision register expected");
6012     if (AcceptDoublePrecisionOnly && !Op.isDPRRegList())
6013       return Error(Op.getStartLoc(),
6014                    "VFP/Neon double precision register expected");
6015   }
6016 
6017   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
6018 
6019   // Some instructions, mostly Thumb, have forms for the same mnemonic that
6020   // do and don't have a cc_out optional-def operand. With some spot-checks
6021   // of the operand list, we can figure out which variant we're trying to
6022   // parse and adjust accordingly before actually matching. We shouldn't ever
6023   // try to remove a cc_out operand that was explicitly set on the
6024   // mnemonic, of course (CarrySetting == true). Reason number #317 the
6025   // table driven matcher doesn't fit well with the ARM instruction set.
6026   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
6027     Operands.erase(Operands.begin() + 1);
6028 
6029   // Some instructions have the same mnemonic, but don't always
6030   // have a predicate. Distinguish them here and delete the
6031   // predicate if needed.
6032   if (shouldOmitPredicateOperand(Mnemonic, Operands))
6033     Operands.erase(Operands.begin() + 1);
6034 
6035   // ARM mode 'blx' need special handling, as the register operand version
6036   // is predicable, but the label operand version is not. So, we can't rely
6037   // on the Mnemonic based checking to correctly figure out when to put
6038   // a k_CondCode operand in the list. If we're trying to match the label
6039   // version, remove the k_CondCode operand here.
6040   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
6041       static_cast<ARMOperand &>(*Operands[2]).isImm())
6042     Operands.erase(Operands.begin() + 1);
6043 
6044   // Adjust operands of ldrexd/strexd to MCK_GPRPair.
6045   // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
6046   // a single GPRPair reg operand is used in the .td file to replace the two
6047   // GPRs. However, when parsing from asm, the two GRPs cannot be automatically
6048   // expressed as a GPRPair, so we have to manually merge them.
6049   // FIXME: We would really like to be able to tablegen'erate this.
6050   if (!isThumb() && Operands.size() > 4 &&
6051       (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
6052        Mnemonic == "stlexd")) {
6053     bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
6054     unsigned Idx = isLoad ? 2 : 3;
6055     ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
6056     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
6057 
6058     const MCRegisterClass& MRC = MRI->getRegClass(ARM::GPRRegClassID);
6059     // Adjust only if Op1 and Op2 are GPRs.
6060     if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
6061         MRC.contains(Op2.getReg())) {
6062       unsigned Reg1 = Op1.getReg();
6063       unsigned Reg2 = Op2.getReg();
6064       unsigned Rt = MRI->getEncodingValue(Reg1);
6065       unsigned Rt2 = MRI->getEncodingValue(Reg2);
6066 
6067       // Rt2 must be Rt + 1 and Rt must be even.
6068       if (Rt + 1 != Rt2 || (Rt & 1)) {
6069         return Error(Op2.getStartLoc(),
6070                      isLoad ? "destination operands must be sequential"
6071                             : "source operands must be sequential");
6072       }
6073       unsigned NewReg = MRI->getMatchingSuperReg(Reg1, ARM::gsub_0,
6074           &(MRI->getRegClass(ARM::GPRPairRegClassID)));
6075       Operands[Idx] =
6076           ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
6077       Operands.erase(Operands.begin() + Idx + 1);
6078     }
6079   }
6080 
6081   // GNU Assembler extension (compatibility)
6082   if ((Mnemonic == "ldrd" || Mnemonic == "strd")) {
6083     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
6084     ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6085     if (Op3.isMem()) {
6086       assert(Op2.isReg() && "expected register argument");
6087 
6088       unsigned SuperReg = MRI->getMatchingSuperReg(
6089           Op2.getReg(), ARM::gsub_0, &MRI->getRegClass(ARM::GPRPairRegClassID));
6090 
6091       assert(SuperReg && "expected register pair");
6092 
6093       unsigned PairedReg = MRI->getSubReg(SuperReg, ARM::gsub_1);
6094 
6095       Operands.insert(
6096           Operands.begin() + 3,
6097           ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
6098     }
6099   }
6100 
6101   // FIXME: As said above, this is all a pretty gross hack.  This instruction
6102   // does not fit with other "subs" and tblgen.
6103   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
6104   // so the Mnemonic is the original name "subs" and delete the predicate
6105   // operand so it will match the table entry.
6106   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
6107       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6108       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
6109       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6110       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
6111       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
6112     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
6113     Operands.erase(Operands.begin() + 1);
6114   }
6115   return false;
6116 }
6117 
6118 // Validate context-sensitive operand constraints.
6119 
6120 // return 'true' if register list contains non-low GPR registers,
6121 // 'false' otherwise. If Reg is in the register list or is HiReg, set
6122 // 'containsReg' to true.
6123 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
6124                                  unsigned Reg, unsigned HiReg,
6125                                  bool &containsReg) {
6126   containsReg = false;
6127   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
6128     unsigned OpReg = Inst.getOperand(i).getReg();
6129     if (OpReg == Reg)
6130       containsReg = true;
6131     // Anything other than a low register isn't legal here.
6132     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
6133       return true;
6134   }
6135   return false;
6136 }
6137 
6138 // Check if the specified regisgter is in the register list of the inst,
6139 // starting at the indicated operand number.
6140 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
6141   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
6142     unsigned OpReg = Inst.getOperand(i).getReg();
6143     if (OpReg == Reg)
6144       return true;
6145   }
6146   return false;
6147 }
6148 
6149 // Return true if instruction has the interesting property of being
6150 // allowed in IT blocks, but not being predicable.
6151 static bool instIsBreakpoint(const MCInst &Inst) {
6152     return Inst.getOpcode() == ARM::tBKPT ||
6153            Inst.getOpcode() == ARM::BKPT ||
6154            Inst.getOpcode() == ARM::tHLT ||
6155            Inst.getOpcode() == ARM::HLT;
6156 
6157 }
6158 
6159 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
6160                                        const OperandVector &Operands,
6161                                        unsigned ListNo, bool IsARPop) {
6162   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6163   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6164 
6165   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6166   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
6167   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6168 
6169   if (!IsARPop && ListContainsSP)
6170     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6171                  "SP may not be in the register list");
6172   else if (ListContainsPC && ListContainsLR)
6173     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6174                  "PC and LR may not be in the register list simultaneously");
6175   return false;
6176 }
6177 
6178 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
6179                                        const OperandVector &Operands,
6180                                        unsigned ListNo) {
6181   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6182   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6183 
6184   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6185   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6186 
6187   if (ListContainsSP && ListContainsPC)
6188     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6189                  "SP and PC may not be in the register list");
6190   else if (ListContainsSP)
6191     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6192                  "SP may not be in the register list");
6193   else if (ListContainsPC)
6194     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6195                  "PC may not be in the register list");
6196   return false;
6197 }
6198 
6199 // FIXME: We would really like to be able to tablegen'erate this.
6200 bool ARMAsmParser::validateInstruction(MCInst &Inst,
6201                                        const OperandVector &Operands) {
6202   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
6203   SMLoc Loc = Operands[0]->getStartLoc();
6204 
6205   // Check the IT block state first.
6206   // NOTE: BKPT and HLT instructions have the interesting property of being
6207   // allowed in IT blocks, but not being predicable. They just always execute.
6208   if (inITBlock() && !instIsBreakpoint(Inst)) {
6209     // The instruction must be predicable.
6210     if (!MCID.isPredicable())
6211       return Error(Loc, "instructions in IT block must be predicable");
6212     unsigned Cond = Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm();
6213     if (Cond != currentITCond()) {
6214       // Find the condition code Operand to get its SMLoc information.
6215       SMLoc CondLoc;
6216       for (unsigned I = 1; I < Operands.size(); ++I)
6217         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
6218           CondLoc = Operands[I]->getStartLoc();
6219       return Error(CondLoc, "incorrect condition in IT block; got '" +
6220                    StringRef(ARMCondCodeToString(ARMCC::CondCodes(Cond))) +
6221                    "', but expected '" +
6222                    ARMCondCodeToString(ARMCC::CondCodes(currentITCond())) + "'");
6223     }
6224   // Check for non-'al' condition codes outside of the IT block.
6225   } else if (isThumbTwo() && MCID.isPredicable() &&
6226              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6227              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
6228              Inst.getOpcode() != ARM::t2Bcc) {
6229     return Error(Loc, "predicated instructions must be in IT block");
6230   } else if (!isThumb() && !useImplicitITARM() && MCID.isPredicable() &&
6231              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6232                  ARMCC::AL) {
6233     return Warning(Loc, "predicated instructions should be in IT block");
6234   }
6235 
6236   // PC-setting instructions in an IT block, but not the last instruction of
6237   // the block, are UNPREDICTABLE.
6238   if (inExplicitITBlock() && !lastInITBlock() && isITBlockTerminator(Inst)) {
6239     return Error(Loc, "instruction must be outside of IT block or the last instruction in an IT block");
6240   }
6241 
6242   const unsigned Opcode = Inst.getOpcode();
6243   switch (Opcode) {
6244   case ARM::LDRD:
6245   case ARM::LDRD_PRE:
6246   case ARM::LDRD_POST: {
6247     const unsigned RtReg = Inst.getOperand(0).getReg();
6248 
6249     // Rt can't be R14.
6250     if (RtReg == ARM::LR)
6251       return Error(Operands[3]->getStartLoc(),
6252                    "Rt can't be R14");
6253 
6254     const unsigned Rt = MRI->getEncodingValue(RtReg);
6255     // Rt must be even-numbered.
6256     if ((Rt & 1) == 1)
6257       return Error(Operands[3]->getStartLoc(),
6258                    "Rt must be even-numbered");
6259 
6260     // Rt2 must be Rt + 1.
6261     const unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6262     if (Rt2 != Rt + 1)
6263       return Error(Operands[3]->getStartLoc(),
6264                    "destination operands must be sequential");
6265 
6266     if (Opcode == ARM::LDRD_PRE || Opcode == ARM::LDRD_POST) {
6267       const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
6268       // For addressing modes with writeback, the base register needs to be
6269       // different from the destination registers.
6270       if (Rn == Rt || Rn == Rt2)
6271         return Error(Operands[3]->getStartLoc(),
6272                      "base register needs to be different from destination "
6273                      "registers");
6274     }
6275 
6276     return false;
6277   }
6278   case ARM::t2LDRDi8:
6279   case ARM::t2LDRD_PRE:
6280   case ARM::t2LDRD_POST: {
6281     // Rt2 must be different from Rt.
6282     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6283     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6284     if (Rt2 == Rt)
6285       return Error(Operands[3]->getStartLoc(),
6286                    "destination operands can't be identical");
6287     return false;
6288   }
6289   case ARM::t2BXJ: {
6290     const unsigned RmReg = Inst.getOperand(0).getReg();
6291     // Rm = SP is no longer unpredictable in v8-A
6292     if (RmReg == ARM::SP && !hasV8Ops())
6293       return Error(Operands[2]->getStartLoc(),
6294                    "r13 (SP) is an unpredictable operand to BXJ");
6295     return false;
6296   }
6297   case ARM::STRD: {
6298     // Rt2 must be Rt + 1.
6299     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6300     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6301     if (Rt2 != Rt + 1)
6302       return Error(Operands[3]->getStartLoc(),
6303                    "source operands must be sequential");
6304     return false;
6305   }
6306   case ARM::STRD_PRE:
6307   case ARM::STRD_POST: {
6308     // Rt2 must be Rt + 1.
6309     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6310     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6311     if (Rt2 != Rt + 1)
6312       return Error(Operands[3]->getStartLoc(),
6313                    "source operands must be sequential");
6314     return false;
6315   }
6316   case ARM::STR_PRE_IMM:
6317   case ARM::STR_PRE_REG:
6318   case ARM::STR_POST_IMM:
6319   case ARM::STR_POST_REG:
6320   case ARM::STRH_PRE:
6321   case ARM::STRH_POST:
6322   case ARM::STRB_PRE_IMM:
6323   case ARM::STRB_PRE_REG:
6324   case ARM::STRB_POST_IMM:
6325   case ARM::STRB_POST_REG: {
6326     // Rt must be different from Rn.
6327     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6328     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6329 
6330     if (Rt == Rn)
6331       return Error(Operands[3]->getStartLoc(),
6332                    "source register and base register can't be identical");
6333     return false;
6334   }
6335   case ARM::LDR_PRE_IMM:
6336   case ARM::LDR_PRE_REG:
6337   case ARM::LDR_POST_IMM:
6338   case ARM::LDR_POST_REG:
6339   case ARM::LDRH_PRE:
6340   case ARM::LDRH_POST:
6341   case ARM::LDRSH_PRE:
6342   case ARM::LDRSH_POST:
6343   case ARM::LDRB_PRE_IMM:
6344   case ARM::LDRB_PRE_REG:
6345   case ARM::LDRB_POST_IMM:
6346   case ARM::LDRB_POST_REG:
6347   case ARM::LDRSB_PRE:
6348   case ARM::LDRSB_POST: {
6349     // Rt must be different from Rn.
6350     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6351     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6352 
6353     if (Rt == Rn)
6354       return Error(Operands[3]->getStartLoc(),
6355                    "destination register and base register can't be identical");
6356     return false;
6357   }
6358   case ARM::SBFX:
6359   case ARM::UBFX: {
6360     // Width must be in range [1, 32-lsb].
6361     unsigned LSB = Inst.getOperand(2).getImm();
6362     unsigned Widthm1 = Inst.getOperand(3).getImm();
6363     if (Widthm1 >= 32 - LSB)
6364       return Error(Operands[5]->getStartLoc(),
6365                    "bitfield width must be in range [1,32-lsb]");
6366     return false;
6367   }
6368   // Notionally handles ARM::tLDMIA_UPD too.
6369   case ARM::tLDMIA: {
6370     // If we're parsing Thumb2, the .w variant is available and handles
6371     // most cases that are normally illegal for a Thumb1 LDM instruction.
6372     // We'll make the transformation in processInstruction() if necessary.
6373     //
6374     // Thumb LDM instructions are writeback iff the base register is not
6375     // in the register list.
6376     unsigned Rn = Inst.getOperand(0).getReg();
6377     bool HasWritebackToken =
6378         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6379          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
6380     bool ListContainsBase;
6381     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
6382       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
6383                    "registers must be in range r0-r7");
6384     // If we should have writeback, then there should be a '!' token.
6385     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
6386       return Error(Operands[2]->getStartLoc(),
6387                    "writeback operator '!' expected");
6388     // If we should not have writeback, there must not be a '!'. This is
6389     // true even for the 32-bit wide encodings.
6390     if (ListContainsBase && HasWritebackToken)
6391       return Error(Operands[3]->getStartLoc(),
6392                    "writeback operator '!' not allowed when base register "
6393                    "in register list");
6394 
6395     if (validatetLDMRegList(Inst, Operands, 3))
6396       return true;
6397     break;
6398   }
6399   case ARM::LDMIA_UPD:
6400   case ARM::LDMDB_UPD:
6401   case ARM::LDMIB_UPD:
6402   case ARM::LDMDA_UPD:
6403     // ARM variants loading and updating the same register are only officially
6404     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
6405     if (!hasV7Ops())
6406       break;
6407     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6408       return Error(Operands.back()->getStartLoc(),
6409                    "writeback register not allowed in register list");
6410     break;
6411   case ARM::t2LDMIA:
6412   case ARM::t2LDMDB:
6413     if (validatetLDMRegList(Inst, Operands, 3))
6414       return true;
6415     break;
6416   case ARM::t2STMIA:
6417   case ARM::t2STMDB:
6418     if (validatetSTMRegList(Inst, Operands, 3))
6419       return true;
6420     break;
6421   case ARM::t2LDMIA_UPD:
6422   case ARM::t2LDMDB_UPD:
6423   case ARM::t2STMIA_UPD:
6424   case ARM::t2STMDB_UPD: {
6425     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6426       return Error(Operands.back()->getStartLoc(),
6427                    "writeback register not allowed in register list");
6428 
6429     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
6430       if (validatetLDMRegList(Inst, Operands, 3))
6431         return true;
6432     } else {
6433       if (validatetSTMRegList(Inst, Operands, 3))
6434         return true;
6435     }
6436     break;
6437   }
6438   case ARM::sysLDMIA_UPD:
6439   case ARM::sysLDMDA_UPD:
6440   case ARM::sysLDMDB_UPD:
6441   case ARM::sysLDMIB_UPD:
6442     if (!listContainsReg(Inst, 3, ARM::PC))
6443       return Error(Operands[4]->getStartLoc(),
6444                    "writeback register only allowed on system LDM "
6445                    "if PC in register-list");
6446     break;
6447   case ARM::sysSTMIA_UPD:
6448   case ARM::sysSTMDA_UPD:
6449   case ARM::sysSTMDB_UPD:
6450   case ARM::sysSTMIB_UPD:
6451     return Error(Operands[2]->getStartLoc(),
6452                  "system STM cannot have writeback register");
6453   case ARM::tMUL: {
6454     // The second source operand must be the same register as the destination
6455     // operand.
6456     //
6457     // In this case, we must directly check the parsed operands because the
6458     // cvtThumbMultiply() function is written in such a way that it guarantees
6459     // this first statement is always true for the new Inst.  Essentially, the
6460     // destination is unconditionally copied into the second source operand
6461     // without checking to see if it matches what we actually parsed.
6462     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
6463                                  ((ARMOperand &)*Operands[5]).getReg()) &&
6464         (((ARMOperand &)*Operands[3]).getReg() !=
6465          ((ARMOperand &)*Operands[4]).getReg())) {
6466       return Error(Operands[3]->getStartLoc(),
6467                    "destination register must match source register");
6468     }
6469     break;
6470   }
6471   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
6472   // so only issue a diagnostic for thumb1. The instructions will be
6473   // switched to the t2 encodings in processInstruction() if necessary.
6474   case ARM::tPOP: {
6475     bool ListContainsBase;
6476     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
6477         !isThumbTwo())
6478       return Error(Operands[2]->getStartLoc(),
6479                    "registers must be in range r0-r7 or pc");
6480     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
6481       return true;
6482     break;
6483   }
6484   case ARM::tPUSH: {
6485     bool ListContainsBase;
6486     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
6487         !isThumbTwo())
6488       return Error(Operands[2]->getStartLoc(),
6489                    "registers must be in range r0-r7 or lr");
6490     if (validatetSTMRegList(Inst, Operands, 2))
6491       return true;
6492     break;
6493   }
6494   case ARM::tSTMIA_UPD: {
6495     bool ListContainsBase, InvalidLowList;
6496     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
6497                                           0, ListContainsBase);
6498     if (InvalidLowList && !isThumbTwo())
6499       return Error(Operands[4]->getStartLoc(),
6500                    "registers must be in range r0-r7");
6501 
6502     // This would be converted to a 32-bit stm, but that's not valid if the
6503     // writeback register is in the list.
6504     if (InvalidLowList && ListContainsBase)
6505       return Error(Operands[4]->getStartLoc(),
6506                    "writeback operator '!' not allowed when base register "
6507                    "in register list");
6508 
6509     if (validatetSTMRegList(Inst, Operands, 4))
6510       return true;
6511     break;
6512   }
6513   case ARM::tADDrSP: {
6514     // If the non-SP source operand and the destination operand are not the
6515     // same, we need thumb2 (for the wide encoding), or we have an error.
6516     if (!isThumbTwo() &&
6517         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
6518       return Error(Operands[4]->getStartLoc(),
6519                    "source register must be the same as destination");
6520     }
6521     break;
6522   }
6523   // Final range checking for Thumb unconditional branch instructions.
6524   case ARM::tB:
6525     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
6526       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6527     break;
6528   case ARM::t2B: {
6529     int op = (Operands[2]->isImm()) ? 2 : 3;
6530     if (!static_cast<ARMOperand &>(*Operands[op]).isSignedOffset<24, 1>())
6531       return Error(Operands[op]->getStartLoc(), "branch target out of range");
6532     break;
6533   }
6534   // Final range checking for Thumb conditional branch instructions.
6535   case ARM::tBcc:
6536     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
6537       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6538     break;
6539   case ARM::t2Bcc: {
6540     int Op = (Operands[2]->isImm()) ? 2 : 3;
6541     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
6542       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
6543     break;
6544   }
6545   case ARM::tCBZ:
6546   case ARM::tCBNZ: {
6547     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<6, 1>())
6548       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6549     break;
6550   }
6551   case ARM::MOVi16:
6552   case ARM::MOVTi16:
6553   case ARM::t2MOVi16:
6554   case ARM::t2MOVTi16:
6555     {
6556     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
6557     // especially when we turn it into a movw and the expression <symbol> does
6558     // not have a :lower16: or :upper16 as part of the expression.  We don't
6559     // want the behavior of silently truncating, which can be unexpected and
6560     // lead to bugs that are difficult to find since this is an easy mistake
6561     // to make.
6562     int i = (Operands[3]->isImm()) ? 3 : 4;
6563     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
6564     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
6565     if (CE) break;
6566     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
6567     if (!E) break;
6568     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
6569     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
6570                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
6571       return Error(
6572           Op.getStartLoc(),
6573           "immediate expression for mov requires :lower16: or :upper16");
6574     break;
6575   }
6576   case ARM::HINT:
6577   case ARM::t2HINT: {
6578     if (hasRAS()) {
6579       // ESB is not predicable (pred must be AL)
6580       unsigned Imm8 = Inst.getOperand(0).getImm();
6581       unsigned Pred = Inst.getOperand(1).getImm();
6582       if (Imm8 == 0x10 && Pred != ARMCC::AL)
6583         return Error(Operands[1]->getStartLoc(), "instruction 'esb' is not "
6584                                                  "predicable, but condition "
6585                                                  "code specified");
6586     }
6587     // Without the RAS extension, this behaves as any other unallocated hint.
6588     break;
6589   }
6590   }
6591 
6592   return false;
6593 }
6594 
6595 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
6596   switch(Opc) {
6597   default: llvm_unreachable("unexpected opcode!");
6598   // VST1LN
6599   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6600   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6601   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6602   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6603   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6604   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6605   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
6606   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
6607   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
6608 
6609   // VST2LN
6610   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6611   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6612   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6613   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6614   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6615 
6616   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6617   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6618   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6619   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6620   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6621 
6622   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
6623   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
6624   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
6625   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
6626   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
6627 
6628   // VST3LN
6629   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6630   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6631   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6632   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
6633   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6634   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6635   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6636   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6637   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
6638   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6639   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
6640   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
6641   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
6642   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
6643   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
6644 
6645   // VST3
6646   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6647   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6648   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6649   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6650   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6651   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6652   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6653   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6654   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6655   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6656   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6657   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6658   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
6659   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
6660   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
6661   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
6662   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
6663   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
6664 
6665   // VST4LN
6666   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6667   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6668   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6669   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
6670   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6671   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6672   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6673   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6674   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
6675   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6676   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
6677   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
6678   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
6679   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
6680   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
6681 
6682   // VST4
6683   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6684   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6685   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6686   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6687   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6688   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6689   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6690   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6691   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6692   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6693   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6694   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6695   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
6696   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
6697   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
6698   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
6699   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
6700   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
6701   }
6702 }
6703 
6704 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
6705   switch(Opc) {
6706   default: llvm_unreachable("unexpected opcode!");
6707   // VLD1LN
6708   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6709   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6710   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6711   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6712   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6713   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6714   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
6715   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
6716   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
6717 
6718   // VLD2LN
6719   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6720   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6721   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6722   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
6723   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6724   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6725   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6726   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6727   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
6728   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6729   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
6730   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
6731   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
6732   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
6733   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
6734 
6735   // VLD3DUP
6736   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6737   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6738   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6739   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
6740   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6741   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6742   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6743   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6744   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6745   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
6746   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6747   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6748   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
6749   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
6750   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
6751   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
6752   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
6753   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
6754 
6755   // VLD3LN
6756   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6757   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6758   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6759   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
6760   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6761   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6762   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6763   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6764   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
6765   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6766   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
6767   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
6768   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
6769   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
6770   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
6771 
6772   // VLD3
6773   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6774   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6775   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6776   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6777   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6778   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6779   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6780   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6781   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6782   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6783   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6784   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6785   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
6786   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
6787   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
6788   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
6789   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
6790   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
6791 
6792   // VLD4LN
6793   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6794   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6795   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6796   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6797   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6798   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6799   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6800   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6801   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6802   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6803   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
6804   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
6805   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
6806   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
6807   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
6808 
6809   // VLD4DUP
6810   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6811   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6812   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6813   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
6814   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
6815   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6816   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6817   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6818   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6819   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
6820   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
6821   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6822   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
6823   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
6824   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
6825   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
6826   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
6827   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
6828 
6829   // VLD4
6830   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6831   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6832   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6833   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6834   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6835   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6836   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6837   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6838   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6839   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6840   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6841   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6842   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
6843   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
6844   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
6845   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
6846   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
6847   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
6848   }
6849 }
6850 
6851 bool ARMAsmParser::processInstruction(MCInst &Inst,
6852                                       const OperandVector &Operands,
6853                                       MCStreamer &Out) {
6854   switch (Inst.getOpcode()) {
6855   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
6856   case ARM::LDRT_POST:
6857   case ARM::LDRBT_POST: {
6858     const unsigned Opcode =
6859       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
6860                                            : ARM::LDRBT_POST_IMM;
6861     MCInst TmpInst;
6862     TmpInst.setOpcode(Opcode);
6863     TmpInst.addOperand(Inst.getOperand(0));
6864     TmpInst.addOperand(Inst.getOperand(1));
6865     TmpInst.addOperand(Inst.getOperand(1));
6866     TmpInst.addOperand(MCOperand::createReg(0));
6867     TmpInst.addOperand(MCOperand::createImm(0));
6868     TmpInst.addOperand(Inst.getOperand(2));
6869     TmpInst.addOperand(Inst.getOperand(3));
6870     Inst = TmpInst;
6871     return true;
6872   }
6873   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
6874   case ARM::STRT_POST:
6875   case ARM::STRBT_POST: {
6876     const unsigned Opcode =
6877       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
6878                                            : ARM::STRBT_POST_IMM;
6879     MCInst TmpInst;
6880     TmpInst.setOpcode(Opcode);
6881     TmpInst.addOperand(Inst.getOperand(1));
6882     TmpInst.addOperand(Inst.getOperand(0));
6883     TmpInst.addOperand(Inst.getOperand(1));
6884     TmpInst.addOperand(MCOperand::createReg(0));
6885     TmpInst.addOperand(MCOperand::createImm(0));
6886     TmpInst.addOperand(Inst.getOperand(2));
6887     TmpInst.addOperand(Inst.getOperand(3));
6888     Inst = TmpInst;
6889     return true;
6890   }
6891   // Alias for alternate form of 'ADR Rd, #imm' instruction.
6892   case ARM::ADDri: {
6893     if (Inst.getOperand(1).getReg() != ARM::PC ||
6894         Inst.getOperand(5).getReg() != 0 ||
6895         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
6896       return false;
6897     MCInst TmpInst;
6898     TmpInst.setOpcode(ARM::ADR);
6899     TmpInst.addOperand(Inst.getOperand(0));
6900     if (Inst.getOperand(2).isImm()) {
6901       // Immediate (mod_imm) will be in its encoded form, we must unencode it
6902       // before passing it to the ADR instruction.
6903       unsigned Enc = Inst.getOperand(2).getImm();
6904       TmpInst.addOperand(MCOperand::createImm(
6905         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
6906     } else {
6907       // Turn PC-relative expression into absolute expression.
6908       // Reading PC provides the start of the current instruction + 8 and
6909       // the transform to adr is biased by that.
6910       MCSymbol *Dot = getContext().createTempSymbol();
6911       Out.EmitLabel(Dot);
6912       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
6913       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
6914                                                      MCSymbolRefExpr::VK_None,
6915                                                      getContext());
6916       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
6917       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
6918                                                      getContext());
6919       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
6920                                                         getContext());
6921       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
6922     }
6923     TmpInst.addOperand(Inst.getOperand(3));
6924     TmpInst.addOperand(Inst.getOperand(4));
6925     Inst = TmpInst;
6926     return true;
6927   }
6928   // Aliases for alternate PC+imm syntax of LDR instructions.
6929   case ARM::t2LDRpcrel:
6930     // Select the narrow version if the immediate will fit.
6931     if (Inst.getOperand(1).getImm() > 0 &&
6932         Inst.getOperand(1).getImm() <= 0xff &&
6933         !(static_cast<ARMOperand &>(*Operands[2]).isToken() &&
6934           static_cast<ARMOperand &>(*Operands[2]).getToken() == ".w"))
6935       Inst.setOpcode(ARM::tLDRpci);
6936     else
6937       Inst.setOpcode(ARM::t2LDRpci);
6938     return true;
6939   case ARM::t2LDRBpcrel:
6940     Inst.setOpcode(ARM::t2LDRBpci);
6941     return true;
6942   case ARM::t2LDRHpcrel:
6943     Inst.setOpcode(ARM::t2LDRHpci);
6944     return true;
6945   case ARM::t2LDRSBpcrel:
6946     Inst.setOpcode(ARM::t2LDRSBpci);
6947     return true;
6948   case ARM::t2LDRSHpcrel:
6949     Inst.setOpcode(ARM::t2LDRSHpci);
6950     return true;
6951   case ARM::LDRConstPool:
6952   case ARM::tLDRConstPool:
6953   case ARM::t2LDRConstPool: {
6954     // Pseudo instruction ldr rt, =immediate is converted to a
6955     // MOV rt, immediate if immediate is known and representable
6956     // otherwise we create a constant pool entry that we load from.
6957     MCInst TmpInst;
6958     if (Inst.getOpcode() == ARM::LDRConstPool)
6959       TmpInst.setOpcode(ARM::LDRi12);
6960     else if (Inst.getOpcode() == ARM::tLDRConstPool)
6961       TmpInst.setOpcode(ARM::tLDRpci);
6962     else if (Inst.getOpcode() == ARM::t2LDRConstPool)
6963       TmpInst.setOpcode(ARM::t2LDRpci);
6964     const ARMOperand &PoolOperand =
6965       (static_cast<ARMOperand &>(*Operands[2]).isToken() &&
6966        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".w") ?
6967       static_cast<ARMOperand &>(*Operands[4]) :
6968       static_cast<ARMOperand &>(*Operands[3]);
6969     const MCExpr *SubExprVal = PoolOperand.getConstantPoolImm();
6970     // If SubExprVal is a constant we may be able to use a MOV
6971     if (isa<MCConstantExpr>(SubExprVal) &&
6972         Inst.getOperand(0).getReg() != ARM::PC &&
6973         Inst.getOperand(0).getReg() != ARM::SP) {
6974       int64_t Value =
6975         (int64_t) (cast<MCConstantExpr>(SubExprVal))->getValue();
6976       bool UseMov  = true;
6977       bool MovHasS = true;
6978       if (Inst.getOpcode() == ARM::LDRConstPool) {
6979         // ARM Constant
6980         if (ARM_AM::getSOImmVal(Value) != -1) {
6981           Value = ARM_AM::getSOImmVal(Value);
6982           TmpInst.setOpcode(ARM::MOVi);
6983         }
6984         else if (ARM_AM::getSOImmVal(~Value) != -1) {
6985           Value = ARM_AM::getSOImmVal(~Value);
6986           TmpInst.setOpcode(ARM::MVNi);
6987         }
6988         else if (hasV6T2Ops() &&
6989                  Value >=0 && Value < 65536) {
6990           TmpInst.setOpcode(ARM::MOVi16);
6991           MovHasS = false;
6992         }
6993         else
6994           UseMov = false;
6995       }
6996       else {
6997         // Thumb/Thumb2 Constant
6998         if (hasThumb2() &&
6999             ARM_AM::getT2SOImmVal(Value) != -1)
7000           TmpInst.setOpcode(ARM::t2MOVi);
7001         else if (hasThumb2() &&
7002                  ARM_AM::getT2SOImmVal(~Value) != -1) {
7003           TmpInst.setOpcode(ARM::t2MVNi);
7004           Value = ~Value;
7005         }
7006         else if (hasV8MBaseline() &&
7007                  Value >=0 && Value < 65536) {
7008           TmpInst.setOpcode(ARM::t2MOVi16);
7009           MovHasS = false;
7010         }
7011         else
7012           UseMov = false;
7013       }
7014       if (UseMov) {
7015         TmpInst.addOperand(Inst.getOperand(0));           // Rt
7016         TmpInst.addOperand(MCOperand::createImm(Value));  // Immediate
7017         TmpInst.addOperand(Inst.getOperand(2));           // CondCode
7018         TmpInst.addOperand(Inst.getOperand(3));           // CondCode
7019         if (MovHasS)
7020           TmpInst.addOperand(MCOperand::createReg(0));    // S
7021         Inst = TmpInst;
7022         return true;
7023       }
7024     }
7025     // No opportunity to use MOV/MVN create constant pool
7026     const MCExpr *CPLoc =
7027       getTargetStreamer().addConstantPoolEntry(SubExprVal,
7028                                                PoolOperand.getStartLoc());
7029     TmpInst.addOperand(Inst.getOperand(0));           // Rt
7030     TmpInst.addOperand(MCOperand::createExpr(CPLoc)); // offset to constpool
7031     if (TmpInst.getOpcode() == ARM::LDRi12)
7032       TmpInst.addOperand(MCOperand::createImm(0));    // unused offset
7033     TmpInst.addOperand(Inst.getOperand(2));           // CondCode
7034     TmpInst.addOperand(Inst.getOperand(3));           // CondCode
7035     Inst = TmpInst;
7036     return true;
7037   }
7038   // Handle NEON VST complex aliases.
7039   case ARM::VST1LNdWB_register_Asm_8:
7040   case ARM::VST1LNdWB_register_Asm_16:
7041   case ARM::VST1LNdWB_register_Asm_32: {
7042     MCInst TmpInst;
7043     // Shuffle the operands around so the lane index operand is in the
7044     // right place.
7045     unsigned Spacing;
7046     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7047     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7048     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7049     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7050     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7051     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7052     TmpInst.addOperand(Inst.getOperand(1)); // lane
7053     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7054     TmpInst.addOperand(Inst.getOperand(6));
7055     Inst = TmpInst;
7056     return true;
7057   }
7058 
7059   case ARM::VST2LNdWB_register_Asm_8:
7060   case ARM::VST2LNdWB_register_Asm_16:
7061   case ARM::VST2LNdWB_register_Asm_32:
7062   case ARM::VST2LNqWB_register_Asm_16:
7063   case ARM::VST2LNqWB_register_Asm_32: {
7064     MCInst TmpInst;
7065     // Shuffle the operands around so the lane index operand is in the
7066     // right place.
7067     unsigned Spacing;
7068     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7069     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7070     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7071     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7072     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7073     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7074     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7075                                             Spacing));
7076     TmpInst.addOperand(Inst.getOperand(1)); // lane
7077     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7078     TmpInst.addOperand(Inst.getOperand(6));
7079     Inst = TmpInst;
7080     return true;
7081   }
7082 
7083   case ARM::VST3LNdWB_register_Asm_8:
7084   case ARM::VST3LNdWB_register_Asm_16:
7085   case ARM::VST3LNdWB_register_Asm_32:
7086   case ARM::VST3LNqWB_register_Asm_16:
7087   case ARM::VST3LNqWB_register_Asm_32: {
7088     MCInst TmpInst;
7089     // Shuffle the operands around so the lane index operand is in the
7090     // right place.
7091     unsigned Spacing;
7092     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7093     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7094     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7095     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7096     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7097     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7098     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7099                                             Spacing));
7100     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7101                                             Spacing * 2));
7102     TmpInst.addOperand(Inst.getOperand(1)); // lane
7103     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7104     TmpInst.addOperand(Inst.getOperand(6));
7105     Inst = TmpInst;
7106     return true;
7107   }
7108 
7109   case ARM::VST4LNdWB_register_Asm_8:
7110   case ARM::VST4LNdWB_register_Asm_16:
7111   case ARM::VST4LNdWB_register_Asm_32:
7112   case ARM::VST4LNqWB_register_Asm_16:
7113   case ARM::VST4LNqWB_register_Asm_32: {
7114     MCInst TmpInst;
7115     // Shuffle the operands around so the lane index operand is in the
7116     // right place.
7117     unsigned Spacing;
7118     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7119     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7120     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7121     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7122     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7123     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7124     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7125                                             Spacing));
7126     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7127                                             Spacing * 2));
7128     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7129                                             Spacing * 3));
7130     TmpInst.addOperand(Inst.getOperand(1)); // lane
7131     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7132     TmpInst.addOperand(Inst.getOperand(6));
7133     Inst = TmpInst;
7134     return true;
7135   }
7136 
7137   case ARM::VST1LNdWB_fixed_Asm_8:
7138   case ARM::VST1LNdWB_fixed_Asm_16:
7139   case ARM::VST1LNdWB_fixed_Asm_32: {
7140     MCInst TmpInst;
7141     // Shuffle the operands around so the lane index operand is in the
7142     // right place.
7143     unsigned Spacing;
7144     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7145     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7146     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7147     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7148     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7149     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7150     TmpInst.addOperand(Inst.getOperand(1)); // lane
7151     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7152     TmpInst.addOperand(Inst.getOperand(5));
7153     Inst = TmpInst;
7154     return true;
7155   }
7156 
7157   case ARM::VST2LNdWB_fixed_Asm_8:
7158   case ARM::VST2LNdWB_fixed_Asm_16:
7159   case ARM::VST2LNdWB_fixed_Asm_32:
7160   case ARM::VST2LNqWB_fixed_Asm_16:
7161   case ARM::VST2LNqWB_fixed_Asm_32: {
7162     MCInst TmpInst;
7163     // Shuffle the operands around so the lane index operand is in the
7164     // right place.
7165     unsigned Spacing;
7166     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7167     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7168     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7169     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7170     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7171     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7172     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7173                                             Spacing));
7174     TmpInst.addOperand(Inst.getOperand(1)); // lane
7175     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7176     TmpInst.addOperand(Inst.getOperand(5));
7177     Inst = TmpInst;
7178     return true;
7179   }
7180 
7181   case ARM::VST3LNdWB_fixed_Asm_8:
7182   case ARM::VST3LNdWB_fixed_Asm_16:
7183   case ARM::VST3LNdWB_fixed_Asm_32:
7184   case ARM::VST3LNqWB_fixed_Asm_16:
7185   case ARM::VST3LNqWB_fixed_Asm_32: {
7186     MCInst TmpInst;
7187     // Shuffle the operands around so the lane index operand is in the
7188     // right place.
7189     unsigned Spacing;
7190     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7191     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7192     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7193     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7194     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7195     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7196     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7197                                             Spacing));
7198     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7199                                             Spacing * 2));
7200     TmpInst.addOperand(Inst.getOperand(1)); // lane
7201     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7202     TmpInst.addOperand(Inst.getOperand(5));
7203     Inst = TmpInst;
7204     return true;
7205   }
7206 
7207   case ARM::VST4LNdWB_fixed_Asm_8:
7208   case ARM::VST4LNdWB_fixed_Asm_16:
7209   case ARM::VST4LNdWB_fixed_Asm_32:
7210   case ARM::VST4LNqWB_fixed_Asm_16:
7211   case ARM::VST4LNqWB_fixed_Asm_32: {
7212     MCInst TmpInst;
7213     // Shuffle the operands around so the lane index operand is in the
7214     // right place.
7215     unsigned Spacing;
7216     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7217     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7218     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7219     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7220     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7221     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7222     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7223                                             Spacing));
7224     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7225                                             Spacing * 2));
7226     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7227                                             Spacing * 3));
7228     TmpInst.addOperand(Inst.getOperand(1)); // lane
7229     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7230     TmpInst.addOperand(Inst.getOperand(5));
7231     Inst = TmpInst;
7232     return true;
7233   }
7234 
7235   case ARM::VST1LNdAsm_8:
7236   case ARM::VST1LNdAsm_16:
7237   case ARM::VST1LNdAsm_32: {
7238     MCInst TmpInst;
7239     // Shuffle the operands around so the lane index operand is in the
7240     // right place.
7241     unsigned Spacing;
7242     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7243     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7244     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7245     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7246     TmpInst.addOperand(Inst.getOperand(1)); // lane
7247     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7248     TmpInst.addOperand(Inst.getOperand(5));
7249     Inst = TmpInst;
7250     return true;
7251   }
7252 
7253   case ARM::VST2LNdAsm_8:
7254   case ARM::VST2LNdAsm_16:
7255   case ARM::VST2LNdAsm_32:
7256   case ARM::VST2LNqAsm_16:
7257   case ARM::VST2LNqAsm_32: {
7258     MCInst TmpInst;
7259     // Shuffle the operands around so the lane index operand is in the
7260     // right place.
7261     unsigned Spacing;
7262     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7263     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7264     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7265     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7266     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7267                                             Spacing));
7268     TmpInst.addOperand(Inst.getOperand(1)); // lane
7269     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7270     TmpInst.addOperand(Inst.getOperand(5));
7271     Inst = TmpInst;
7272     return true;
7273   }
7274 
7275   case ARM::VST3LNdAsm_8:
7276   case ARM::VST3LNdAsm_16:
7277   case ARM::VST3LNdAsm_32:
7278   case ARM::VST3LNqAsm_16:
7279   case ARM::VST3LNqAsm_32: {
7280     MCInst TmpInst;
7281     // Shuffle the operands around so the lane index operand is in the
7282     // right place.
7283     unsigned Spacing;
7284     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7285     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7286     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7287     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7288     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7289                                             Spacing));
7290     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7291                                             Spacing * 2));
7292     TmpInst.addOperand(Inst.getOperand(1)); // lane
7293     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7294     TmpInst.addOperand(Inst.getOperand(5));
7295     Inst = TmpInst;
7296     return true;
7297   }
7298 
7299   case ARM::VST4LNdAsm_8:
7300   case ARM::VST4LNdAsm_16:
7301   case ARM::VST4LNdAsm_32:
7302   case ARM::VST4LNqAsm_16:
7303   case ARM::VST4LNqAsm_32: {
7304     MCInst TmpInst;
7305     // Shuffle the operands around so the lane index operand is in the
7306     // right place.
7307     unsigned Spacing;
7308     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7309     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7310     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7311     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7312     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7313                                             Spacing));
7314     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7315                                             Spacing * 2));
7316     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7317                                             Spacing * 3));
7318     TmpInst.addOperand(Inst.getOperand(1)); // lane
7319     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7320     TmpInst.addOperand(Inst.getOperand(5));
7321     Inst = TmpInst;
7322     return true;
7323   }
7324 
7325   // Handle NEON VLD complex aliases.
7326   case ARM::VLD1LNdWB_register_Asm_8:
7327   case ARM::VLD1LNdWB_register_Asm_16:
7328   case ARM::VLD1LNdWB_register_Asm_32: {
7329     MCInst TmpInst;
7330     // Shuffle the operands around so the lane index operand is in the
7331     // right place.
7332     unsigned Spacing;
7333     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7334     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7335     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7336     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7337     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7338     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7339     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7340     TmpInst.addOperand(Inst.getOperand(1)); // lane
7341     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7342     TmpInst.addOperand(Inst.getOperand(6));
7343     Inst = TmpInst;
7344     return true;
7345   }
7346 
7347   case ARM::VLD2LNdWB_register_Asm_8:
7348   case ARM::VLD2LNdWB_register_Asm_16:
7349   case ARM::VLD2LNdWB_register_Asm_32:
7350   case ARM::VLD2LNqWB_register_Asm_16:
7351   case ARM::VLD2LNqWB_register_Asm_32: {
7352     MCInst TmpInst;
7353     // Shuffle the operands around so the lane index operand is in the
7354     // right place.
7355     unsigned Spacing;
7356     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7357     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7358     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7359                                             Spacing));
7360     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7361     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7362     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7363     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7364     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7365     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7366                                             Spacing));
7367     TmpInst.addOperand(Inst.getOperand(1)); // lane
7368     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7369     TmpInst.addOperand(Inst.getOperand(6));
7370     Inst = TmpInst;
7371     return true;
7372   }
7373 
7374   case ARM::VLD3LNdWB_register_Asm_8:
7375   case ARM::VLD3LNdWB_register_Asm_16:
7376   case ARM::VLD3LNdWB_register_Asm_32:
7377   case ARM::VLD3LNqWB_register_Asm_16:
7378   case ARM::VLD3LNqWB_register_Asm_32: {
7379     MCInst TmpInst;
7380     // Shuffle the operands around so the lane index operand is in the
7381     // right place.
7382     unsigned Spacing;
7383     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7384     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7385     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7386                                             Spacing));
7387     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7388                                             Spacing * 2));
7389     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7390     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7391     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7392     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7393     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7394     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7395                                             Spacing));
7396     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7397                                             Spacing * 2));
7398     TmpInst.addOperand(Inst.getOperand(1)); // lane
7399     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7400     TmpInst.addOperand(Inst.getOperand(6));
7401     Inst = TmpInst;
7402     return true;
7403   }
7404 
7405   case ARM::VLD4LNdWB_register_Asm_8:
7406   case ARM::VLD4LNdWB_register_Asm_16:
7407   case ARM::VLD4LNdWB_register_Asm_32:
7408   case ARM::VLD4LNqWB_register_Asm_16:
7409   case ARM::VLD4LNqWB_register_Asm_32: {
7410     MCInst TmpInst;
7411     // Shuffle the operands around so the lane index operand is in the
7412     // right place.
7413     unsigned Spacing;
7414     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7415     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7416     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7417                                             Spacing));
7418     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7419                                             Spacing * 2));
7420     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7421                                             Spacing * 3));
7422     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7423     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7424     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7425     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7426     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7427     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7428                                             Spacing));
7429     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7430                                             Spacing * 2));
7431     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7432                                             Spacing * 3));
7433     TmpInst.addOperand(Inst.getOperand(1)); // lane
7434     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7435     TmpInst.addOperand(Inst.getOperand(6));
7436     Inst = TmpInst;
7437     return true;
7438   }
7439 
7440   case ARM::VLD1LNdWB_fixed_Asm_8:
7441   case ARM::VLD1LNdWB_fixed_Asm_16:
7442   case ARM::VLD1LNdWB_fixed_Asm_32: {
7443     MCInst TmpInst;
7444     // Shuffle the operands around so the lane index operand is in the
7445     // right place.
7446     unsigned Spacing;
7447     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7448     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7449     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7450     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7451     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7452     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7453     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7454     TmpInst.addOperand(Inst.getOperand(1)); // lane
7455     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7456     TmpInst.addOperand(Inst.getOperand(5));
7457     Inst = TmpInst;
7458     return true;
7459   }
7460 
7461   case ARM::VLD2LNdWB_fixed_Asm_8:
7462   case ARM::VLD2LNdWB_fixed_Asm_16:
7463   case ARM::VLD2LNdWB_fixed_Asm_32:
7464   case ARM::VLD2LNqWB_fixed_Asm_16:
7465   case ARM::VLD2LNqWB_fixed_Asm_32: {
7466     MCInst TmpInst;
7467     // Shuffle the operands around so the lane index operand is in the
7468     // right place.
7469     unsigned Spacing;
7470     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7471     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7472     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7473                                             Spacing));
7474     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7475     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7476     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7477     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7478     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7479     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7480                                             Spacing));
7481     TmpInst.addOperand(Inst.getOperand(1)); // lane
7482     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7483     TmpInst.addOperand(Inst.getOperand(5));
7484     Inst = TmpInst;
7485     return true;
7486   }
7487 
7488   case ARM::VLD3LNdWB_fixed_Asm_8:
7489   case ARM::VLD3LNdWB_fixed_Asm_16:
7490   case ARM::VLD3LNdWB_fixed_Asm_32:
7491   case ARM::VLD3LNqWB_fixed_Asm_16:
7492   case ARM::VLD3LNqWB_fixed_Asm_32: {
7493     MCInst TmpInst;
7494     // Shuffle the operands around so the lane index operand is in the
7495     // right place.
7496     unsigned Spacing;
7497     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7498     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7499     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7500                                             Spacing));
7501     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7502                                             Spacing * 2));
7503     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7504     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7505     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7506     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7507     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7508     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7509                                             Spacing));
7510     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7511                                             Spacing * 2));
7512     TmpInst.addOperand(Inst.getOperand(1)); // lane
7513     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7514     TmpInst.addOperand(Inst.getOperand(5));
7515     Inst = TmpInst;
7516     return true;
7517   }
7518 
7519   case ARM::VLD4LNdWB_fixed_Asm_8:
7520   case ARM::VLD4LNdWB_fixed_Asm_16:
7521   case ARM::VLD4LNdWB_fixed_Asm_32:
7522   case ARM::VLD4LNqWB_fixed_Asm_16:
7523   case ARM::VLD4LNqWB_fixed_Asm_32: {
7524     MCInst TmpInst;
7525     // Shuffle the operands around so the lane index operand is in the
7526     // right place.
7527     unsigned Spacing;
7528     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7529     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7530     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7531                                             Spacing));
7532     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7533                                             Spacing * 2));
7534     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7535                                             Spacing * 3));
7536     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7537     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7538     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7539     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7540     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7541     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7542                                             Spacing));
7543     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7544                                             Spacing * 2));
7545     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7546                                             Spacing * 3));
7547     TmpInst.addOperand(Inst.getOperand(1)); // lane
7548     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7549     TmpInst.addOperand(Inst.getOperand(5));
7550     Inst = TmpInst;
7551     return true;
7552   }
7553 
7554   case ARM::VLD1LNdAsm_8:
7555   case ARM::VLD1LNdAsm_16:
7556   case ARM::VLD1LNdAsm_32: {
7557     MCInst TmpInst;
7558     // Shuffle the operands around so the lane index operand is in the
7559     // right place.
7560     unsigned Spacing;
7561     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7562     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7563     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7564     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7565     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7566     TmpInst.addOperand(Inst.getOperand(1)); // lane
7567     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7568     TmpInst.addOperand(Inst.getOperand(5));
7569     Inst = TmpInst;
7570     return true;
7571   }
7572 
7573   case ARM::VLD2LNdAsm_8:
7574   case ARM::VLD2LNdAsm_16:
7575   case ARM::VLD2LNdAsm_32:
7576   case ARM::VLD2LNqAsm_16:
7577   case ARM::VLD2LNqAsm_32: {
7578     MCInst TmpInst;
7579     // Shuffle the operands around so the lane index operand is in the
7580     // right place.
7581     unsigned Spacing;
7582     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7583     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7584     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7585                                             Spacing));
7586     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7587     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7588     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7589     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7590                                             Spacing));
7591     TmpInst.addOperand(Inst.getOperand(1)); // lane
7592     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7593     TmpInst.addOperand(Inst.getOperand(5));
7594     Inst = TmpInst;
7595     return true;
7596   }
7597 
7598   case ARM::VLD3LNdAsm_8:
7599   case ARM::VLD3LNdAsm_16:
7600   case ARM::VLD3LNdAsm_32:
7601   case ARM::VLD3LNqAsm_16:
7602   case ARM::VLD3LNqAsm_32: {
7603     MCInst TmpInst;
7604     // Shuffle the operands around so the lane index operand is in the
7605     // right place.
7606     unsigned Spacing;
7607     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7608     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7609     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7610                                             Spacing));
7611     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7612                                             Spacing * 2));
7613     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7614     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7615     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7616     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7617                                             Spacing));
7618     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7619                                             Spacing * 2));
7620     TmpInst.addOperand(Inst.getOperand(1)); // lane
7621     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7622     TmpInst.addOperand(Inst.getOperand(5));
7623     Inst = TmpInst;
7624     return true;
7625   }
7626 
7627   case ARM::VLD4LNdAsm_8:
7628   case ARM::VLD4LNdAsm_16:
7629   case ARM::VLD4LNdAsm_32:
7630   case ARM::VLD4LNqAsm_16:
7631   case ARM::VLD4LNqAsm_32: {
7632     MCInst TmpInst;
7633     // Shuffle the operands around so the lane index operand is in the
7634     // right place.
7635     unsigned Spacing;
7636     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7637     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7638     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7639                                             Spacing));
7640     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7641                                             Spacing * 2));
7642     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7643                                             Spacing * 3));
7644     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7645     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7646     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7647     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7648                                             Spacing));
7649     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7650                                             Spacing * 2));
7651     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7652                                             Spacing * 3));
7653     TmpInst.addOperand(Inst.getOperand(1)); // lane
7654     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7655     TmpInst.addOperand(Inst.getOperand(5));
7656     Inst = TmpInst;
7657     return true;
7658   }
7659 
7660   // VLD3DUP single 3-element structure to all lanes instructions.
7661   case ARM::VLD3DUPdAsm_8:
7662   case ARM::VLD3DUPdAsm_16:
7663   case ARM::VLD3DUPdAsm_32:
7664   case ARM::VLD3DUPqAsm_8:
7665   case ARM::VLD3DUPqAsm_16:
7666   case ARM::VLD3DUPqAsm_32: {
7667     MCInst TmpInst;
7668     unsigned Spacing;
7669     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7670     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7671     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7672                                             Spacing));
7673     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7674                                             Spacing * 2));
7675     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7676     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7677     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7678     TmpInst.addOperand(Inst.getOperand(4));
7679     Inst = TmpInst;
7680     return true;
7681   }
7682 
7683   case ARM::VLD3DUPdWB_fixed_Asm_8:
7684   case ARM::VLD3DUPdWB_fixed_Asm_16:
7685   case ARM::VLD3DUPdWB_fixed_Asm_32:
7686   case ARM::VLD3DUPqWB_fixed_Asm_8:
7687   case ARM::VLD3DUPqWB_fixed_Asm_16:
7688   case ARM::VLD3DUPqWB_fixed_Asm_32: {
7689     MCInst TmpInst;
7690     unsigned Spacing;
7691     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7692     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7693     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7694                                             Spacing));
7695     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7696                                             Spacing * 2));
7697     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7698     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7699     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7700     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7701     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7702     TmpInst.addOperand(Inst.getOperand(4));
7703     Inst = TmpInst;
7704     return true;
7705   }
7706 
7707   case ARM::VLD3DUPdWB_register_Asm_8:
7708   case ARM::VLD3DUPdWB_register_Asm_16:
7709   case ARM::VLD3DUPdWB_register_Asm_32:
7710   case ARM::VLD3DUPqWB_register_Asm_8:
7711   case ARM::VLD3DUPqWB_register_Asm_16:
7712   case ARM::VLD3DUPqWB_register_Asm_32: {
7713     MCInst TmpInst;
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(MCOperand::createReg(Inst.getOperand(0).getReg() +
7720                                             Spacing * 2));
7721     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7722     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7723     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7724     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7725     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7726     TmpInst.addOperand(Inst.getOperand(5));
7727     Inst = TmpInst;
7728     return true;
7729   }
7730 
7731   // VLD3 multiple 3-element structure instructions.
7732   case ARM::VLD3dAsm_8:
7733   case ARM::VLD3dAsm_16:
7734   case ARM::VLD3dAsm_32:
7735   case ARM::VLD3qAsm_8:
7736   case ARM::VLD3qAsm_16:
7737   case ARM::VLD3qAsm_32: {
7738     MCInst TmpInst;
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(1)); // Rn
7747     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7748     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7749     TmpInst.addOperand(Inst.getOperand(4));
7750     Inst = TmpInst;
7751     return true;
7752   }
7753 
7754   case ARM::VLD3dWB_fixed_Asm_8:
7755   case ARM::VLD3dWB_fixed_Asm_16:
7756   case ARM::VLD3dWB_fixed_Asm_32:
7757   case ARM::VLD3qWB_fixed_Asm_8:
7758   case ARM::VLD3qWB_fixed_Asm_16:
7759   case ARM::VLD3qWB_fixed_Asm_32: {
7760     MCInst TmpInst;
7761     unsigned Spacing;
7762     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7763     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7764     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7765                                             Spacing));
7766     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7767                                             Spacing * 2));
7768     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7769     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7770     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7771     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7772     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7773     TmpInst.addOperand(Inst.getOperand(4));
7774     Inst = TmpInst;
7775     return true;
7776   }
7777 
7778   case ARM::VLD3dWB_register_Asm_8:
7779   case ARM::VLD3dWB_register_Asm_16:
7780   case ARM::VLD3dWB_register_Asm_32:
7781   case ARM::VLD3qWB_register_Asm_8:
7782   case ARM::VLD3qWB_register_Asm_16:
7783   case ARM::VLD3qWB_register_Asm_32: {
7784     MCInst TmpInst;
7785     unsigned Spacing;
7786     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7787     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7788     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7789                                             Spacing));
7790     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7791                                             Spacing * 2));
7792     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7793     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7794     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7795     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7796     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7797     TmpInst.addOperand(Inst.getOperand(5));
7798     Inst = TmpInst;
7799     return true;
7800   }
7801 
7802   // VLD4DUP single 3-element structure to all lanes instructions.
7803   case ARM::VLD4DUPdAsm_8:
7804   case ARM::VLD4DUPdAsm_16:
7805   case ARM::VLD4DUPdAsm_32:
7806   case ARM::VLD4DUPqAsm_8:
7807   case ARM::VLD4DUPqAsm_16:
7808   case ARM::VLD4DUPqAsm_32: {
7809     MCInst TmpInst;
7810     unsigned Spacing;
7811     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7812     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7813     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7814                                             Spacing));
7815     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7816                                             Spacing * 2));
7817     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7818                                             Spacing * 3));
7819     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7820     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7821     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7822     TmpInst.addOperand(Inst.getOperand(4));
7823     Inst = TmpInst;
7824     return true;
7825   }
7826 
7827   case ARM::VLD4DUPdWB_fixed_Asm_8:
7828   case ARM::VLD4DUPdWB_fixed_Asm_16:
7829   case ARM::VLD4DUPdWB_fixed_Asm_32:
7830   case ARM::VLD4DUPqWB_fixed_Asm_8:
7831   case ARM::VLD4DUPqWB_fixed_Asm_16:
7832   case ARM::VLD4DUPqWB_fixed_Asm_32: {
7833     MCInst TmpInst;
7834     unsigned Spacing;
7835     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7836     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7837     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7838                                             Spacing));
7839     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7840                                             Spacing * 2));
7841     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7842                                             Spacing * 3));
7843     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7844     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7845     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7846     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7847     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7848     TmpInst.addOperand(Inst.getOperand(4));
7849     Inst = TmpInst;
7850     return true;
7851   }
7852 
7853   case ARM::VLD4DUPdWB_register_Asm_8:
7854   case ARM::VLD4DUPdWB_register_Asm_16:
7855   case ARM::VLD4DUPdWB_register_Asm_32:
7856   case ARM::VLD4DUPqWB_register_Asm_8:
7857   case ARM::VLD4DUPqWB_register_Asm_16:
7858   case ARM::VLD4DUPqWB_register_Asm_32: {
7859     MCInst TmpInst;
7860     unsigned Spacing;
7861     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7862     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7863     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7864                                             Spacing));
7865     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7866                                             Spacing * 2));
7867     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7868                                             Spacing * 3));
7869     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7870     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7871     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7872     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7873     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7874     TmpInst.addOperand(Inst.getOperand(5));
7875     Inst = TmpInst;
7876     return true;
7877   }
7878 
7879   // VLD4 multiple 4-element structure instructions.
7880   case ARM::VLD4dAsm_8:
7881   case ARM::VLD4dAsm_16:
7882   case ARM::VLD4dAsm_32:
7883   case ARM::VLD4qAsm_8:
7884   case ARM::VLD4qAsm_16:
7885   case ARM::VLD4qAsm_32: {
7886     MCInst TmpInst;
7887     unsigned Spacing;
7888     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7889     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7890     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7891                                             Spacing));
7892     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7893                                             Spacing * 2));
7894     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7895                                             Spacing * 3));
7896     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7897     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7898     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7899     TmpInst.addOperand(Inst.getOperand(4));
7900     Inst = TmpInst;
7901     return true;
7902   }
7903 
7904   case ARM::VLD4dWB_fixed_Asm_8:
7905   case ARM::VLD4dWB_fixed_Asm_16:
7906   case ARM::VLD4dWB_fixed_Asm_32:
7907   case ARM::VLD4qWB_fixed_Asm_8:
7908   case ARM::VLD4qWB_fixed_Asm_16:
7909   case ARM::VLD4qWB_fixed_Asm_32: {
7910     MCInst TmpInst;
7911     unsigned Spacing;
7912     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7913     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7914     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7915                                             Spacing));
7916     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7917                                             Spacing * 2));
7918     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7919                                             Spacing * 3));
7920     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7921     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7922     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7923     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7924     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7925     TmpInst.addOperand(Inst.getOperand(4));
7926     Inst = TmpInst;
7927     return true;
7928   }
7929 
7930   case ARM::VLD4dWB_register_Asm_8:
7931   case ARM::VLD4dWB_register_Asm_16:
7932   case ARM::VLD4dWB_register_Asm_32:
7933   case ARM::VLD4qWB_register_Asm_8:
7934   case ARM::VLD4qWB_register_Asm_16:
7935   case ARM::VLD4qWB_register_Asm_32: {
7936     MCInst TmpInst;
7937     unsigned Spacing;
7938     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7939     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7940     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7941                                             Spacing));
7942     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7943                                             Spacing * 2));
7944     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7945                                             Spacing * 3));
7946     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7947     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7948     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7949     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7950     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7951     TmpInst.addOperand(Inst.getOperand(5));
7952     Inst = TmpInst;
7953     return true;
7954   }
7955 
7956   // VST3 multiple 3-element structure instructions.
7957   case ARM::VST3dAsm_8:
7958   case ARM::VST3dAsm_16:
7959   case ARM::VST3dAsm_32:
7960   case ARM::VST3qAsm_8:
7961   case ARM::VST3qAsm_16:
7962   case ARM::VST3qAsm_32: {
7963     MCInst TmpInst;
7964     unsigned Spacing;
7965     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7966     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7967     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7968     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7969     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7970                                             Spacing));
7971     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7972                                             Spacing * 2));
7973     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7974     TmpInst.addOperand(Inst.getOperand(4));
7975     Inst = TmpInst;
7976     return true;
7977   }
7978 
7979   case ARM::VST3dWB_fixed_Asm_8:
7980   case ARM::VST3dWB_fixed_Asm_16:
7981   case ARM::VST3dWB_fixed_Asm_32:
7982   case ARM::VST3qWB_fixed_Asm_8:
7983   case ARM::VST3qWB_fixed_Asm_16:
7984   case ARM::VST3qWB_fixed_Asm_32: {
7985     MCInst TmpInst;
7986     unsigned Spacing;
7987     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7988     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7989     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7990     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7991     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7992     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7993     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7994                                             Spacing));
7995     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7996                                             Spacing * 2));
7997     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7998     TmpInst.addOperand(Inst.getOperand(4));
7999     Inst = TmpInst;
8000     return true;
8001   }
8002 
8003   case ARM::VST3dWB_register_Asm_8:
8004   case ARM::VST3dWB_register_Asm_16:
8005   case ARM::VST3dWB_register_Asm_32:
8006   case ARM::VST3qWB_register_Asm_8:
8007   case ARM::VST3qWB_register_Asm_16:
8008   case ARM::VST3qWB_register_Asm_32: {
8009     MCInst TmpInst;
8010     unsigned Spacing;
8011     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8012     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8013     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8014     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8015     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8016     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8017     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8018                                             Spacing));
8019     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8020                                             Spacing * 2));
8021     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8022     TmpInst.addOperand(Inst.getOperand(5));
8023     Inst = TmpInst;
8024     return true;
8025   }
8026 
8027   // VST4 multiple 3-element structure instructions.
8028   case ARM::VST4dAsm_8:
8029   case ARM::VST4dAsm_16:
8030   case ARM::VST4dAsm_32:
8031   case ARM::VST4qAsm_8:
8032   case ARM::VST4qAsm_16:
8033   case ARM::VST4qAsm_32: {
8034     MCInst TmpInst;
8035     unsigned Spacing;
8036     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8037     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8038     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8039     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8040     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8041                                             Spacing));
8042     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8043                                             Spacing * 2));
8044     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8045                                             Spacing * 3));
8046     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8047     TmpInst.addOperand(Inst.getOperand(4));
8048     Inst = TmpInst;
8049     return true;
8050   }
8051 
8052   case ARM::VST4dWB_fixed_Asm_8:
8053   case ARM::VST4dWB_fixed_Asm_16:
8054   case ARM::VST4dWB_fixed_Asm_32:
8055   case ARM::VST4qWB_fixed_Asm_8:
8056   case ARM::VST4qWB_fixed_Asm_16:
8057   case ARM::VST4qWB_fixed_Asm_32: {
8058     MCInst TmpInst;
8059     unsigned Spacing;
8060     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8061     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8062     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8063     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8064     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8065     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8066     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8067                                             Spacing));
8068     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8069                                             Spacing * 2));
8070     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8071                                             Spacing * 3));
8072     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8073     TmpInst.addOperand(Inst.getOperand(4));
8074     Inst = TmpInst;
8075     return true;
8076   }
8077 
8078   case ARM::VST4dWB_register_Asm_8:
8079   case ARM::VST4dWB_register_Asm_16:
8080   case ARM::VST4dWB_register_Asm_32:
8081   case ARM::VST4qWB_register_Asm_8:
8082   case ARM::VST4qWB_register_Asm_16:
8083   case ARM::VST4qWB_register_Asm_32: {
8084     MCInst TmpInst;
8085     unsigned Spacing;
8086     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8087     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8088     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8089     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8090     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8091     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8092     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8093                                             Spacing));
8094     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8095                                             Spacing * 2));
8096     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8097                                             Spacing * 3));
8098     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8099     TmpInst.addOperand(Inst.getOperand(5));
8100     Inst = TmpInst;
8101     return true;
8102   }
8103 
8104   // Handle encoding choice for the shift-immediate instructions.
8105   case ARM::t2LSLri:
8106   case ARM::t2LSRri:
8107   case ARM::t2ASRri: {
8108     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8109         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8110         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8111         !(static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8112           static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w")) {
8113       unsigned NewOpc;
8114       switch (Inst.getOpcode()) {
8115       default: llvm_unreachable("unexpected opcode");
8116       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
8117       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
8118       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
8119       }
8120       // The Thumb1 operands aren't in the same order. Awesome, eh?
8121       MCInst TmpInst;
8122       TmpInst.setOpcode(NewOpc);
8123       TmpInst.addOperand(Inst.getOperand(0));
8124       TmpInst.addOperand(Inst.getOperand(5));
8125       TmpInst.addOperand(Inst.getOperand(1));
8126       TmpInst.addOperand(Inst.getOperand(2));
8127       TmpInst.addOperand(Inst.getOperand(3));
8128       TmpInst.addOperand(Inst.getOperand(4));
8129       Inst = TmpInst;
8130       return true;
8131     }
8132     return false;
8133   }
8134 
8135   // Handle the Thumb2 mode MOV complex aliases.
8136   case ARM::t2MOVsr:
8137   case ARM::t2MOVSsr: {
8138     // Which instruction to expand to depends on the CCOut operand and
8139     // whether we're in an IT block if the register operands are low
8140     // registers.
8141     bool isNarrow = false;
8142     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8143         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8144         isARMLowRegister(Inst.getOperand(2).getReg()) &&
8145         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8146         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr))
8147       isNarrow = true;
8148     MCInst TmpInst;
8149     unsigned newOpc;
8150     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
8151     default: llvm_unreachable("unexpected opcode!");
8152     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
8153     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
8154     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
8155     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
8156     }
8157     TmpInst.setOpcode(newOpc);
8158     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8159     if (isNarrow)
8160       TmpInst.addOperand(MCOperand::createReg(
8161           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8162     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8163     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8164     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8165     TmpInst.addOperand(Inst.getOperand(5));
8166     if (!isNarrow)
8167       TmpInst.addOperand(MCOperand::createReg(
8168           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8169     Inst = TmpInst;
8170     return true;
8171   }
8172   case ARM::t2MOVsi:
8173   case ARM::t2MOVSsi: {
8174     // Which instruction to expand to depends on the CCOut operand and
8175     // whether we're in an IT block if the register operands are low
8176     // registers.
8177     bool isNarrow = false;
8178     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8179         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8180         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi))
8181       isNarrow = true;
8182     MCInst TmpInst;
8183     unsigned newOpc;
8184     unsigned Shift = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8185     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
8186     bool isMov = false;
8187     // MOV rd, rm, LSL #0 is actually a MOV instruction
8188     if (Shift == ARM_AM::lsl && Amount == 0) {
8189       isMov = true;
8190       // The 16-bit encoding of MOV rd, rm, LSL #N is explicitly encoding T2 of
8191       // MOV (register) in the ARMv8-A and ARMv8-M manuals, and immediate 0 is
8192       // unpredictable in an IT block so the 32-bit encoding T3 has to be used
8193       // instead.
8194       if (inITBlock()) {
8195         isNarrow = false;
8196       }
8197       newOpc = isNarrow ? ARM::tMOVSr : ARM::t2MOVr;
8198     } else {
8199       switch(Shift) {
8200       default: llvm_unreachable("unexpected opcode!");
8201       case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
8202       case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
8203       case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
8204       case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
8205       case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
8206       }
8207     }
8208     if (Amount == 32) Amount = 0;
8209     TmpInst.setOpcode(newOpc);
8210     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8211     if (isNarrow && !isMov)
8212       TmpInst.addOperand(MCOperand::createReg(
8213           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8214     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8215     if (newOpc != ARM::t2RRX && !isMov)
8216       TmpInst.addOperand(MCOperand::createImm(Amount));
8217     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8218     TmpInst.addOperand(Inst.getOperand(4));
8219     if (!isNarrow)
8220       TmpInst.addOperand(MCOperand::createReg(
8221           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8222     Inst = TmpInst;
8223     return true;
8224   }
8225   // Handle the ARM mode MOV complex aliases.
8226   case ARM::ASRr:
8227   case ARM::LSRr:
8228   case ARM::LSLr:
8229   case ARM::RORr: {
8230     ARM_AM::ShiftOpc ShiftTy;
8231     switch(Inst.getOpcode()) {
8232     default: llvm_unreachable("unexpected opcode!");
8233     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
8234     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
8235     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
8236     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
8237     }
8238     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
8239     MCInst TmpInst;
8240     TmpInst.setOpcode(ARM::MOVsr);
8241     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8242     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8243     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8244     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8245     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8246     TmpInst.addOperand(Inst.getOperand(4));
8247     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8248     Inst = TmpInst;
8249     return true;
8250   }
8251   case ARM::ASRi:
8252   case ARM::LSRi:
8253   case ARM::LSLi:
8254   case ARM::RORi: {
8255     ARM_AM::ShiftOpc ShiftTy;
8256     switch(Inst.getOpcode()) {
8257     default: llvm_unreachable("unexpected opcode!");
8258     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
8259     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
8260     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
8261     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
8262     }
8263     // A shift by zero is a plain MOVr, not a MOVsi.
8264     unsigned Amt = Inst.getOperand(2).getImm();
8265     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
8266     // A shift by 32 should be encoded as 0 when permitted
8267     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
8268       Amt = 0;
8269     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
8270     MCInst TmpInst;
8271     TmpInst.setOpcode(Opc);
8272     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8273     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8274     if (Opc == ARM::MOVsi)
8275       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8276     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8277     TmpInst.addOperand(Inst.getOperand(4));
8278     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8279     Inst = TmpInst;
8280     return true;
8281   }
8282   case ARM::RRXi: {
8283     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
8284     MCInst TmpInst;
8285     TmpInst.setOpcode(ARM::MOVsi);
8286     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8287     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8288     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8289     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8290     TmpInst.addOperand(Inst.getOperand(3));
8291     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
8292     Inst = TmpInst;
8293     return true;
8294   }
8295   case ARM::t2LDMIA_UPD: {
8296     // If this is a load of a single register, then we should use
8297     // a post-indexed LDR instruction instead, per the ARM ARM.
8298     if (Inst.getNumOperands() != 5)
8299       return false;
8300     MCInst TmpInst;
8301     TmpInst.setOpcode(ARM::t2LDR_POST);
8302     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8303     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8304     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8305     TmpInst.addOperand(MCOperand::createImm(4));
8306     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8307     TmpInst.addOperand(Inst.getOperand(3));
8308     Inst = TmpInst;
8309     return true;
8310   }
8311   case ARM::t2STMDB_UPD: {
8312     // If this is a store of a single register, then we should use
8313     // a pre-indexed STR instruction instead, per the ARM ARM.
8314     if (Inst.getNumOperands() != 5)
8315       return false;
8316     MCInst TmpInst;
8317     TmpInst.setOpcode(ARM::t2STR_PRE);
8318     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8319     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8320     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8321     TmpInst.addOperand(MCOperand::createImm(-4));
8322     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8323     TmpInst.addOperand(Inst.getOperand(3));
8324     Inst = TmpInst;
8325     return true;
8326   }
8327   case ARM::LDMIA_UPD:
8328     // If this is a load of a single register via a 'pop', then we should use
8329     // a post-indexed LDR instruction instead, per the ARM ARM.
8330     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
8331         Inst.getNumOperands() == 5) {
8332       MCInst TmpInst;
8333       TmpInst.setOpcode(ARM::LDR_POST_IMM);
8334       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8335       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8336       TmpInst.addOperand(Inst.getOperand(1)); // Rn
8337       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
8338       TmpInst.addOperand(MCOperand::createImm(4));
8339       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8340       TmpInst.addOperand(Inst.getOperand(3));
8341       Inst = TmpInst;
8342       return true;
8343     }
8344     break;
8345   case ARM::STMDB_UPD:
8346     // If this is a store of a single register via a 'push', then we should use
8347     // a pre-indexed STR instruction instead, per the ARM ARM.
8348     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
8349         Inst.getNumOperands() == 5) {
8350       MCInst TmpInst;
8351       TmpInst.setOpcode(ARM::STR_PRE_IMM);
8352       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8353       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8354       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
8355       TmpInst.addOperand(MCOperand::createImm(-4));
8356       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8357       TmpInst.addOperand(Inst.getOperand(3));
8358       Inst = TmpInst;
8359     }
8360     break;
8361   case ARM::t2ADDri12:
8362     // If the immediate fits for encoding T3 (t2ADDri) and the generic "add"
8363     // mnemonic was used (not "addw"), encoding T3 is preferred.
8364     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "add" ||
8365         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8366       break;
8367     Inst.setOpcode(ARM::t2ADDri);
8368     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8369     break;
8370   case ARM::t2SUBri12:
8371     // If the immediate fits for encoding T3 (t2SUBri) and the generic "sub"
8372     // mnemonic was used (not "subw"), encoding T3 is preferred.
8373     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "sub" ||
8374         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8375       break;
8376     Inst.setOpcode(ARM::t2SUBri);
8377     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8378     break;
8379   case ARM::tADDi8:
8380     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8381     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8382     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8383     // to encoding T1 if <Rd> is omitted."
8384     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8385       Inst.setOpcode(ARM::tADDi3);
8386       return true;
8387     }
8388     break;
8389   case ARM::tSUBi8:
8390     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8391     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8392     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8393     // to encoding T1 if <Rd> is omitted."
8394     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8395       Inst.setOpcode(ARM::tSUBi3);
8396       return true;
8397     }
8398     break;
8399   case ARM::t2ADDri:
8400   case ARM::t2SUBri: {
8401     // If the destination and first source operand are the same, and
8402     // the flags are compatible with the current IT status, use encoding T2
8403     // instead of T3. For compatibility with the system 'as'. Make sure the
8404     // wide encoding wasn't explicit.
8405     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
8406         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
8407         (unsigned)Inst.getOperand(2).getImm() > 255 ||
8408         ((!inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR) ||
8409          (inITBlock() && Inst.getOperand(5).getReg() != 0)) ||
8410         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8411          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w"))
8412       break;
8413     MCInst TmpInst;
8414     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
8415                       ARM::tADDi8 : ARM::tSUBi8);
8416     TmpInst.addOperand(Inst.getOperand(0));
8417     TmpInst.addOperand(Inst.getOperand(5));
8418     TmpInst.addOperand(Inst.getOperand(0));
8419     TmpInst.addOperand(Inst.getOperand(2));
8420     TmpInst.addOperand(Inst.getOperand(3));
8421     TmpInst.addOperand(Inst.getOperand(4));
8422     Inst = TmpInst;
8423     return true;
8424   }
8425   case ARM::t2ADDrr: {
8426     // If the destination and first source operand are the same, and
8427     // there's no setting of the flags, use encoding T2 instead of T3.
8428     // Note that this is only for ADD, not SUB. This mirrors the system
8429     // 'as' behaviour.  Also take advantage of ADD being commutative.
8430     // Make sure the wide encoding wasn't explicit.
8431     bool Swap = false;
8432     auto DestReg = Inst.getOperand(0).getReg();
8433     bool Transform = DestReg == Inst.getOperand(1).getReg();
8434     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
8435       Transform = true;
8436       Swap = true;
8437     }
8438     if (!Transform ||
8439         Inst.getOperand(5).getReg() != 0 ||
8440         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8441          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w"))
8442       break;
8443     MCInst TmpInst;
8444     TmpInst.setOpcode(ARM::tADDhirr);
8445     TmpInst.addOperand(Inst.getOperand(0));
8446     TmpInst.addOperand(Inst.getOperand(0));
8447     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
8448     TmpInst.addOperand(Inst.getOperand(3));
8449     TmpInst.addOperand(Inst.getOperand(4));
8450     Inst = TmpInst;
8451     return true;
8452   }
8453   case ARM::tADDrSP: {
8454     // If the non-SP source operand and the destination operand are not the
8455     // same, we need to use the 32-bit encoding if it's available.
8456     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
8457       Inst.setOpcode(ARM::t2ADDrr);
8458       Inst.addOperand(MCOperand::createReg(0)); // cc_out
8459       return true;
8460     }
8461     break;
8462   }
8463   case ARM::tB:
8464     // A Thumb conditional branch outside of an IT block is a tBcc.
8465     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
8466       Inst.setOpcode(ARM::tBcc);
8467       return true;
8468     }
8469     break;
8470   case ARM::t2B:
8471     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
8472     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
8473       Inst.setOpcode(ARM::t2Bcc);
8474       return true;
8475     }
8476     break;
8477   case ARM::t2Bcc:
8478     // If the conditional is AL or we're in an IT block, we really want t2B.
8479     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
8480       Inst.setOpcode(ARM::t2B);
8481       return true;
8482     }
8483     break;
8484   case ARM::tBcc:
8485     // If the conditional is AL, we really want tB.
8486     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
8487       Inst.setOpcode(ARM::tB);
8488       return true;
8489     }
8490     break;
8491   case ARM::tLDMIA: {
8492     // If the register list contains any high registers, or if the writeback
8493     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
8494     // instead if we're in Thumb2. Otherwise, this should have generated
8495     // an error in validateInstruction().
8496     unsigned Rn = Inst.getOperand(0).getReg();
8497     bool hasWritebackToken =
8498         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8499          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
8500     bool listContainsBase;
8501     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
8502         (!listContainsBase && !hasWritebackToken) ||
8503         (listContainsBase && hasWritebackToken)) {
8504       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8505       assert (isThumbTwo());
8506       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
8507       // If we're switching to the updating version, we need to insert
8508       // the writeback tied operand.
8509       if (hasWritebackToken)
8510         Inst.insert(Inst.begin(),
8511                     MCOperand::createReg(Inst.getOperand(0).getReg()));
8512       return true;
8513     }
8514     break;
8515   }
8516   case ARM::tSTMIA_UPD: {
8517     // If the register list contains any high registers, we need to use
8518     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8519     // should have generated an error in validateInstruction().
8520     unsigned Rn = Inst.getOperand(0).getReg();
8521     bool listContainsBase;
8522     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
8523       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8524       assert (isThumbTwo());
8525       Inst.setOpcode(ARM::t2STMIA_UPD);
8526       return true;
8527     }
8528     break;
8529   }
8530   case ARM::tPOP: {
8531     bool listContainsBase;
8532     // If the register list contains any high registers, we need to use
8533     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8534     // should have generated an error in validateInstruction().
8535     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
8536       return false;
8537     assert (isThumbTwo());
8538     Inst.setOpcode(ARM::t2LDMIA_UPD);
8539     // Add the base register and writeback operands.
8540     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8541     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8542     return true;
8543   }
8544   case ARM::tPUSH: {
8545     bool listContainsBase;
8546     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
8547       return false;
8548     assert (isThumbTwo());
8549     Inst.setOpcode(ARM::t2STMDB_UPD);
8550     // Add the base register and writeback operands.
8551     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8552     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8553     return true;
8554   }
8555   case ARM::t2MOVi: {
8556     // If we can use the 16-bit encoding and the user didn't explicitly
8557     // request the 32-bit variant, transform it here.
8558     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8559         (unsigned)Inst.getOperand(1).getImm() <= 255 &&
8560         ((!inITBlock() && Inst.getOperand(2).getImm() == ARMCC::AL &&
8561           Inst.getOperand(4).getReg() == ARM::CPSR) ||
8562          (inITBlock() && Inst.getOperand(4).getReg() == 0)) &&
8563         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8564          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8565       // The operands aren't in the same order for tMOVi8...
8566       MCInst TmpInst;
8567       TmpInst.setOpcode(ARM::tMOVi8);
8568       TmpInst.addOperand(Inst.getOperand(0));
8569       TmpInst.addOperand(Inst.getOperand(4));
8570       TmpInst.addOperand(Inst.getOperand(1));
8571       TmpInst.addOperand(Inst.getOperand(2));
8572       TmpInst.addOperand(Inst.getOperand(3));
8573       Inst = TmpInst;
8574       return true;
8575     }
8576     break;
8577   }
8578   case ARM::t2MOVr: {
8579     // If we can use the 16-bit encoding and the user didn't explicitly
8580     // request the 32-bit variant, transform it here.
8581     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8582         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8583         Inst.getOperand(2).getImm() == ARMCC::AL &&
8584         Inst.getOperand(4).getReg() == ARM::CPSR &&
8585         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8586          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8587       // The operands aren't the same for tMOV[S]r... (no cc_out)
8588       MCInst TmpInst;
8589       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
8590       TmpInst.addOperand(Inst.getOperand(0));
8591       TmpInst.addOperand(Inst.getOperand(1));
8592       TmpInst.addOperand(Inst.getOperand(2));
8593       TmpInst.addOperand(Inst.getOperand(3));
8594       Inst = TmpInst;
8595       return true;
8596     }
8597     break;
8598   }
8599   case ARM::t2SXTH:
8600   case ARM::t2SXTB:
8601   case ARM::t2UXTH:
8602   case ARM::t2UXTB: {
8603     // If we can use the 16-bit encoding and the user didn't explicitly
8604     // request the 32-bit variant, transform it here.
8605     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8606         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8607         Inst.getOperand(2).getImm() == 0 &&
8608         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8609          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8610       unsigned NewOpc;
8611       switch (Inst.getOpcode()) {
8612       default: llvm_unreachable("Illegal opcode!");
8613       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
8614       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
8615       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
8616       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
8617       }
8618       // The operands aren't the same for thumb1 (no rotate operand).
8619       MCInst TmpInst;
8620       TmpInst.setOpcode(NewOpc);
8621       TmpInst.addOperand(Inst.getOperand(0));
8622       TmpInst.addOperand(Inst.getOperand(1));
8623       TmpInst.addOperand(Inst.getOperand(3));
8624       TmpInst.addOperand(Inst.getOperand(4));
8625       Inst = TmpInst;
8626       return true;
8627     }
8628     break;
8629   }
8630   case ARM::MOVsi: {
8631     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8632     // rrx shifts and asr/lsr of #32 is encoded as 0
8633     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr)
8634       return false;
8635     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
8636       // Shifting by zero is accepted as a vanilla 'MOVr'
8637       MCInst TmpInst;
8638       TmpInst.setOpcode(ARM::MOVr);
8639       TmpInst.addOperand(Inst.getOperand(0));
8640       TmpInst.addOperand(Inst.getOperand(1));
8641       TmpInst.addOperand(Inst.getOperand(3));
8642       TmpInst.addOperand(Inst.getOperand(4));
8643       TmpInst.addOperand(Inst.getOperand(5));
8644       Inst = TmpInst;
8645       return true;
8646     }
8647     return false;
8648   }
8649   case ARM::ANDrsi:
8650   case ARM::ORRrsi:
8651   case ARM::EORrsi:
8652   case ARM::BICrsi:
8653   case ARM::SUBrsi:
8654   case ARM::ADDrsi: {
8655     unsigned newOpc;
8656     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
8657     if (SOpc == ARM_AM::rrx) return false;
8658     switch (Inst.getOpcode()) {
8659     default: llvm_unreachable("unexpected opcode!");
8660     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
8661     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
8662     case ARM::EORrsi: newOpc = ARM::EORrr; break;
8663     case ARM::BICrsi: newOpc = ARM::BICrr; break;
8664     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
8665     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
8666     }
8667     // If the shift is by zero, use the non-shifted instruction definition.
8668     // The exception is for right shifts, where 0 == 32
8669     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
8670         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
8671       MCInst TmpInst;
8672       TmpInst.setOpcode(newOpc);
8673       TmpInst.addOperand(Inst.getOperand(0));
8674       TmpInst.addOperand(Inst.getOperand(1));
8675       TmpInst.addOperand(Inst.getOperand(2));
8676       TmpInst.addOperand(Inst.getOperand(4));
8677       TmpInst.addOperand(Inst.getOperand(5));
8678       TmpInst.addOperand(Inst.getOperand(6));
8679       Inst = TmpInst;
8680       return true;
8681     }
8682     return false;
8683   }
8684   case ARM::ITasm:
8685   case ARM::t2IT: {
8686     MCOperand &MO = Inst.getOperand(1);
8687     unsigned Mask = MO.getImm();
8688     ARMCC::CondCodes Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
8689 
8690     // Set up the IT block state according to the IT instruction we just
8691     // matched.
8692     assert(!inITBlock() && "nested IT blocks?!");
8693     startExplicitITBlock(Cond, Mask);
8694     MO.setImm(getITMaskEncoding());
8695     break;
8696   }
8697   case ARM::t2LSLrr:
8698   case ARM::t2LSRrr:
8699   case ARM::t2ASRrr:
8700   case ARM::t2SBCrr:
8701   case ARM::t2RORrr:
8702   case ARM::t2BICrr:
8703   {
8704     // Assemblers should use the narrow encodings of these instructions when permissible.
8705     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8706          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8707         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8708         ((!inITBlock() && Inst.getOperand(5).getReg() == ARM::CPSR) ||
8709          (inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR)) &&
8710         (!static_cast<ARMOperand &>(*Operands[3]).isToken() ||
8711          !static_cast<ARMOperand &>(*Operands[3]).getToken().equals_lower(
8712              ".w"))) {
8713       unsigned NewOpc;
8714       switch (Inst.getOpcode()) {
8715         default: llvm_unreachable("unexpected opcode");
8716         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
8717         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
8718         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
8719         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
8720         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
8721         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
8722       }
8723       MCInst TmpInst;
8724       TmpInst.setOpcode(NewOpc);
8725       TmpInst.addOperand(Inst.getOperand(0));
8726       TmpInst.addOperand(Inst.getOperand(5));
8727       TmpInst.addOperand(Inst.getOperand(1));
8728       TmpInst.addOperand(Inst.getOperand(2));
8729       TmpInst.addOperand(Inst.getOperand(3));
8730       TmpInst.addOperand(Inst.getOperand(4));
8731       Inst = TmpInst;
8732       return true;
8733     }
8734     return false;
8735   }
8736   case ARM::t2ANDrr:
8737   case ARM::t2EORrr:
8738   case ARM::t2ADCrr:
8739   case ARM::t2ORRrr:
8740   {
8741     // Assemblers should use the narrow encodings of these instructions when permissible.
8742     // These instructions are special in that they are commutable, so shorter encodings
8743     // are available more often.
8744     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8745          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8746         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
8747          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
8748         ((!inITBlock() && Inst.getOperand(5).getReg() == ARM::CPSR) ||
8749          (inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR)) &&
8750         (!static_cast<ARMOperand &>(*Operands[3]).isToken() ||
8751          !static_cast<ARMOperand &>(*Operands[3]).getToken().equals_lower(
8752              ".w"))) {
8753       unsigned NewOpc;
8754       switch (Inst.getOpcode()) {
8755         default: llvm_unreachable("unexpected opcode");
8756         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
8757         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
8758         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
8759         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
8760       }
8761       MCInst TmpInst;
8762       TmpInst.setOpcode(NewOpc);
8763       TmpInst.addOperand(Inst.getOperand(0));
8764       TmpInst.addOperand(Inst.getOperand(5));
8765       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
8766         TmpInst.addOperand(Inst.getOperand(1));
8767         TmpInst.addOperand(Inst.getOperand(2));
8768       } else {
8769         TmpInst.addOperand(Inst.getOperand(2));
8770         TmpInst.addOperand(Inst.getOperand(1));
8771       }
8772       TmpInst.addOperand(Inst.getOperand(3));
8773       TmpInst.addOperand(Inst.getOperand(4));
8774       Inst = TmpInst;
8775       return true;
8776     }
8777     return false;
8778   }
8779   }
8780   return false;
8781 }
8782 
8783 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
8784   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
8785   // suffix depending on whether they're in an IT block or not.
8786   unsigned Opc = Inst.getOpcode();
8787   const MCInstrDesc &MCID = MII.get(Opc);
8788   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
8789     assert(MCID.hasOptionalDef() &&
8790            "optionally flag setting instruction missing optional def operand");
8791     assert(MCID.NumOperands == Inst.getNumOperands() &&
8792            "operand count mismatch!");
8793     // Find the optional-def operand (cc_out).
8794     unsigned OpNo;
8795     for (OpNo = 0;
8796          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
8797          ++OpNo)
8798       ;
8799     // If we're parsing Thumb1, reject it completely.
8800     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
8801       return Match_RequiresFlagSetting;
8802     // If we're parsing Thumb2, which form is legal depends on whether we're
8803     // in an IT block.
8804     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
8805         !inITBlock())
8806       return Match_RequiresITBlock;
8807     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
8808         inITBlock())
8809       return Match_RequiresNotITBlock;
8810     // LSL with zero immediate is not allowed in an IT block
8811     if (Opc == ARM::tLSLri && Inst.getOperand(3).getImm() == 0 && inITBlock())
8812       return Match_RequiresNotITBlock;
8813   } else if (isThumbOne()) {
8814     // Some high-register supporting Thumb1 encodings only allow both registers
8815     // to be from r0-r7 when in Thumb2.
8816     if (Opc == ARM::tADDhirr && !hasV6MOps() &&
8817         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8818         isARMLowRegister(Inst.getOperand(2).getReg()))
8819       return Match_RequiresThumb2;
8820     // Others only require ARMv6 or later.
8821     else if (Opc == ARM::tMOVr && !hasV6Ops() &&
8822              isARMLowRegister(Inst.getOperand(0).getReg()) &&
8823              isARMLowRegister(Inst.getOperand(1).getReg()))
8824       return Match_RequiresV6;
8825   }
8826 
8827   // Before ARMv8 the rules for when SP is allowed in t2MOVr are more complex
8828   // than the loop below can handle, so it uses the GPRnopc register class and
8829   // we do SP handling here.
8830   if (Opc == ARM::t2MOVr && !hasV8Ops())
8831   {
8832     // SP as both source and destination is not allowed
8833     if (Inst.getOperand(0).getReg() == ARM::SP &&
8834         Inst.getOperand(1).getReg() == ARM::SP)
8835       return Match_RequiresV8;
8836     // When flags-setting SP as either source or destination is not allowed
8837     if (Inst.getOperand(4).getReg() == ARM::CPSR &&
8838         (Inst.getOperand(0).getReg() == ARM::SP ||
8839          Inst.getOperand(1).getReg() == ARM::SP))
8840       return Match_RequiresV8;
8841   }
8842 
8843   for (unsigned I = 0; I < MCID.NumOperands; ++I)
8844     if (MCID.OpInfo[I].RegClass == ARM::rGPRRegClassID) {
8845       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
8846       if ((Inst.getOperand(I).getReg() == ARM::SP) && !hasV8Ops())
8847         return Match_RequiresV8;
8848       else if (Inst.getOperand(I).getReg() == ARM::PC)
8849         return Match_InvalidOperand;
8850     }
8851 
8852   return Match_Success;
8853 }
8854 
8855 namespace llvm {
8856 template <> inline bool IsCPSRDead<MCInst>(const MCInst *Instr) {
8857   return true; // In an assembly source, no need to second-guess
8858 }
8859 }
8860 
8861 // Returns true if Inst is unpredictable if it is in and IT block, but is not
8862 // the last instruction in the block.
8863 bool ARMAsmParser::isITBlockTerminator(MCInst &Inst) const {
8864   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8865 
8866   // All branch & call instructions terminate IT blocks.
8867   if (MCID.isTerminator() || MCID.isCall() || MCID.isReturn() ||
8868       MCID.isBranch() || MCID.isIndirectBranch())
8869     return true;
8870 
8871   // Any arithmetic instruction which writes to the PC also terminates the IT
8872   // block.
8873   for (unsigned OpIdx = 0; OpIdx < MCID.getNumDefs(); ++OpIdx) {
8874     MCOperand &Op = Inst.getOperand(OpIdx);
8875     if (Op.isReg() && Op.getReg() == ARM::PC)
8876       return true;
8877   }
8878 
8879   if (MCID.hasImplicitDefOfPhysReg(ARM::PC, MRI))
8880     return true;
8881 
8882   // Instructions with variable operand lists, which write to the variable
8883   // operands. We only care about Thumb instructions here, as ARM instructions
8884   // obviously can't be in an IT block.
8885   switch (Inst.getOpcode()) {
8886   case ARM::tLDMIA:
8887   case ARM::t2LDMIA:
8888   case ARM::t2LDMIA_UPD:
8889   case ARM::t2LDMDB:
8890   case ARM::t2LDMDB_UPD:
8891     if (listContainsReg(Inst, 3, ARM::PC))
8892       return true;
8893     break;
8894   case ARM::tPOP:
8895     if (listContainsReg(Inst, 2, ARM::PC))
8896       return true;
8897     break;
8898   }
8899 
8900   return false;
8901 }
8902 
8903 unsigned ARMAsmParser::MatchInstruction(OperandVector &Operands, MCInst &Inst,
8904                                           uint64_t &ErrorInfo,
8905                                           bool MatchingInlineAsm,
8906                                           bool &EmitInITBlock,
8907                                           MCStreamer &Out) {
8908   // If we can't use an implicit IT block here, just match as normal.
8909   if (inExplicitITBlock() || !isThumbTwo() || !useImplicitITThumb())
8910     return MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
8911 
8912   // Try to match the instruction in an extension of the current IT block (if
8913   // there is one).
8914   if (inImplicitITBlock()) {
8915     extendImplicitITBlock(ITState.Cond);
8916     if (MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm) ==
8917             Match_Success) {
8918       // The match succeded, but we still have to check that the instruction is
8919       // valid in this implicit IT block.
8920       const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8921       if (MCID.isPredicable()) {
8922         ARMCC::CondCodes InstCond =
8923             (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
8924                 .getImm();
8925         ARMCC::CondCodes ITCond = currentITCond();
8926         if (InstCond == ITCond) {
8927           EmitInITBlock = true;
8928           return Match_Success;
8929         } else if (InstCond == ARMCC::getOppositeCondition(ITCond)) {
8930           invertCurrentITCondition();
8931           EmitInITBlock = true;
8932           return Match_Success;
8933         }
8934       }
8935     }
8936     rewindImplicitITPosition();
8937   }
8938 
8939   // Finish the current IT block, and try to match outside any IT block.
8940   flushPendingInstructions(Out);
8941   unsigned PlainMatchResult =
8942       MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
8943   if (PlainMatchResult == Match_Success) {
8944     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8945     if (MCID.isPredicable()) {
8946       ARMCC::CondCodes InstCond =
8947           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
8948               .getImm();
8949       // Some forms of the branch instruction have their own condition code
8950       // fields, so can be conditionally executed without an IT block.
8951       if (Inst.getOpcode() == ARM::tBcc || Inst.getOpcode() == ARM::t2Bcc) {
8952         EmitInITBlock = false;
8953         return Match_Success;
8954       }
8955       if (InstCond == ARMCC::AL) {
8956         EmitInITBlock = false;
8957         return Match_Success;
8958       }
8959     } else {
8960       EmitInITBlock = false;
8961       return Match_Success;
8962     }
8963   }
8964 
8965   // Try to match in a new IT block. The matcher doesn't check the actual
8966   // condition, so we create an IT block with a dummy condition, and fix it up
8967   // once we know the actual condition.
8968   startImplicitITBlock();
8969   if (MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm) ==
8970       Match_Success) {
8971     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8972     if (MCID.isPredicable()) {
8973       ITState.Cond =
8974           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
8975               .getImm();
8976       EmitInITBlock = true;
8977       return Match_Success;
8978     }
8979   }
8980   discardImplicitITBlock();
8981 
8982   // If none of these succeed, return the error we got when trying to match
8983   // outside any IT blocks.
8984   EmitInITBlock = false;
8985   return PlainMatchResult;
8986 }
8987 
8988 static const char *getSubtargetFeatureName(uint64_t Val);
8989 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
8990                                            OperandVector &Operands,
8991                                            MCStreamer &Out, uint64_t &ErrorInfo,
8992                                            bool MatchingInlineAsm) {
8993   MCInst Inst;
8994   unsigned MatchResult;
8995   bool PendConditionalInstruction = false;
8996 
8997   MatchResult = MatchInstruction(Operands, Inst, ErrorInfo, MatchingInlineAsm,
8998                                  PendConditionalInstruction, Out);
8999 
9000   SMLoc ErrorLoc;
9001   if (ErrorInfo < Operands.size()) {
9002     ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
9003     if (ErrorLoc == SMLoc())
9004       ErrorLoc = IDLoc;
9005   }
9006 
9007   switch (MatchResult) {
9008   case Match_Success:
9009     // Context sensitive operand constraints aren't handled by the matcher,
9010     // so check them here.
9011     if (validateInstruction(Inst, Operands)) {
9012       // Still progress the IT block, otherwise one wrong condition causes
9013       // nasty cascading errors.
9014       forwardITPosition();
9015       return true;
9016     }
9017 
9018     { // processInstruction() updates inITBlock state, we need to save it away
9019       bool wasInITBlock = inITBlock();
9020 
9021       // Some instructions need post-processing to, for example, tweak which
9022       // encoding is selected. Loop on it while changes happen so the
9023       // individual transformations can chain off each other. E.g.,
9024       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
9025       while (processInstruction(Inst, Operands, Out))
9026         ;
9027 
9028       // Only after the instruction is fully processed, we can validate it
9029       if (wasInITBlock && hasV8Ops() && isThumb() &&
9030           !isV8EligibleForIT(&Inst)) {
9031         Warning(IDLoc, "deprecated instruction in IT block");
9032       }
9033     }
9034 
9035     // Only move forward at the very end so that everything in validate
9036     // and process gets a consistent answer about whether we're in an IT
9037     // block.
9038     forwardITPosition();
9039 
9040     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
9041     // doesn't actually encode.
9042     if (Inst.getOpcode() == ARM::ITasm)
9043       return false;
9044 
9045     Inst.setLoc(IDLoc);
9046     if (PendConditionalInstruction) {
9047       PendingConditionalInsts.push_back(Inst);
9048       if (isITBlockFull() || isITBlockTerminator(Inst))
9049         flushPendingInstructions(Out);
9050     } else {
9051       Out.EmitInstruction(Inst, getSTI());
9052     }
9053     return false;
9054   case Match_MissingFeature: {
9055     assert(ErrorInfo && "Unknown missing feature!");
9056     // Special case the error message for the very common case where only
9057     // a single subtarget feature is missing (Thumb vs. ARM, e.g.).
9058     std::string Msg = "instruction requires:";
9059     uint64_t Mask = 1;
9060     for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
9061       if (ErrorInfo & Mask) {
9062         Msg += " ";
9063         Msg += getSubtargetFeatureName(ErrorInfo & Mask);
9064       }
9065       Mask <<= 1;
9066     }
9067     return Error(IDLoc, Msg);
9068   }
9069   case Match_InvalidOperand: {
9070     SMLoc ErrorLoc = IDLoc;
9071     if (ErrorInfo != ~0ULL) {
9072       if (ErrorInfo >= Operands.size())
9073         return Error(IDLoc, "too few operands for instruction");
9074 
9075       ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
9076       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
9077     }
9078 
9079     return Error(ErrorLoc, "invalid operand for instruction");
9080   }
9081   case Match_MnemonicFail:
9082     return Error(IDLoc, "invalid instruction",
9083                  ((ARMOperand &)*Operands[0]).getLocRange());
9084   case Match_RequiresNotITBlock:
9085     return Error(IDLoc, "flag setting instruction only valid outside IT block");
9086   case Match_RequiresITBlock:
9087     return Error(IDLoc, "instruction only valid inside IT block");
9088   case Match_RequiresV6:
9089     return Error(IDLoc, "instruction variant requires ARMv6 or later");
9090   case Match_RequiresThumb2:
9091     return Error(IDLoc, "instruction variant requires Thumb2");
9092   case Match_RequiresV8:
9093     return Error(IDLoc, "instruction variant requires ARMv8 or later");
9094   case Match_RequiresFlagSetting:
9095     return Error(IDLoc, "no flag-preserving variant of this instruction available");
9096   case Match_ImmRange0_1:
9097     return Error(ErrorLoc, "immediate operand must be in the range [0,1]");
9098   case Match_ImmRange0_3:
9099     return Error(ErrorLoc, "immediate operand must be in the range [0,3]");
9100   case Match_ImmRange0_7:
9101     return Error(ErrorLoc, "immediate operand must be in the range [0,7]");
9102   case Match_ImmRange0_15:
9103     return Error(ErrorLoc, "immediate operand must be in the range [0,15]");
9104   case Match_ImmRange0_31:
9105     return Error(ErrorLoc, "immediate operand must be in the range [0,31]");
9106   case Match_ImmRange0_32:
9107     return Error(ErrorLoc, "immediate operand must be in the range [0,32]");
9108   case Match_ImmRange0_63:
9109     return Error(ErrorLoc, "immediate operand must be in the range [0,63]");
9110   case Match_ImmRange0_239:
9111     return Error(ErrorLoc, "immediate operand must be in the range [0,239]");
9112   case Match_ImmRange0_255:
9113     return Error(ErrorLoc, "immediate operand must be in the range [0,255]");
9114   case Match_ImmRange0_4095:
9115     return Error(ErrorLoc, "immediate operand must be in the range [0,4095]");
9116   case Match_ImmRange0_65535:
9117     return Error(ErrorLoc, "immediate operand must be in the range [0,65535]");
9118   case Match_ImmRange1_7:
9119     return Error(ErrorLoc, "immediate operand must be in the range [1,7]");
9120   case Match_ImmRange1_8:
9121     return Error(ErrorLoc, "immediate operand must be in the range [1,8]");
9122   case Match_ImmRange1_15:
9123     return Error(ErrorLoc, "immediate operand must be in the range [1,15]");
9124   case Match_ImmRange1_16:
9125     return Error(ErrorLoc, "immediate operand must be in the range [1,16]");
9126   case Match_ImmRange1_31:
9127     return Error(ErrorLoc, "immediate operand must be in the range [1,31]");
9128   case Match_ImmRange1_32:
9129     return Error(ErrorLoc, "immediate operand must be in the range [1,32]");
9130   case Match_ImmRange1_64:
9131     return Error(ErrorLoc, "immediate operand must be in the range [1,64]");
9132   case Match_ImmRange8_8:
9133     return Error(ErrorLoc, "immediate operand must be 8.");
9134   case Match_ImmRange16_16:
9135     return Error(ErrorLoc, "immediate operand must be 16.");
9136   case Match_ImmRange32_32:
9137     return Error(ErrorLoc, "immediate operand must be 32.");
9138   case Match_ImmRange256_65535:
9139     return Error(ErrorLoc, "immediate operand must be in the range [255,65535]");
9140   case Match_ImmRange0_16777215:
9141     return Error(ErrorLoc, "immediate operand must be in the range [0,0xffffff]");
9142   case Match_AlignedMemoryRequiresNone:
9143   case Match_DupAlignedMemoryRequiresNone:
9144   case Match_AlignedMemoryRequires16:
9145   case Match_DupAlignedMemoryRequires16:
9146   case Match_AlignedMemoryRequires32:
9147   case Match_DupAlignedMemoryRequires32:
9148   case Match_AlignedMemoryRequires64:
9149   case Match_DupAlignedMemoryRequires64:
9150   case Match_AlignedMemoryRequires64or128:
9151   case Match_DupAlignedMemoryRequires64or128:
9152   case Match_AlignedMemoryRequires64or128or256:
9153   {
9154     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getAlignmentLoc();
9155     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
9156     switch (MatchResult) {
9157       default:
9158         llvm_unreachable("Missing Match_Aligned type");
9159       case Match_AlignedMemoryRequiresNone:
9160       case Match_DupAlignedMemoryRequiresNone:
9161         return Error(ErrorLoc, "alignment must be omitted");
9162       case Match_AlignedMemoryRequires16:
9163       case Match_DupAlignedMemoryRequires16:
9164         return Error(ErrorLoc, "alignment must be 16 or omitted");
9165       case Match_AlignedMemoryRequires32:
9166       case Match_DupAlignedMemoryRequires32:
9167         return Error(ErrorLoc, "alignment must be 32 or omitted");
9168       case Match_AlignedMemoryRequires64:
9169       case Match_DupAlignedMemoryRequires64:
9170         return Error(ErrorLoc, "alignment must be 64 or omitted");
9171       case Match_AlignedMemoryRequires64or128:
9172       case Match_DupAlignedMemoryRequires64or128:
9173         return Error(ErrorLoc, "alignment must be 64, 128 or omitted");
9174       case Match_AlignedMemoryRequires64or128or256:
9175         return Error(ErrorLoc, "alignment must be 64, 128, 256 or omitted");
9176     }
9177   }
9178   }
9179 
9180   llvm_unreachable("Implement any new match types added!");
9181 }
9182 
9183 /// parseDirective parses the arm specific directives
9184 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
9185   const MCObjectFileInfo::Environment Format =
9186     getContext().getObjectFileInfo()->getObjectFileType();
9187   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9188   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
9189 
9190   StringRef IDVal = DirectiveID.getIdentifier();
9191   if (IDVal == ".word")
9192     parseLiteralValues(4, DirectiveID.getLoc());
9193   else if (IDVal == ".short" || IDVal == ".hword")
9194     parseLiteralValues(2, DirectiveID.getLoc());
9195   else if (IDVal == ".thumb")
9196     parseDirectiveThumb(DirectiveID.getLoc());
9197   else if (IDVal == ".arm")
9198     parseDirectiveARM(DirectiveID.getLoc());
9199   else if (IDVal == ".thumb_func")
9200     parseDirectiveThumbFunc(DirectiveID.getLoc());
9201   else if (IDVal == ".code")
9202     parseDirectiveCode(DirectiveID.getLoc());
9203   else if (IDVal == ".syntax")
9204     parseDirectiveSyntax(DirectiveID.getLoc());
9205   else if (IDVal == ".unreq")
9206     parseDirectiveUnreq(DirectiveID.getLoc());
9207   else if (IDVal == ".fnend")
9208     parseDirectiveFnEnd(DirectiveID.getLoc());
9209   else if (IDVal == ".cantunwind")
9210     parseDirectiveCantUnwind(DirectiveID.getLoc());
9211   else if (IDVal == ".personality")
9212     parseDirectivePersonality(DirectiveID.getLoc());
9213   else if (IDVal == ".handlerdata")
9214     parseDirectiveHandlerData(DirectiveID.getLoc());
9215   else if (IDVal == ".setfp")
9216     parseDirectiveSetFP(DirectiveID.getLoc());
9217   else if (IDVal == ".pad")
9218     parseDirectivePad(DirectiveID.getLoc());
9219   else if (IDVal == ".save")
9220     parseDirectiveRegSave(DirectiveID.getLoc(), false);
9221   else if (IDVal == ".vsave")
9222     parseDirectiveRegSave(DirectiveID.getLoc(), true);
9223   else if (IDVal == ".ltorg" || IDVal == ".pool")
9224     parseDirectiveLtorg(DirectiveID.getLoc());
9225   else if (IDVal == ".even")
9226     parseDirectiveEven(DirectiveID.getLoc());
9227   else if (IDVal == ".personalityindex")
9228     parseDirectivePersonalityIndex(DirectiveID.getLoc());
9229   else if (IDVal == ".unwind_raw")
9230     parseDirectiveUnwindRaw(DirectiveID.getLoc());
9231   else if (IDVal == ".movsp")
9232     parseDirectiveMovSP(DirectiveID.getLoc());
9233   else if (IDVal == ".arch_extension")
9234     parseDirectiveArchExtension(DirectiveID.getLoc());
9235   else if (IDVal == ".align")
9236     return parseDirectiveAlign(DirectiveID.getLoc()); // Use Generic on failure.
9237   else if (IDVal == ".thumb_set")
9238     parseDirectiveThumbSet(DirectiveID.getLoc());
9239   else if (!IsMachO && !IsCOFF) {
9240     if (IDVal == ".arch")
9241       parseDirectiveArch(DirectiveID.getLoc());
9242     else if (IDVal == ".cpu")
9243       parseDirectiveCPU(DirectiveID.getLoc());
9244     else if (IDVal == ".eabi_attribute")
9245       parseDirectiveEabiAttr(DirectiveID.getLoc());
9246     else if (IDVal == ".fpu")
9247       parseDirectiveFPU(DirectiveID.getLoc());
9248     else if (IDVal == ".fnstart")
9249       parseDirectiveFnStart(DirectiveID.getLoc());
9250     else if (IDVal == ".inst")
9251       parseDirectiveInst(DirectiveID.getLoc());
9252     else if (IDVal == ".inst.n")
9253       parseDirectiveInst(DirectiveID.getLoc(), 'n');
9254     else if (IDVal == ".inst.w")
9255       parseDirectiveInst(DirectiveID.getLoc(), 'w');
9256     else if (IDVal == ".object_arch")
9257       parseDirectiveObjectArch(DirectiveID.getLoc());
9258     else if (IDVal == ".tlsdescseq")
9259       parseDirectiveTLSDescSeq(DirectiveID.getLoc());
9260     else
9261       return true;
9262   } else
9263     return true;
9264   return false;
9265 }
9266 
9267 /// parseLiteralValues
9268 ///  ::= .hword expression [, expression]*
9269 ///  ::= .short expression [, expression]*
9270 ///  ::= .word expression [, expression]*
9271 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
9272   auto parseOne = [&]() -> bool {
9273     const MCExpr *Value;
9274     if (getParser().parseExpression(Value))
9275       return true;
9276     getParser().getStreamer().EmitValue(Value, Size, L);
9277     return false;
9278   };
9279   return (parseMany(parseOne));
9280 }
9281 
9282 /// parseDirectiveThumb
9283 ///  ::= .thumb
9284 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
9285   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9286       check(!hasThumb(), L, "target does not support Thumb mode"))
9287     return true;
9288 
9289   if (!isThumb())
9290     SwitchMode();
9291 
9292   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9293   return false;
9294 }
9295 
9296 /// parseDirectiveARM
9297 ///  ::= .arm
9298 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
9299   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9300       check(!hasARM(), L, "target does not support ARM mode"))
9301     return true;
9302 
9303   if (isThumb())
9304     SwitchMode();
9305   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9306   return false;
9307 }
9308 
9309 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
9310   // We need to flush the current implicit IT block on a label, because it is
9311   // not legal to branch into an IT block.
9312   flushPendingInstructions(getStreamer());
9313   if (NextSymbolIsThumb) {
9314     getParser().getStreamer().EmitThumbFunc(Symbol);
9315     NextSymbolIsThumb = false;
9316   }
9317 }
9318 
9319 /// parseDirectiveThumbFunc
9320 ///  ::= .thumbfunc symbol_name
9321 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
9322   MCAsmParser &Parser = getParser();
9323   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
9324   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9325 
9326   // Darwin asm has (optionally) function name after .thumb_func direction
9327   // ELF doesn't
9328 
9329   if (IsMachO) {
9330     if (Parser.getTok().is(AsmToken::Identifier) ||
9331         Parser.getTok().is(AsmToken::String)) {
9332       MCSymbol *Func = getParser().getContext().getOrCreateSymbol(
9333           Parser.getTok().getIdentifier());
9334       getParser().getStreamer().EmitThumbFunc(Func);
9335       Parser.Lex();
9336       if (parseToken(AsmToken::EndOfStatement,
9337                      "unexpected token in '.thumb_func' directive"))
9338         return true;
9339       return false;
9340     }
9341   }
9342 
9343   if (parseToken(AsmToken::EndOfStatement,
9344                  "unexpected token in '.thumb_func' directive"))
9345     return true;
9346 
9347   NextSymbolIsThumb = true;
9348   return false;
9349 }
9350 
9351 /// parseDirectiveSyntax
9352 ///  ::= .syntax unified | divided
9353 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
9354   MCAsmParser &Parser = getParser();
9355   const AsmToken &Tok = Parser.getTok();
9356   if (Tok.isNot(AsmToken::Identifier)) {
9357     Error(L, "unexpected token in .syntax directive");
9358     return false;
9359   }
9360 
9361   StringRef Mode = Tok.getString();
9362   Parser.Lex();
9363   if (check(Mode == "divided" || Mode == "DIVIDED", L,
9364             "'.syntax divided' arm assembly not supported") ||
9365       check(Mode != "unified" && Mode != "UNIFIED", L,
9366             "unrecognized syntax mode in .syntax directive") ||
9367       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9368     return true;
9369 
9370   // TODO tell the MC streamer the mode
9371   // getParser().getStreamer().Emit???();
9372   return false;
9373 }
9374 
9375 /// parseDirectiveCode
9376 ///  ::= .code 16 | 32
9377 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
9378   MCAsmParser &Parser = getParser();
9379   const AsmToken &Tok = Parser.getTok();
9380   if (Tok.isNot(AsmToken::Integer))
9381     return Error(L, "unexpected token in .code directive");
9382   int64_t Val = Parser.getTok().getIntVal();
9383   if (Val != 16 && Val != 32) {
9384     Error(L, "invalid operand to .code directive");
9385     return false;
9386   }
9387   Parser.Lex();
9388 
9389   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9390     return true;
9391 
9392   if (Val == 16) {
9393     if (!hasThumb())
9394       return Error(L, "target does not support Thumb mode");
9395 
9396     if (!isThumb())
9397       SwitchMode();
9398     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9399   } else {
9400     if (!hasARM())
9401       return Error(L, "target does not support ARM mode");
9402 
9403     if (isThumb())
9404       SwitchMode();
9405     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9406   }
9407 
9408   return false;
9409 }
9410 
9411 /// parseDirectiveReq
9412 ///  ::= name .req registername
9413 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
9414   MCAsmParser &Parser = getParser();
9415   Parser.Lex(); // Eat the '.req' token.
9416   unsigned Reg;
9417   SMLoc SRegLoc, ERegLoc;
9418   if (check(ParseRegister(Reg, SRegLoc, ERegLoc), SRegLoc,
9419             "register name expected") ||
9420       parseToken(AsmToken::EndOfStatement,
9421                  "unexpected input in .req directive."))
9422     return true;
9423 
9424   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg)
9425     return Error(SRegLoc,
9426                  "redefinition of '" + Name + "' does not match original.");
9427 
9428   return false;
9429 }
9430 
9431 /// parseDirectiveUneq
9432 ///  ::= .unreq registername
9433 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
9434   MCAsmParser &Parser = getParser();
9435   if (Parser.getTok().isNot(AsmToken::Identifier))
9436     return Error(L, "unexpected input in .unreq directive.");
9437   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
9438   Parser.Lex(); // Eat the identifier.
9439   if (parseToken(AsmToken::EndOfStatement,
9440                  "unexpected input in '.unreq' directive"))
9441     return true;
9442   return false;
9443 }
9444 
9445 // After changing arch/CPU, try to put the ARM/Thumb mode back to what it was
9446 // before, if supported by the new target, or emit mapping symbols for the mode
9447 // switch.
9448 void ARMAsmParser::FixModeAfterArchChange(bool WasThumb, SMLoc Loc) {
9449   if (WasThumb != isThumb()) {
9450     if (WasThumb && hasThumb()) {
9451       // Stay in Thumb mode
9452       SwitchMode();
9453     } else if (!WasThumb && hasARM()) {
9454       // Stay in ARM mode
9455       SwitchMode();
9456     } else {
9457       // Mode switch forced, because the new arch doesn't support the old mode.
9458       getParser().getStreamer().EmitAssemblerFlag(isThumb() ? MCAF_Code16
9459                                                             : MCAF_Code32);
9460       // Warn about the implcit mode switch. GAS does not switch modes here,
9461       // but instead stays in the old mode, reporting an error on any following
9462       // instructions as the mode does not exist on the target.
9463       Warning(Loc, Twine("new target does not support ") +
9464                        (WasThumb ? "thumb" : "arm") + " mode, switching to " +
9465                        (!WasThumb ? "thumb" : "arm") + " mode");
9466     }
9467   }
9468 }
9469 
9470 /// parseDirectiveArch
9471 ///  ::= .arch token
9472 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
9473   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
9474   unsigned ID = ARM::parseArch(Arch);
9475 
9476   if (ID == ARM::AK_INVALID)
9477     return Error(L, "Unknown arch name");
9478 
9479   bool WasThumb = isThumb();
9480   Triple T;
9481   MCSubtargetInfo &STI = copySTI();
9482   STI.setDefaultFeatures("", ("+" + ARM::getArchName(ID)).str());
9483   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9484   FixModeAfterArchChange(WasThumb, L);
9485 
9486   getTargetStreamer().emitArch(ID);
9487   return false;
9488 }
9489 
9490 /// parseDirectiveEabiAttr
9491 ///  ::= .eabi_attribute int, int [, "str"]
9492 ///  ::= .eabi_attribute Tag_name, int [, "str"]
9493 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
9494   MCAsmParser &Parser = getParser();
9495   int64_t Tag;
9496   SMLoc TagLoc;
9497   TagLoc = Parser.getTok().getLoc();
9498   if (Parser.getTok().is(AsmToken::Identifier)) {
9499     StringRef Name = Parser.getTok().getIdentifier();
9500     Tag = ARMBuildAttrs::AttrTypeFromString(Name);
9501     if (Tag == -1) {
9502       Error(TagLoc, "attribute name not recognised: " + Name);
9503       return false;
9504     }
9505     Parser.Lex();
9506   } else {
9507     const MCExpr *AttrExpr;
9508 
9509     TagLoc = Parser.getTok().getLoc();
9510     if (Parser.parseExpression(AttrExpr))
9511       return true;
9512 
9513     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
9514     if (check(!CE, TagLoc, "expected numeric constant"))
9515       return true;
9516 
9517     Tag = CE->getValue();
9518   }
9519 
9520   if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9521     return true;
9522 
9523   StringRef StringValue = "";
9524   bool IsStringValue = false;
9525 
9526   int64_t IntegerValue = 0;
9527   bool IsIntegerValue = false;
9528 
9529   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
9530     IsStringValue = true;
9531   else if (Tag == ARMBuildAttrs::compatibility) {
9532     IsStringValue = true;
9533     IsIntegerValue = true;
9534   } else if (Tag < 32 || Tag % 2 == 0)
9535     IsIntegerValue = true;
9536   else if (Tag % 2 == 1)
9537     IsStringValue = true;
9538   else
9539     llvm_unreachable("invalid tag type");
9540 
9541   if (IsIntegerValue) {
9542     const MCExpr *ValueExpr;
9543     SMLoc ValueExprLoc = Parser.getTok().getLoc();
9544     if (Parser.parseExpression(ValueExpr))
9545       return true;
9546 
9547     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
9548     if (!CE)
9549       return Error(ValueExprLoc, "expected numeric constant");
9550     IntegerValue = CE->getValue();
9551   }
9552 
9553   if (Tag == ARMBuildAttrs::compatibility) {
9554     if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9555       return true;
9556   }
9557 
9558   if (IsStringValue) {
9559     if (Parser.getTok().isNot(AsmToken::String))
9560       return Error(Parser.getTok().getLoc(), "bad string constant");
9561 
9562     StringValue = Parser.getTok().getStringContents();
9563     Parser.Lex();
9564   }
9565 
9566   if (Parser.parseToken(AsmToken::EndOfStatement,
9567                         "unexpected token in '.eabi_attribute' directive"))
9568     return true;
9569 
9570   if (IsIntegerValue && IsStringValue) {
9571     assert(Tag == ARMBuildAttrs::compatibility);
9572     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
9573   } else if (IsIntegerValue)
9574     getTargetStreamer().emitAttribute(Tag, IntegerValue);
9575   else if (IsStringValue)
9576     getTargetStreamer().emitTextAttribute(Tag, StringValue);
9577   return false;
9578 }
9579 
9580 /// parseDirectiveCPU
9581 ///  ::= .cpu str
9582 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
9583   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
9584   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
9585 
9586   // FIXME: This is using table-gen data, but should be moved to
9587   // ARMTargetParser once that is table-gen'd.
9588   if (!getSTI().isCPUStringValid(CPU))
9589     return Error(L, "Unknown CPU name");
9590 
9591   bool WasThumb = isThumb();
9592   MCSubtargetInfo &STI = copySTI();
9593   STI.setDefaultFeatures(CPU, "");
9594   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9595   FixModeAfterArchChange(WasThumb, L);
9596 
9597   return false;
9598 }
9599 /// parseDirectiveFPU
9600 ///  ::= .fpu str
9601 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
9602   SMLoc FPUNameLoc = getTok().getLoc();
9603   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
9604 
9605   unsigned ID = ARM::parseFPU(FPU);
9606   std::vector<StringRef> Features;
9607   if (!ARM::getFPUFeatures(ID, Features))
9608     return Error(FPUNameLoc, "Unknown FPU name");
9609 
9610   MCSubtargetInfo &STI = copySTI();
9611   for (auto Feature : Features)
9612     STI.ApplyFeatureFlag(Feature);
9613   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9614 
9615   getTargetStreamer().emitFPU(ID);
9616   return false;
9617 }
9618 
9619 /// parseDirectiveFnStart
9620 ///  ::= .fnstart
9621 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
9622   if (parseToken(AsmToken::EndOfStatement,
9623                  "unexpected token in '.fnstart' directive"))
9624     return true;
9625 
9626   if (UC.hasFnStart()) {
9627     Error(L, ".fnstart starts before the end of previous one");
9628     UC.emitFnStartLocNotes();
9629     return true;
9630   }
9631 
9632   // Reset the unwind directives parser state
9633   UC.reset();
9634 
9635   getTargetStreamer().emitFnStart();
9636 
9637   UC.recordFnStart(L);
9638   return false;
9639 }
9640 
9641 /// parseDirectiveFnEnd
9642 ///  ::= .fnend
9643 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
9644   if (parseToken(AsmToken::EndOfStatement,
9645                  "unexpected token in '.fnend' directive"))
9646     return true;
9647   // Check the ordering of unwind directives
9648   if (!UC.hasFnStart())
9649     return Error(L, ".fnstart must precede .fnend directive");
9650 
9651   // Reset the unwind directives parser state
9652   getTargetStreamer().emitFnEnd();
9653 
9654   UC.reset();
9655   return false;
9656 }
9657 
9658 /// parseDirectiveCantUnwind
9659 ///  ::= .cantunwind
9660 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
9661   if (parseToken(AsmToken::EndOfStatement,
9662                  "unexpected token in '.cantunwind' directive"))
9663     return true;
9664 
9665   UC.recordCantUnwind(L);
9666   // Check the ordering of unwind directives
9667   if (check(!UC.hasFnStart(), L, ".fnstart must precede .cantunwind directive"))
9668     return true;
9669 
9670   if (UC.hasHandlerData()) {
9671     Error(L, ".cantunwind can't be used with .handlerdata directive");
9672     UC.emitHandlerDataLocNotes();
9673     return true;
9674   }
9675   if (UC.hasPersonality()) {
9676     Error(L, ".cantunwind can't be used with .personality directive");
9677     UC.emitPersonalityLocNotes();
9678     return true;
9679   }
9680 
9681   getTargetStreamer().emitCantUnwind();
9682   return false;
9683 }
9684 
9685 /// parseDirectivePersonality
9686 ///  ::= .personality name
9687 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
9688   MCAsmParser &Parser = getParser();
9689   bool HasExistingPersonality = UC.hasPersonality();
9690 
9691   // Parse the name of the personality routine
9692   if (Parser.getTok().isNot(AsmToken::Identifier))
9693     return Error(L, "unexpected input in .personality directive.");
9694   StringRef Name(Parser.getTok().getIdentifier());
9695   Parser.Lex();
9696 
9697   if (parseToken(AsmToken::EndOfStatement,
9698                  "unexpected token in '.personality' directive"))
9699     return true;
9700 
9701   UC.recordPersonality(L);
9702 
9703   // Check the ordering of unwind directives
9704   if (!UC.hasFnStart())
9705     return Error(L, ".fnstart must precede .personality directive");
9706   if (UC.cantUnwind()) {
9707     Error(L, ".personality can't be used with .cantunwind directive");
9708     UC.emitCantUnwindLocNotes();
9709     return true;
9710   }
9711   if (UC.hasHandlerData()) {
9712     Error(L, ".personality must precede .handlerdata directive");
9713     UC.emitHandlerDataLocNotes();
9714     return true;
9715   }
9716   if (HasExistingPersonality) {
9717     Error(L, "multiple personality directives");
9718     UC.emitPersonalityLocNotes();
9719     return true;
9720   }
9721 
9722   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
9723   getTargetStreamer().emitPersonality(PR);
9724   return false;
9725 }
9726 
9727 /// parseDirectiveHandlerData
9728 ///  ::= .handlerdata
9729 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
9730   if (parseToken(AsmToken::EndOfStatement,
9731                  "unexpected token in '.handlerdata' directive"))
9732     return true;
9733 
9734   UC.recordHandlerData(L);
9735   // Check the ordering of unwind directives
9736   if (!UC.hasFnStart())
9737     return Error(L, ".fnstart must precede .personality directive");
9738   if (UC.cantUnwind()) {
9739     Error(L, ".handlerdata can't be used with .cantunwind directive");
9740     UC.emitCantUnwindLocNotes();
9741     return true;
9742   }
9743 
9744   getTargetStreamer().emitHandlerData();
9745   return false;
9746 }
9747 
9748 /// parseDirectiveSetFP
9749 ///  ::= .setfp fpreg, spreg [, offset]
9750 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
9751   MCAsmParser &Parser = getParser();
9752   // Check the ordering of unwind directives
9753   if (check(!UC.hasFnStart(), L, ".fnstart must precede .setfp directive") ||
9754       check(UC.hasHandlerData(), L,
9755             ".setfp must precede .handlerdata directive"))
9756     return true;
9757 
9758   // Parse fpreg
9759   SMLoc FPRegLoc = Parser.getTok().getLoc();
9760   int FPReg = tryParseRegister();
9761 
9762   if (check(FPReg == -1, FPRegLoc, "frame pointer register expected") ||
9763       Parser.parseToken(AsmToken::Comma, "comma expected"))
9764     return true;
9765 
9766   // Parse spreg
9767   SMLoc SPRegLoc = Parser.getTok().getLoc();
9768   int SPReg = tryParseRegister();
9769   if (check(SPReg == -1, SPRegLoc, "stack pointer register expected") ||
9770       check(SPReg != ARM::SP && SPReg != UC.getFPReg(), SPRegLoc,
9771             "register should be either $sp or the latest fp register"))
9772     return true;
9773 
9774   // Update the frame pointer register
9775   UC.saveFPReg(FPReg);
9776 
9777   // Parse offset
9778   int64_t Offset = 0;
9779   if (Parser.parseOptionalToken(AsmToken::Comma)) {
9780     if (Parser.getTok().isNot(AsmToken::Hash) &&
9781         Parser.getTok().isNot(AsmToken::Dollar))
9782       return Error(Parser.getTok().getLoc(), "'#' expected");
9783     Parser.Lex(); // skip hash token.
9784 
9785     const MCExpr *OffsetExpr;
9786     SMLoc ExLoc = Parser.getTok().getLoc();
9787     SMLoc EndLoc;
9788     if (getParser().parseExpression(OffsetExpr, EndLoc))
9789       return Error(ExLoc, "malformed setfp offset");
9790     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9791     if (check(!CE, ExLoc, "setfp offset must be an immediate"))
9792       return true;
9793     Offset = CE->getValue();
9794   }
9795 
9796   if (Parser.parseToken(AsmToken::EndOfStatement))
9797     return true;
9798 
9799   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
9800                                 static_cast<unsigned>(SPReg), Offset);
9801   return false;
9802 }
9803 
9804 /// parseDirective
9805 ///  ::= .pad offset
9806 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
9807   MCAsmParser &Parser = getParser();
9808   // Check the ordering of unwind directives
9809   if (!UC.hasFnStart())
9810     return Error(L, ".fnstart must precede .pad directive");
9811   if (UC.hasHandlerData())
9812     return Error(L, ".pad must precede .handlerdata directive");
9813 
9814   // Parse the offset
9815   if (Parser.getTok().isNot(AsmToken::Hash) &&
9816       Parser.getTok().isNot(AsmToken::Dollar))
9817     return Error(Parser.getTok().getLoc(), "'#' expected");
9818   Parser.Lex(); // skip hash token.
9819 
9820   const MCExpr *OffsetExpr;
9821   SMLoc ExLoc = Parser.getTok().getLoc();
9822   SMLoc EndLoc;
9823   if (getParser().parseExpression(OffsetExpr, EndLoc))
9824     return Error(ExLoc, "malformed pad offset");
9825   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9826   if (!CE)
9827     return Error(ExLoc, "pad offset must be an immediate");
9828 
9829   if (parseToken(AsmToken::EndOfStatement,
9830                  "unexpected token in '.pad' directive"))
9831     return true;
9832 
9833   getTargetStreamer().emitPad(CE->getValue());
9834   return false;
9835 }
9836 
9837 /// parseDirectiveRegSave
9838 ///  ::= .save  { registers }
9839 ///  ::= .vsave { registers }
9840 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
9841   // Check the ordering of unwind directives
9842   if (!UC.hasFnStart())
9843     return Error(L, ".fnstart must precede .save or .vsave directives");
9844   if (UC.hasHandlerData())
9845     return Error(L, ".save or .vsave must precede .handlerdata directive");
9846 
9847   // RAII object to make sure parsed operands are deleted.
9848   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
9849 
9850   // Parse the register list
9851   if (parseRegisterList(Operands) ||
9852       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9853     return true;
9854   ARMOperand &Op = (ARMOperand &)*Operands[0];
9855   if (!IsVector && !Op.isRegList())
9856     return Error(L, ".save expects GPR registers");
9857   if (IsVector && !Op.isDPRRegList())
9858     return Error(L, ".vsave expects DPR registers");
9859 
9860   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
9861   return false;
9862 }
9863 
9864 /// parseDirectiveInst
9865 ///  ::= .inst opcode [, ...]
9866 ///  ::= .inst.n opcode [, ...]
9867 ///  ::= .inst.w opcode [, ...]
9868 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
9869   int Width = 4;
9870 
9871   if (isThumb()) {
9872     switch (Suffix) {
9873     case 'n':
9874       Width = 2;
9875       break;
9876     case 'w':
9877       break;
9878     default:
9879       return Error(Loc, "cannot determine Thumb instruction size, "
9880                         "use inst.n/inst.w instead");
9881     }
9882   } else {
9883     if (Suffix)
9884       return Error(Loc, "width suffixes are invalid in ARM mode");
9885   }
9886 
9887   auto parseOne = [&]() -> bool {
9888     const MCExpr *Expr;
9889     if (getParser().parseExpression(Expr))
9890       return true;
9891     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
9892     if (!Value) {
9893       return Error(Loc, "expected constant expression");
9894     }
9895 
9896     switch (Width) {
9897     case 2:
9898       if (Value->getValue() > 0xffff)
9899         return Error(Loc, "inst.n operand is too big, use inst.w instead");
9900       break;
9901     case 4:
9902       if (Value->getValue() > 0xffffffff)
9903         return Error(Loc, StringRef(Suffix ? "inst.w" : "inst") +
9904                               " operand is too big");
9905       break;
9906     default:
9907       llvm_unreachable("only supported widths are 2 and 4");
9908     }
9909 
9910     getTargetStreamer().emitInst(Value->getValue(), Suffix);
9911     return false;
9912   };
9913 
9914   if (parseOptionalToken(AsmToken::EndOfStatement))
9915     return Error(Loc, "expected expression following directive");
9916   if (parseMany(parseOne))
9917     return true;
9918   return false;
9919 }
9920 
9921 /// parseDirectiveLtorg
9922 ///  ::= .ltorg | .pool
9923 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
9924   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9925     return true;
9926   getTargetStreamer().emitCurrentConstantPool();
9927   return false;
9928 }
9929 
9930 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
9931   const MCSection *Section = getStreamer().getCurrentSectionOnly();
9932 
9933   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9934     return true;
9935 
9936   if (!Section) {
9937     getStreamer().InitSections(false);
9938     Section = getStreamer().getCurrentSectionOnly();
9939   }
9940 
9941   assert(Section && "must have section to emit alignment");
9942   if (Section->UseCodeAlign())
9943     getStreamer().EmitCodeAlignment(2);
9944   else
9945     getStreamer().EmitValueToAlignment(2);
9946 
9947   return false;
9948 }
9949 
9950 /// parseDirectivePersonalityIndex
9951 ///   ::= .personalityindex index
9952 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
9953   MCAsmParser &Parser = getParser();
9954   bool HasExistingPersonality = UC.hasPersonality();
9955 
9956   const MCExpr *IndexExpression;
9957   SMLoc IndexLoc = Parser.getTok().getLoc();
9958   if (Parser.parseExpression(IndexExpression) ||
9959       parseToken(AsmToken::EndOfStatement,
9960                  "unexpected token in '.personalityindex' directive")) {
9961     return true;
9962   }
9963 
9964   UC.recordPersonalityIndex(L);
9965 
9966   if (!UC.hasFnStart()) {
9967     return Error(L, ".fnstart must precede .personalityindex directive");
9968   }
9969   if (UC.cantUnwind()) {
9970     Error(L, ".personalityindex cannot be used with .cantunwind");
9971     UC.emitCantUnwindLocNotes();
9972     return true;
9973   }
9974   if (UC.hasHandlerData()) {
9975     Error(L, ".personalityindex must precede .handlerdata directive");
9976     UC.emitHandlerDataLocNotes();
9977     return true;
9978   }
9979   if (HasExistingPersonality) {
9980     Error(L, "multiple personality directives");
9981     UC.emitPersonalityLocNotes();
9982     return true;
9983   }
9984 
9985   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
9986   if (!CE)
9987     return Error(IndexLoc, "index must be a constant number");
9988   if (CE->getValue() < 0 || CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX)
9989     return Error(IndexLoc,
9990                  "personality routine index should be in range [0-3]");
9991 
9992   getTargetStreamer().emitPersonalityIndex(CE->getValue());
9993   return false;
9994 }
9995 
9996 /// parseDirectiveUnwindRaw
9997 ///   ::= .unwind_raw offset, opcode [, opcode...]
9998 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
9999   MCAsmParser &Parser = getParser();
10000   int64_t StackOffset;
10001   const MCExpr *OffsetExpr;
10002   SMLoc OffsetLoc = getLexer().getLoc();
10003 
10004   if (!UC.hasFnStart())
10005     return Error(L, ".fnstart must precede .unwind_raw directives");
10006   if (getParser().parseExpression(OffsetExpr))
10007     return Error(OffsetLoc, "expected expression");
10008 
10009   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10010   if (!CE)
10011     return Error(OffsetLoc, "offset must be a constant");
10012 
10013   StackOffset = CE->getValue();
10014 
10015   if (Parser.parseToken(AsmToken::Comma, "expected comma"))
10016     return true;
10017 
10018   SmallVector<uint8_t, 16> Opcodes;
10019 
10020   auto parseOne = [&]() -> bool {
10021     const MCExpr *OE;
10022     SMLoc OpcodeLoc = getLexer().getLoc();
10023     if (check(getLexer().is(AsmToken::EndOfStatement) ||
10024                   Parser.parseExpression(OE),
10025               OpcodeLoc, "expected opcode expression"))
10026       return true;
10027     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
10028     if (!OC)
10029       return Error(OpcodeLoc, "opcode value must be a constant");
10030     const int64_t Opcode = OC->getValue();
10031     if (Opcode & ~0xff)
10032       return Error(OpcodeLoc, "invalid opcode");
10033     Opcodes.push_back(uint8_t(Opcode));
10034     return false;
10035   };
10036 
10037   // Must have at least 1 element
10038   SMLoc OpcodeLoc = getLexer().getLoc();
10039   if (parseOptionalToken(AsmToken::EndOfStatement))
10040     return Error(OpcodeLoc, "expected opcode expression");
10041   if (parseMany(parseOne))
10042     return true;
10043 
10044   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
10045   return false;
10046 }
10047 
10048 /// parseDirectiveTLSDescSeq
10049 ///   ::= .tlsdescseq tls-variable
10050 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
10051   MCAsmParser &Parser = getParser();
10052 
10053   if (getLexer().isNot(AsmToken::Identifier))
10054     return TokError("expected variable after '.tlsdescseq' directive");
10055 
10056   const MCSymbolRefExpr *SRE =
10057     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
10058                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
10059   Lex();
10060 
10061   if (parseToken(AsmToken::EndOfStatement,
10062                  "unexpected token in '.tlsdescseq' directive"))
10063     return true;
10064 
10065   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
10066   return false;
10067 }
10068 
10069 /// parseDirectiveMovSP
10070 ///  ::= .movsp reg [, #offset]
10071 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
10072   MCAsmParser &Parser = getParser();
10073   if (!UC.hasFnStart())
10074     return Error(L, ".fnstart must precede .movsp directives");
10075   if (UC.getFPReg() != ARM::SP)
10076     return Error(L, "unexpected .movsp directive");
10077 
10078   SMLoc SPRegLoc = Parser.getTok().getLoc();
10079   int SPReg = tryParseRegister();
10080   if (SPReg == -1)
10081     return Error(SPRegLoc, "register expected");
10082   if (SPReg == ARM::SP || SPReg == ARM::PC)
10083     return Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
10084 
10085   int64_t Offset = 0;
10086   if (Parser.parseOptionalToken(AsmToken::Comma)) {
10087     if (Parser.parseToken(AsmToken::Hash, "expected #constant"))
10088       return true;
10089 
10090     const MCExpr *OffsetExpr;
10091     SMLoc OffsetLoc = Parser.getTok().getLoc();
10092 
10093     if (Parser.parseExpression(OffsetExpr))
10094       return Error(OffsetLoc, "malformed offset expression");
10095 
10096     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10097     if (!CE)
10098       return Error(OffsetLoc, "offset must be an immediate constant");
10099 
10100     Offset = CE->getValue();
10101   }
10102 
10103   if (parseToken(AsmToken::EndOfStatement,
10104                  "unexpected token in '.movsp' directive"))
10105     return true;
10106 
10107   getTargetStreamer().emitMovSP(SPReg, Offset);
10108   UC.saveFPReg(SPReg);
10109 
10110   return false;
10111 }
10112 
10113 /// parseDirectiveObjectArch
10114 ///   ::= .object_arch name
10115 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
10116   MCAsmParser &Parser = getParser();
10117   if (getLexer().isNot(AsmToken::Identifier))
10118     return Error(getLexer().getLoc(), "unexpected token");
10119 
10120   StringRef Arch = Parser.getTok().getString();
10121   SMLoc ArchLoc = Parser.getTok().getLoc();
10122   Lex();
10123 
10124   unsigned ID = ARM::parseArch(Arch);
10125 
10126   if (ID == ARM::AK_INVALID)
10127     return Error(ArchLoc, "unknown architecture '" + Arch + "'");
10128   if (parseToken(AsmToken::EndOfStatement))
10129     return true;
10130 
10131   getTargetStreamer().emitObjectArch(ID);
10132   return false;
10133 }
10134 
10135 /// parseDirectiveAlign
10136 ///   ::= .align
10137 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
10138   // NOTE: if this is not the end of the statement, fall back to the target
10139   // agnostic handling for this directive which will correctly handle this.
10140   if (parseOptionalToken(AsmToken::EndOfStatement)) {
10141     // '.align' is target specifically handled to mean 2**2 byte alignment.
10142     const MCSection *Section = getStreamer().getCurrentSectionOnly();
10143     assert(Section && "must have section to emit alignment");
10144     if (Section->UseCodeAlign())
10145       getStreamer().EmitCodeAlignment(4, 0);
10146     else
10147       getStreamer().EmitValueToAlignment(4, 0, 1, 0);
10148     return false;
10149   }
10150   return true;
10151 }
10152 
10153 /// parseDirectiveThumbSet
10154 ///  ::= .thumb_set name, value
10155 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
10156   MCAsmParser &Parser = getParser();
10157 
10158   StringRef Name;
10159   if (check(Parser.parseIdentifier(Name),
10160             "expected identifier after '.thumb_set'") ||
10161       parseToken(AsmToken::Comma, "expected comma after name '" + Name + "'"))
10162     return true;
10163 
10164   MCSymbol *Sym;
10165   const MCExpr *Value;
10166   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
10167                                                Parser, Sym, Value))
10168     return true;
10169 
10170   getTargetStreamer().emitThumbSet(Sym, Value);
10171   return false;
10172 }
10173 
10174 /// Force static initialization.
10175 extern "C" void LLVMInitializeARMAsmParser() {
10176   RegisterMCAsmParser<ARMAsmParser> X(getTheARMLETarget());
10177   RegisterMCAsmParser<ARMAsmParser> Y(getTheARMBETarget());
10178   RegisterMCAsmParser<ARMAsmParser> A(getTheThumbLETarget());
10179   RegisterMCAsmParser<ARMAsmParser> B(getTheThumbBETarget());
10180 }
10181 
10182 #define GET_REGISTER_MATCHER
10183 #define GET_SUBTARGET_FEATURE_NAME
10184 #define GET_MATCHER_IMPLEMENTATION
10185 #include "ARMGenAsmMatcher.inc"
10186 
10187 // FIXME: This structure should be moved inside ARMTargetParser
10188 // when we start to table-generate them, and we can use the ARM
10189 // flags below, that were generated by table-gen.
10190 static const struct {
10191   const unsigned Kind;
10192   const uint64_t ArchCheck;
10193   const FeatureBitset Features;
10194 } Extensions[] = {
10195   { ARM::AEK_CRC, Feature_HasV8, {ARM::FeatureCRC} },
10196   { ARM::AEK_CRYPTO,  Feature_HasV8,
10197     {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10198   { ARM::AEK_FP, Feature_HasV8, {ARM::FeatureFPARMv8} },
10199   { (ARM::AEK_HWDIV | ARM::AEK_HWDIVARM), Feature_HasV7 | Feature_IsNotMClass,
10200     {ARM::FeatureHWDiv, ARM::FeatureHWDivARM} },
10201   { ARM::AEK_MP, Feature_HasV7 | Feature_IsNotMClass, {ARM::FeatureMP} },
10202   { ARM::AEK_SIMD, Feature_HasV8, {ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10203   { ARM::AEK_SEC, Feature_HasV6K, {ARM::FeatureTrustZone} },
10204   // FIXME: Only available in A-class, isel not predicated
10205   { ARM::AEK_VIRT, Feature_HasV7, {ARM::FeatureVirtualization} },
10206   { ARM::AEK_FP16, Feature_HasV8_2a, {ARM::FeatureFPARMv8, ARM::FeatureFullFP16} },
10207   { ARM::AEK_RAS, Feature_HasV8, {ARM::FeatureRAS} },
10208   // FIXME: Unsupported extensions.
10209   { ARM::AEK_OS, Feature_None, {} },
10210   { ARM::AEK_IWMMXT, Feature_None, {} },
10211   { ARM::AEK_IWMMXT2, Feature_None, {} },
10212   { ARM::AEK_MAVERICK, Feature_None, {} },
10213   { ARM::AEK_XSCALE, Feature_None, {} },
10214 };
10215 
10216 /// parseDirectiveArchExtension
10217 ///   ::= .arch_extension [no]feature
10218 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
10219   MCAsmParser &Parser = getParser();
10220 
10221   if (getLexer().isNot(AsmToken::Identifier))
10222     return Error(getLexer().getLoc(), "expected architecture extension name");
10223 
10224   StringRef Name = Parser.getTok().getString();
10225   SMLoc ExtLoc = Parser.getTok().getLoc();
10226   Lex();
10227 
10228   if (parseToken(AsmToken::EndOfStatement,
10229                  "unexpected token in '.arch_extension' directive"))
10230     return true;
10231 
10232   bool EnableFeature = true;
10233   if (Name.startswith_lower("no")) {
10234     EnableFeature = false;
10235     Name = Name.substr(2);
10236   }
10237   unsigned FeatureKind = ARM::parseArchExt(Name);
10238   if (FeatureKind == ARM::AEK_INVALID)
10239     return Error(ExtLoc, "unknown architectural extension: " + Name);
10240 
10241   for (const auto &Extension : Extensions) {
10242     if (Extension.Kind != FeatureKind)
10243       continue;
10244 
10245     if (Extension.Features.none())
10246       return Error(ExtLoc, "unsupported architectural extension: " + Name);
10247 
10248     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck)
10249       return Error(ExtLoc, "architectural extension '" + Name +
10250                                "' is not "
10251                                "allowed for the current base architecture");
10252 
10253     MCSubtargetInfo &STI = copySTI();
10254     FeatureBitset ToggleFeatures = EnableFeature
10255       ? (~STI.getFeatureBits() & Extension.Features)
10256       : ( STI.getFeatureBits() & Extension.Features);
10257 
10258     uint64_t Features =
10259         ComputeAvailableFeatures(STI.ToggleFeature(ToggleFeatures));
10260     setAvailableFeatures(Features);
10261     return false;
10262   }
10263 
10264   return Error(ExtLoc, "unknown architectural extension: " + Name);
10265 }
10266 
10267 // Define this matcher function after the auto-generated include so we
10268 // have the match class enum definitions.
10269 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
10270                                                   unsigned Kind) {
10271   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
10272   // If the kind is a token for a literal immediate, check if our asm
10273   // operand matches. This is for InstAliases which have a fixed-value
10274   // immediate in the syntax.
10275   switch (Kind) {
10276   default: break;
10277   case MCK__35_0:
10278     if (Op.isImm())
10279       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
10280         if (CE->getValue() == 0)
10281           return Match_Success;
10282     break;
10283   case MCK_ModImm:
10284     if (Op.isImm()) {
10285       const MCExpr *SOExpr = Op.getImm();
10286       int64_t Value;
10287       if (!SOExpr->evaluateAsAbsolute(Value))
10288         return Match_Success;
10289       assert((Value >= INT32_MIN && Value <= UINT32_MAX) &&
10290              "expression value must be representable in 32 bits");
10291     }
10292     break;
10293   case MCK_rGPR:
10294     if (hasV8Ops() && Op.isReg() && Op.getReg() == ARM::SP)
10295       return Match_Success;
10296     break;
10297   case MCK_GPRPair:
10298     if (Op.isReg() &&
10299         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
10300       return Match_Success;
10301     break;
10302   }
10303   return Match_InvalidOperand;
10304 }
10305