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 "InstPrinter/ARMInstPrinter.h"
12 #include "Utils/ARMBaseInfo.h"
13 #include "MCTargetDesc/ARMAddressingModes.h"
14 #include "MCTargetDesc/ARMBaseInfo.h"
15 #include "MCTargetDesc/ARMMCExpr.h"
16 #include "MCTargetDesc/ARMMCTargetDesc.h"
17 #include "llvm/ADT/APFloat.h"
18 #include "llvm/ADT/APInt.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/ADT/Twine.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCExpr.h"
30 #include "llvm/MC/MCInst.h"
31 #include "llvm/MC/MCInstrDesc.h"
32 #include "llvm/MC/MCInstrInfo.h"
33 #include "llvm/MC/MCObjectFileInfo.h"
34 #include "llvm/MC/MCParser/MCAsmLexer.h"
35 #include "llvm/MC/MCParser/MCAsmParser.h"
36 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
37 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
38 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
39 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
40 #include "llvm/MC/MCRegisterInfo.h"
41 #include "llvm/MC/MCSection.h"
42 #include "llvm/MC/MCStreamer.h"
43 #include "llvm/MC/MCSubtargetInfo.h"
44 #include "llvm/MC/MCSymbol.h"
45 #include "llvm/MC/SubtargetFeature.h"
46 #include "llvm/Support/ARMBuildAttributes.h"
47 #include "llvm/Support/ARMEHABI.h"
48 #include "llvm/Support/Casting.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/SMLoc.h"
54 #include "llvm/Support/TargetParser.h"
55 #include "llvm/Support/TargetRegistry.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include <algorithm>
58 #include <cassert>
59 #include <cstddef>
60 #include <cstdint>
61 #include <iterator>
62 #include <limits>
63 #include <memory>
64 #include <string>
65 #include <utility>
66 #include <vector>
67 
68 #define DEBUG_TYPE "asm-parser"
69 
70 using namespace llvm;
71 
72 namespace {
73 
74 enum class ImplicitItModeTy { Always, Never, ARMOnly, ThumbOnly };
75 
76 static cl::opt<ImplicitItModeTy> ImplicitItMode(
77     "arm-implicit-it", cl::init(ImplicitItModeTy::ARMOnly),
78     cl::desc("Allow conditional instructions outdside of an IT block"),
79     cl::values(clEnumValN(ImplicitItModeTy::Always, "always",
80                           "Accept in both ISAs, emit implicit ITs in Thumb"),
81                clEnumValN(ImplicitItModeTy::Never, "never",
82                           "Warn in ARM, reject in Thumb"),
83                clEnumValN(ImplicitItModeTy::ARMOnly, "arm",
84                           "Accept in ARM, reject in Thumb"),
85                clEnumValN(ImplicitItModeTy::ThumbOnly, "thumb",
86                           "Warn in ARM, emit implicit ITs in Thumb")));
87 
88 static cl::opt<bool> AddBuildAttributes("arm-add-build-attributes",
89                                         cl::init(false));
90 
91 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
92 
93 class UnwindContext {
94   using Locs = SmallVector<SMLoc, 4>;
95 
96   MCAsmParser &Parser;
97   Locs FnStartLocs;
98   Locs CantUnwindLocs;
99   Locs PersonalityLocs;
100   Locs PersonalityIndexLocs;
101   Locs HandlerDataLocs;
102   int FPReg;
103 
104 public:
UnwindContext(MCAsmParser & P)105   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
106 
hasFnStart() const107   bool hasFnStart() const { return !FnStartLocs.empty(); }
cantUnwind() const108   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
hasHandlerData() const109   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
110 
hasPersonality() const111   bool hasPersonality() const {
112     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
113   }
114 
recordFnStart(SMLoc L)115   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
recordCantUnwind(SMLoc L)116   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
recordPersonality(SMLoc L)117   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
recordHandlerData(SMLoc L)118   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
recordPersonalityIndex(SMLoc L)119   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
120 
saveFPReg(int Reg)121   void saveFPReg(int Reg) { FPReg = Reg; }
getFPReg() const122   int getFPReg() const { return FPReg; }
123 
emitFnStartLocNotes() const124   void emitFnStartLocNotes() const {
125     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
126          FI != FE; ++FI)
127       Parser.Note(*FI, ".fnstart was specified here");
128   }
129 
emitCantUnwindLocNotes() const130   void emitCantUnwindLocNotes() const {
131     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
132                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
133       Parser.Note(*UI, ".cantunwind was specified here");
134   }
135 
emitHandlerDataLocNotes() const136   void emitHandlerDataLocNotes() const {
137     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
138                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
139       Parser.Note(*HI, ".handlerdata was specified here");
140   }
141 
emitPersonalityLocNotes() const142   void emitPersonalityLocNotes() const {
143     for (Locs::const_iterator PI = PersonalityLocs.begin(),
144                               PE = PersonalityLocs.end(),
145                               PII = PersonalityIndexLocs.begin(),
146                               PIE = PersonalityIndexLocs.end();
147          PI != PE || PII != PIE;) {
148       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
149         Parser.Note(*PI++, ".personality was specified here");
150       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
151         Parser.Note(*PII++, ".personalityindex was specified here");
152       else
153         llvm_unreachable(".personality and .personalityindex cannot be "
154                          "at the same location");
155     }
156   }
157 
reset()158   void reset() {
159     FnStartLocs = Locs();
160     CantUnwindLocs = Locs();
161     PersonalityLocs = Locs();
162     HandlerDataLocs = Locs();
163     PersonalityIndexLocs = Locs();
164     FPReg = ARM::SP;
165   }
166 };
167 
168 class ARMAsmParser : public MCTargetAsmParser {
169   const MCRegisterInfo *MRI;
170   UnwindContext UC;
171 
getTargetStreamer()172   ARMTargetStreamer &getTargetStreamer() {
173     assert(getParser().getStreamer().getTargetStreamer() &&
174            "do not have a target streamer");
175     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
176     return static_cast<ARMTargetStreamer &>(TS);
177   }
178 
179   // Map of register aliases registers via the .req directive.
180   StringMap<unsigned> RegisterReqs;
181 
182   bool NextSymbolIsThumb;
183 
useImplicitITThumb() const184   bool useImplicitITThumb() const {
185     return ImplicitItMode == ImplicitItModeTy::Always ||
186            ImplicitItMode == ImplicitItModeTy::ThumbOnly;
187   }
188 
useImplicitITARM() const189   bool useImplicitITARM() const {
190     return ImplicitItMode == ImplicitItModeTy::Always ||
191            ImplicitItMode == ImplicitItModeTy::ARMOnly;
192   }
193 
194   struct {
195     ARMCC::CondCodes Cond;    // Condition for IT block.
196     unsigned Mask:4;          // Condition mask for instructions.
197                               // Starting at first 1 (from lsb).
198                               //   '1'  condition as indicated in IT.
199                               //   '0'  inverse of condition (else).
200                               // Count of instructions in IT block is
201                               // 4 - trailingzeroes(mask)
202                               // Note that this does not have the same encoding
203                               // as in the IT instruction, which also depends
204                               // on the low bit of the condition code.
205 
206     unsigned CurPosition;     // Current position in parsing of IT
207                               // block. In range [0,4], with 0 being the IT
208                               // instruction itself. Initialized according to
209                               // count of instructions in block.  ~0U if no
210                               // active IT block.
211 
212     bool IsExplicit;          // true  - The IT instruction was present in the
213                               //         input, we should not modify it.
214                               // false - The IT instruction was added
215                               //         implicitly, we can extend it if that
216                               //         would be legal.
217   } ITState;
218 
219   SmallVector<MCInst, 4> PendingConditionalInsts;
220 
flushPendingInstructions(MCStreamer & Out)221   void flushPendingInstructions(MCStreamer &Out) override {
222     if (!inImplicitITBlock()) {
223       assert(PendingConditionalInsts.size() == 0);
224       return;
225     }
226 
227     // Emit the IT instruction
228     unsigned Mask = getITMaskEncoding();
229     MCInst ITInst;
230     ITInst.setOpcode(ARM::t2IT);
231     ITInst.addOperand(MCOperand::createImm(ITState.Cond));
232     ITInst.addOperand(MCOperand::createImm(Mask));
233     Out.EmitInstruction(ITInst, getSTI());
234 
235     // Emit the conditonal instructions
236     assert(PendingConditionalInsts.size() <= 4);
237     for (const MCInst &Inst : PendingConditionalInsts) {
238       Out.EmitInstruction(Inst, getSTI());
239     }
240     PendingConditionalInsts.clear();
241 
242     // Clear the IT state
243     ITState.Mask = 0;
244     ITState.CurPosition = ~0U;
245   }
246 
inITBlock()247   bool inITBlock() { return ITState.CurPosition != ~0U; }
inExplicitITBlock()248   bool inExplicitITBlock() { return inITBlock() && ITState.IsExplicit; }
inImplicitITBlock()249   bool inImplicitITBlock() { return inITBlock() && !ITState.IsExplicit; }
250 
lastInITBlock()251   bool lastInITBlock() {
252     return ITState.CurPosition == 4 - countTrailingZeros(ITState.Mask);
253   }
254 
forwardITPosition()255   void forwardITPosition() {
256     if (!inITBlock()) return;
257     // Move to the next instruction in the IT block, if there is one. If not,
258     // mark the block as done, except for implicit IT blocks, which we leave
259     // open until we find an instruction that can't be added to it.
260     unsigned TZ = countTrailingZeros(ITState.Mask);
261     if (++ITState.CurPosition == 5 - TZ && ITState.IsExplicit)
262       ITState.CurPosition = ~0U; // Done with the IT block after this.
263   }
264 
265   // Rewind the state of the current IT block, removing the last slot from it.
rewindImplicitITPosition()266   void rewindImplicitITPosition() {
267     assert(inImplicitITBlock());
268     assert(ITState.CurPosition > 1);
269     ITState.CurPosition--;
270     unsigned TZ = countTrailingZeros(ITState.Mask);
271     unsigned NewMask = 0;
272     NewMask |= ITState.Mask & (0xC << TZ);
273     NewMask |= 0x2 << TZ;
274     ITState.Mask = NewMask;
275   }
276 
277   // Rewind the state of the current IT block, removing the last slot from it.
278   // If we were at the first slot, this closes the IT block.
discardImplicitITBlock()279   void discardImplicitITBlock() {
280     assert(inImplicitITBlock());
281     assert(ITState.CurPosition == 1);
282     ITState.CurPosition = ~0U;
283   }
284 
285   // Return the low-subreg of a given Q register.
getDRegFromQReg(unsigned QReg) const286   unsigned getDRegFromQReg(unsigned QReg) const {
287     return MRI->getSubReg(QReg, ARM::dsub_0);
288   }
289 
290   // Get the encoding of the IT mask, as it will appear in an IT instruction.
getITMaskEncoding()291   unsigned getITMaskEncoding() {
292     assert(inITBlock());
293     unsigned Mask = ITState.Mask;
294     unsigned TZ = countTrailingZeros(Mask);
295     if ((ITState.Cond & 1) == 0) {
296       assert(Mask && TZ <= 3 && "illegal IT mask value!");
297       Mask ^= (0xE << TZ) & 0xF;
298     }
299     return Mask;
300   }
301 
302   // Get the condition code corresponding to the current IT block slot.
currentITCond()303   ARMCC::CondCodes currentITCond() {
304     unsigned MaskBit;
305     if (ITState.CurPosition == 1)
306       MaskBit = 1;
307     else
308       MaskBit = (ITState.Mask >> (5 - ITState.CurPosition)) & 1;
309 
310     return MaskBit ? ITState.Cond : ARMCC::getOppositeCondition(ITState.Cond);
311   }
312 
313   // Invert the condition of the current IT block slot without changing any
314   // other slots in the same block.
invertCurrentITCondition()315   void invertCurrentITCondition() {
316     if (ITState.CurPosition == 1) {
317       ITState.Cond = ARMCC::getOppositeCondition(ITState.Cond);
318     } else {
319       ITState.Mask ^= 1 << (5 - ITState.CurPosition);
320     }
321   }
322 
323   // Returns true if the current IT block is full (all 4 slots used).
isITBlockFull()324   bool isITBlockFull() {
325     return inITBlock() && (ITState.Mask & 1);
326   }
327 
328   // Extend the current implicit IT block to have one more slot with the given
329   // condition code.
extendImplicitITBlock(ARMCC::CondCodes Cond)330   void extendImplicitITBlock(ARMCC::CondCodes Cond) {
331     assert(inImplicitITBlock());
332     assert(!isITBlockFull());
333     assert(Cond == ITState.Cond ||
334            Cond == ARMCC::getOppositeCondition(ITState.Cond));
335     unsigned TZ = countTrailingZeros(ITState.Mask);
336     unsigned NewMask = 0;
337     // Keep any existing condition bits.
338     NewMask |= ITState.Mask & (0xE << TZ);
339     // Insert the new condition bit.
340     NewMask |= (Cond == ITState.Cond) << TZ;
341     // Move the trailing 1 down one bit.
342     NewMask |= 1 << (TZ - 1);
343     ITState.Mask = NewMask;
344   }
345 
346   // Create a new implicit IT block with a dummy condition code.
startImplicitITBlock()347   void startImplicitITBlock() {
348     assert(!inITBlock());
349     ITState.Cond = ARMCC::AL;
350     ITState.Mask = 8;
351     ITState.CurPosition = 1;
352     ITState.IsExplicit = false;
353   }
354 
355   // Create a new explicit IT block with the given condition and mask. The mask
356   // should be in the parsed format, with a 1 implying 't', regardless of the
357   // low bit of the condition.
startExplicitITBlock(ARMCC::CondCodes Cond,unsigned Mask)358   void startExplicitITBlock(ARMCC::CondCodes Cond, unsigned Mask) {
359     assert(!inITBlock());
360     ITState.Cond = Cond;
361     ITState.Mask = Mask;
362     ITState.CurPosition = 0;
363     ITState.IsExplicit = true;
364   }
365 
Note(SMLoc L,const Twine & Msg,SMRange Range=None)366   void Note(SMLoc L, const Twine &Msg, SMRange Range = None) {
367     return getParser().Note(L, Msg, Range);
368   }
369 
Warning(SMLoc L,const Twine & Msg,SMRange Range=None)370   bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) {
371     return getParser().Warning(L, Msg, Range);
372   }
373 
Error(SMLoc L,const Twine & Msg,SMRange Range=None)374   bool Error(SMLoc L, const Twine &Msg, SMRange Range = None) {
375     return getParser().Error(L, Msg, Range);
376   }
377 
378   bool validatetLDMRegList(const MCInst &Inst, const OperandVector &Operands,
379                            unsigned ListNo, bool IsARPop = false);
380   bool validatetSTMRegList(const MCInst &Inst, const OperandVector &Operands,
381                            unsigned ListNo);
382 
383   int tryParseRegister();
384   bool tryParseRegisterWithWriteBack(OperandVector &);
385   int tryParseShiftRegister(OperandVector &);
386   bool parseRegisterList(OperandVector &);
387   bool parseMemory(OperandVector &);
388   bool parseOperand(OperandVector &, StringRef Mnemonic);
389   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
390   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
391                               unsigned &ShiftAmount);
392   bool parseLiteralValues(unsigned Size, SMLoc L);
393   bool parseDirectiveThumb(SMLoc L);
394   bool parseDirectiveARM(SMLoc L);
395   bool parseDirectiveThumbFunc(SMLoc L);
396   bool parseDirectiveCode(SMLoc L);
397   bool parseDirectiveSyntax(SMLoc L);
398   bool parseDirectiveReq(StringRef Name, SMLoc L);
399   bool parseDirectiveUnreq(SMLoc L);
400   bool parseDirectiveArch(SMLoc L);
401   bool parseDirectiveEabiAttr(SMLoc L);
402   bool parseDirectiveCPU(SMLoc L);
403   bool parseDirectiveFPU(SMLoc L);
404   bool parseDirectiveFnStart(SMLoc L);
405   bool parseDirectiveFnEnd(SMLoc L);
406   bool parseDirectiveCantUnwind(SMLoc L);
407   bool parseDirectivePersonality(SMLoc L);
408   bool parseDirectiveHandlerData(SMLoc L);
409   bool parseDirectiveSetFP(SMLoc L);
410   bool parseDirectivePad(SMLoc L);
411   bool parseDirectiveRegSave(SMLoc L, bool IsVector);
412   bool parseDirectiveInst(SMLoc L, char Suffix = '\0');
413   bool parseDirectiveLtorg(SMLoc L);
414   bool parseDirectiveEven(SMLoc L);
415   bool parseDirectivePersonalityIndex(SMLoc L);
416   bool parseDirectiveUnwindRaw(SMLoc L);
417   bool parseDirectiveTLSDescSeq(SMLoc L);
418   bool parseDirectiveMovSP(SMLoc L);
419   bool parseDirectiveObjectArch(SMLoc L);
420   bool parseDirectiveArchExtension(SMLoc L);
421   bool parseDirectiveAlign(SMLoc L);
422   bool parseDirectiveThumbSet(SMLoc L);
423 
424   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
425                           bool &CarrySetting, unsigned &ProcessorIMod,
426                           StringRef &ITMask);
427   void getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
428                              bool &CanAcceptCarrySet,
429                              bool &CanAcceptPredicationCode);
430 
431   void tryConvertingToTwoOperandForm(StringRef Mnemonic, bool CarrySetting,
432                                      OperandVector &Operands);
isThumb() const433   bool isThumb() const {
434     // FIXME: Can tablegen auto-generate this?
435     return getSTI().getFeatureBits()[ARM::ModeThumb];
436   }
437 
isThumbOne() const438   bool isThumbOne() const {
439     return isThumb() && !getSTI().getFeatureBits()[ARM::FeatureThumb2];
440   }
441 
isThumbTwo() const442   bool isThumbTwo() const {
443     return isThumb() && getSTI().getFeatureBits()[ARM::FeatureThumb2];
444   }
445 
hasThumb() const446   bool hasThumb() const {
447     return getSTI().getFeatureBits()[ARM::HasV4TOps];
448   }
449 
hasThumb2() const450   bool hasThumb2() const {
451     return getSTI().getFeatureBits()[ARM::FeatureThumb2];
452   }
453 
hasV6Ops() const454   bool hasV6Ops() const {
455     return getSTI().getFeatureBits()[ARM::HasV6Ops];
456   }
457 
hasV6T2Ops() const458   bool hasV6T2Ops() const {
459     return getSTI().getFeatureBits()[ARM::HasV6T2Ops];
460   }
461 
hasV6MOps() const462   bool hasV6MOps() const {
463     return getSTI().getFeatureBits()[ARM::HasV6MOps];
464   }
465 
hasV7Ops() const466   bool hasV7Ops() const {
467     return getSTI().getFeatureBits()[ARM::HasV7Ops];
468   }
469 
hasV8Ops() const470   bool hasV8Ops() const {
471     return getSTI().getFeatureBits()[ARM::HasV8Ops];
472   }
473 
hasV8MBaseline() const474   bool hasV8MBaseline() const {
475     return getSTI().getFeatureBits()[ARM::HasV8MBaselineOps];
476   }
477 
hasV8MMainline() const478   bool hasV8MMainline() const {
479     return getSTI().getFeatureBits()[ARM::HasV8MMainlineOps];
480   }
481 
has8MSecExt() const482   bool has8MSecExt() const {
483     return getSTI().getFeatureBits()[ARM::Feature8MSecExt];
484   }
485 
hasARM() const486   bool hasARM() const {
487     return !getSTI().getFeatureBits()[ARM::FeatureNoARM];
488   }
489 
hasDSP() const490   bool hasDSP() const {
491     return getSTI().getFeatureBits()[ARM::FeatureDSP];
492   }
493 
hasD16() const494   bool hasD16() const {
495     return getSTI().getFeatureBits()[ARM::FeatureD16];
496   }
497 
hasV8_1aOps() const498   bool hasV8_1aOps() const {
499     return getSTI().getFeatureBits()[ARM::HasV8_1aOps];
500   }
501 
hasRAS() const502   bool hasRAS() const {
503     return getSTI().getFeatureBits()[ARM::FeatureRAS];
504   }
505 
SwitchMode()506   void SwitchMode() {
507     MCSubtargetInfo &STI = copySTI();
508     uint64_t FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
509     setAvailableFeatures(FB);
510   }
511 
512   void FixModeAfterArchChange(bool WasThumb, SMLoc Loc);
513 
isMClass() const514   bool isMClass() const {
515     return getSTI().getFeatureBits()[ARM::FeatureMClass];
516   }
517 
518   /// @name Auto-generated Match Functions
519   /// {
520 
521 #define GET_ASSEMBLER_HEADER
522 #include "ARMGenAsmMatcher.inc"
523 
524   /// }
525 
526   OperandMatchResultTy parseITCondCode(OperandVector &);
527   OperandMatchResultTy parseCoprocNumOperand(OperandVector &);
528   OperandMatchResultTy parseCoprocRegOperand(OperandVector &);
529   OperandMatchResultTy parseCoprocOptionOperand(OperandVector &);
530   OperandMatchResultTy parseMemBarrierOptOperand(OperandVector &);
531   OperandMatchResultTy parseTraceSyncBarrierOptOperand(OperandVector &);
532   OperandMatchResultTy parseInstSyncBarrierOptOperand(OperandVector &);
533   OperandMatchResultTy parseProcIFlagsOperand(OperandVector &);
534   OperandMatchResultTy parseMSRMaskOperand(OperandVector &);
535   OperandMatchResultTy parseBankedRegOperand(OperandVector &);
536   OperandMatchResultTy parsePKHImm(OperandVector &O, StringRef Op, int Low,
537                                    int High);
parsePKHLSLImm(OperandVector & O)538   OperandMatchResultTy parsePKHLSLImm(OperandVector &O) {
539     return parsePKHImm(O, "lsl", 0, 31);
540   }
parsePKHASRImm(OperandVector & O)541   OperandMatchResultTy parsePKHASRImm(OperandVector &O) {
542     return parsePKHImm(O, "asr", 1, 32);
543   }
544   OperandMatchResultTy parseSetEndImm(OperandVector &);
545   OperandMatchResultTy parseShifterImm(OperandVector &);
546   OperandMatchResultTy parseRotImm(OperandVector &);
547   OperandMatchResultTy parseModImm(OperandVector &);
548   OperandMatchResultTy parseBitfield(OperandVector &);
549   OperandMatchResultTy parsePostIdxReg(OperandVector &);
550   OperandMatchResultTy parseAM3Offset(OperandVector &);
551   OperandMatchResultTy parseFPImm(OperandVector &);
552   OperandMatchResultTy parseVectorList(OperandVector &);
553   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index,
554                                        SMLoc &EndLoc);
555 
556   // Asm Match Converter Methods
557   void cvtThumbMultiply(MCInst &Inst, const OperandVector &);
558   void cvtThumbBranches(MCInst &Inst, const OperandVector &);
559 
560   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
561   bool processInstruction(MCInst &Inst, const OperandVector &Ops, MCStreamer &Out);
562   bool shouldOmitCCOutOperand(StringRef Mnemonic, OperandVector &Operands);
563   bool shouldOmitPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
564   bool isITBlockTerminator(MCInst &Inst) const;
565   void fixupGNULDRDAlias(StringRef Mnemonic, OperandVector &Operands);
566   bool validateLDRDSTRD(MCInst &Inst, const OperandVector &Operands,
567                         bool Load, bool ARMMode, bool Writeback);
568 
569 public:
570   enum ARMMatchResultTy {
571     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
572     Match_RequiresNotITBlock,
573     Match_RequiresV6,
574     Match_RequiresThumb2,
575     Match_RequiresV8,
576     Match_RequiresFlagSetting,
577 #define GET_OPERAND_DIAGNOSTIC_TYPES
578 #include "ARMGenAsmMatcher.inc"
579 
580   };
581 
ARMAsmParser(const MCSubtargetInfo & STI,MCAsmParser & Parser,const MCInstrInfo & MII,const MCTargetOptions & Options)582   ARMAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
583                const MCInstrInfo &MII, const MCTargetOptions &Options)
584     : MCTargetAsmParser(Options, STI, MII), UC(Parser) {
585     MCAsmParserExtension::Initialize(Parser);
586 
587     // Cache the MCRegisterInfo.
588     MRI = getContext().getRegisterInfo();
589 
590     // Initialize the set of available features.
591     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
592 
593     // Add build attributes based on the selected target.
594     if (AddBuildAttributes)
595       getTargetStreamer().emitTargetAttributes(STI);
596 
597     // Not in an ITBlock to start with.
598     ITState.CurPosition = ~0U;
599 
600     NextSymbolIsThumb = false;
601   }
602 
603   // Implementation of the MCTargetAsmParser interface:
604   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
605   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
606                         SMLoc NameLoc, OperandVector &Operands) override;
607   bool ParseDirective(AsmToken DirectiveID) override;
608 
609   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
610                                       unsigned Kind) override;
611   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
612 
613   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
614                                OperandVector &Operands, MCStreamer &Out,
615                                uint64_t &ErrorInfo,
616                                bool MatchingInlineAsm) override;
617   unsigned MatchInstruction(OperandVector &Operands, MCInst &Inst,
618                             SmallVectorImpl<NearMissInfo> &NearMisses,
619                             bool MatchingInlineAsm, bool &EmitInITBlock,
620                             MCStreamer &Out);
621 
622   struct NearMissMessage {
623     SMLoc Loc;
624     SmallString<128> Message;
625   };
626 
627   const char *getCustomOperandDiag(ARMMatchResultTy MatchError);
628 
629   void FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
630                         SmallVectorImpl<NearMissMessage> &NearMissesOut,
631                         SMLoc IDLoc, OperandVector &Operands);
632   void ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses, SMLoc IDLoc,
633                         OperandVector &Operands);
634 
635   void doBeforeLabelEmit(MCSymbol *Symbol) override;
636 
637   void onLabelParsed(MCSymbol *Symbol) override;
638 };
639 
640 /// ARMOperand - Instances of this class represent a parsed ARM machine
641 /// operand.
642 class ARMOperand : public MCParsedAsmOperand {
643   enum KindTy {
644     k_CondCode,
645     k_CCOut,
646     k_ITCondMask,
647     k_CoprocNum,
648     k_CoprocReg,
649     k_CoprocOption,
650     k_Immediate,
651     k_MemBarrierOpt,
652     k_InstSyncBarrierOpt,
653     k_TraceSyncBarrierOpt,
654     k_Memory,
655     k_PostIndexRegister,
656     k_MSRMask,
657     k_BankedReg,
658     k_ProcIFlags,
659     k_VectorIndex,
660     k_Register,
661     k_RegisterList,
662     k_DPRRegisterList,
663     k_SPRRegisterList,
664     k_VectorList,
665     k_VectorListAllLanes,
666     k_VectorListIndexed,
667     k_ShiftedRegister,
668     k_ShiftedImmediate,
669     k_ShifterImmediate,
670     k_RotateImmediate,
671     k_ModifiedImmediate,
672     k_ConstantPoolImmediate,
673     k_BitfieldDescriptor,
674     k_Token,
675   } Kind;
676 
677   SMLoc StartLoc, EndLoc, AlignmentLoc;
678   SmallVector<unsigned, 8> Registers;
679 
680   struct CCOp {
681     ARMCC::CondCodes Val;
682   };
683 
684   struct CopOp {
685     unsigned Val;
686   };
687 
688   struct CoprocOptionOp {
689     unsigned Val;
690   };
691 
692   struct ITMaskOp {
693     unsigned Mask:4;
694   };
695 
696   struct MBOptOp {
697     ARM_MB::MemBOpt Val;
698   };
699 
700   struct ISBOptOp {
701     ARM_ISB::InstSyncBOpt Val;
702   };
703 
704   struct TSBOptOp {
705     ARM_TSB::TraceSyncBOpt Val;
706   };
707 
708   struct IFlagsOp {
709     ARM_PROC::IFlags Val;
710   };
711 
712   struct MMaskOp {
713     unsigned Val;
714   };
715 
716   struct BankedRegOp {
717     unsigned Val;
718   };
719 
720   struct TokOp {
721     const char *Data;
722     unsigned Length;
723   };
724 
725   struct RegOp {
726     unsigned RegNum;
727   };
728 
729   // A vector register list is a sequential list of 1 to 4 registers.
730   struct VectorListOp {
731     unsigned RegNum;
732     unsigned Count;
733     unsigned LaneIndex;
734     bool isDoubleSpaced;
735   };
736 
737   struct VectorIndexOp {
738     unsigned Val;
739   };
740 
741   struct ImmOp {
742     const MCExpr *Val;
743   };
744 
745   /// Combined record for all forms of ARM address expressions.
746   struct MemoryOp {
747     unsigned BaseRegNum;
748     // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
749     // was specified.
750     const MCConstantExpr *OffsetImm;  // Offset immediate value
751     unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
752     ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
753     unsigned ShiftImm;        // shift for OffsetReg.
754     unsigned Alignment;       // 0 = no alignment specified
755     // n = alignment in bytes (2, 4, 8, 16, or 32)
756     unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
757   };
758 
759   struct PostIdxRegOp {
760     unsigned RegNum;
761     bool isAdd;
762     ARM_AM::ShiftOpc ShiftTy;
763     unsigned ShiftImm;
764   };
765 
766   struct ShifterImmOp {
767     bool isASR;
768     unsigned Imm;
769   };
770 
771   struct RegShiftedRegOp {
772     ARM_AM::ShiftOpc ShiftTy;
773     unsigned SrcReg;
774     unsigned ShiftReg;
775     unsigned ShiftImm;
776   };
777 
778   struct RegShiftedImmOp {
779     ARM_AM::ShiftOpc ShiftTy;
780     unsigned SrcReg;
781     unsigned ShiftImm;
782   };
783 
784   struct RotImmOp {
785     unsigned Imm;
786   };
787 
788   struct ModImmOp {
789     unsigned Bits;
790     unsigned Rot;
791   };
792 
793   struct BitfieldOp {
794     unsigned LSB;
795     unsigned Width;
796   };
797 
798   union {
799     struct CCOp CC;
800     struct CopOp Cop;
801     struct CoprocOptionOp CoprocOption;
802     struct MBOptOp MBOpt;
803     struct ISBOptOp ISBOpt;
804     struct TSBOptOp TSBOpt;
805     struct ITMaskOp ITMask;
806     struct IFlagsOp IFlags;
807     struct MMaskOp MMask;
808     struct BankedRegOp BankedReg;
809     struct TokOp Tok;
810     struct RegOp Reg;
811     struct VectorListOp VectorList;
812     struct VectorIndexOp VectorIndex;
813     struct ImmOp Imm;
814     struct MemoryOp Memory;
815     struct PostIdxRegOp PostIdxReg;
816     struct ShifterImmOp ShifterImm;
817     struct RegShiftedRegOp RegShiftedReg;
818     struct RegShiftedImmOp RegShiftedImm;
819     struct RotImmOp RotImm;
820     struct ModImmOp ModImm;
821     struct BitfieldOp Bitfield;
822   };
823 
824 public:
ARMOperand(KindTy K)825   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
826 
827   /// getStartLoc - Get the location of the first token of this operand.
getStartLoc() const828   SMLoc getStartLoc() const override { return StartLoc; }
829 
830   /// getEndLoc - Get the location of the last token of this operand.
getEndLoc() const831   SMLoc getEndLoc() const override { return EndLoc; }
832 
833   /// getLocRange - Get the range between the first and last token of this
834   /// operand.
getLocRange() const835   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
836 
837   /// getAlignmentLoc - Get the location of the Alignment token of this operand.
getAlignmentLoc() const838   SMLoc getAlignmentLoc() const {
839     assert(Kind == k_Memory && "Invalid access!");
840     return AlignmentLoc;
841   }
842 
getCondCode() const843   ARMCC::CondCodes getCondCode() const {
844     assert(Kind == k_CondCode && "Invalid access!");
845     return CC.Val;
846   }
847 
getCoproc() const848   unsigned getCoproc() const {
849     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
850     return Cop.Val;
851   }
852 
getToken() const853   StringRef getToken() const {
854     assert(Kind == k_Token && "Invalid access!");
855     return StringRef(Tok.Data, Tok.Length);
856   }
857 
getReg() const858   unsigned getReg() const override {
859     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
860     return Reg.RegNum;
861   }
862 
getRegList() const863   const SmallVectorImpl<unsigned> &getRegList() const {
864     assert((Kind == k_RegisterList || Kind == k_DPRRegisterList ||
865             Kind == k_SPRRegisterList) && "Invalid access!");
866     return Registers;
867   }
868 
getImm() const869   const MCExpr *getImm() const {
870     assert(isImm() && "Invalid access!");
871     return Imm.Val;
872   }
873 
getConstantPoolImm() const874   const MCExpr *getConstantPoolImm() const {
875     assert(isConstantPoolImm() && "Invalid access!");
876     return Imm.Val;
877   }
878 
getVectorIndex() const879   unsigned getVectorIndex() const {
880     assert(Kind == k_VectorIndex && "Invalid access!");
881     return VectorIndex.Val;
882   }
883 
getMemBarrierOpt() const884   ARM_MB::MemBOpt getMemBarrierOpt() const {
885     assert(Kind == k_MemBarrierOpt && "Invalid access!");
886     return MBOpt.Val;
887   }
888 
getInstSyncBarrierOpt() const889   ARM_ISB::InstSyncBOpt getInstSyncBarrierOpt() const {
890     assert(Kind == k_InstSyncBarrierOpt && "Invalid access!");
891     return ISBOpt.Val;
892   }
893 
getTraceSyncBarrierOpt() const894   ARM_TSB::TraceSyncBOpt getTraceSyncBarrierOpt() const {
895     assert(Kind == k_TraceSyncBarrierOpt && "Invalid access!");
896     return TSBOpt.Val;
897   }
898 
getProcIFlags() const899   ARM_PROC::IFlags getProcIFlags() const {
900     assert(Kind == k_ProcIFlags && "Invalid access!");
901     return IFlags.Val;
902   }
903 
getMSRMask() const904   unsigned getMSRMask() const {
905     assert(Kind == k_MSRMask && "Invalid access!");
906     return MMask.Val;
907   }
908 
getBankedReg() const909   unsigned getBankedReg() const {
910     assert(Kind == k_BankedReg && "Invalid access!");
911     return BankedReg.Val;
912   }
913 
isCoprocNum() const914   bool isCoprocNum() const { return Kind == k_CoprocNum; }
isCoprocReg() const915   bool isCoprocReg() const { return Kind == k_CoprocReg; }
isCoprocOption() const916   bool isCoprocOption() const { return Kind == k_CoprocOption; }
isCondCode() const917   bool isCondCode() const { return Kind == k_CondCode; }
isCCOut() const918   bool isCCOut() const { return Kind == k_CCOut; }
isITMask() const919   bool isITMask() const { return Kind == k_ITCondMask; }
isITCondCode() const920   bool isITCondCode() const { return Kind == k_CondCode; }
isImm() const921   bool isImm() const override {
922     return Kind == k_Immediate;
923   }
924 
isARMBranchTarget() const925   bool isARMBranchTarget() const {
926     if (!isImm()) return false;
927 
928     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
929       return CE->getValue() % 4 == 0;
930     return true;
931   }
932 
933 
isThumbBranchTarget() const934   bool isThumbBranchTarget() const {
935     if (!isImm()) return false;
936 
937     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
938       return CE->getValue() % 2 == 0;
939     return true;
940   }
941 
942   // checks whether this operand is an unsigned offset which fits is a field
943   // of specified width and scaled by a specific number of bits
944   template<unsigned width, unsigned scale>
isUnsignedOffset() const945   bool isUnsignedOffset() const {
946     if (!isImm()) return false;
947     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
948     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
949       int64_t Val = CE->getValue();
950       int64_t Align = 1LL << scale;
951       int64_t Max = Align * ((1LL << width) - 1);
952       return ((Val % Align) == 0) && (Val >= 0) && (Val <= Max);
953     }
954     return false;
955   }
956 
957   // checks whether this operand is an signed offset which fits is a field
958   // of specified width and scaled by a specific number of bits
959   template<unsigned width, unsigned scale>
isSignedOffset() const960   bool isSignedOffset() const {
961     if (!isImm()) return false;
962     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
963     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
964       int64_t Val = CE->getValue();
965       int64_t Align = 1LL << scale;
966       int64_t Max = Align * ((1LL << (width-1)) - 1);
967       int64_t Min = -Align * (1LL << (width-1));
968       return ((Val % Align) == 0) && (Val >= Min) && (Val <= Max);
969     }
970     return false;
971   }
972 
973   // checks whether this operand is a memory operand computed as an offset
974   // applied to PC. the offset may have 8 bits of magnitude and is represented
975   // with two bits of shift. textually it may be either [pc, #imm], #imm or
976   // relocable expression...
isThumbMemPC() const977   bool isThumbMemPC() const {
978     int64_t Val = 0;
979     if (isImm()) {
980       if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
981       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
982       if (!CE) return false;
983       Val = CE->getValue();
984     }
985     else if (isMem()) {
986       if(!Memory.OffsetImm || Memory.OffsetRegNum) return false;
987       if(Memory.BaseRegNum != ARM::PC) return false;
988       Val = Memory.OffsetImm->getValue();
989     }
990     else return false;
991     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
992   }
993 
isFPImm() const994   bool isFPImm() const {
995     if (!isImm()) return false;
996     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
997     if (!CE) return false;
998     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
999     return Val != -1;
1000   }
1001 
1002   template<int64_t N, int64_t M>
isImmediate() const1003   bool isImmediate() const {
1004     if (!isImm()) return false;
1005     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1006     if (!CE) return false;
1007     int64_t Value = CE->getValue();
1008     return Value >= N && Value <= M;
1009   }
1010 
1011   template<int64_t N, int64_t M>
isImmediateS4() const1012   bool isImmediateS4() const {
1013     if (!isImm()) return false;
1014     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1015     if (!CE) return false;
1016     int64_t Value = CE->getValue();
1017     return ((Value & 3) == 0) && Value >= N && Value <= M;
1018   }
1019 
isFBits16() const1020   bool isFBits16() const {
1021     return isImmediate<0, 17>();
1022   }
isFBits32() const1023   bool isFBits32() const {
1024     return isImmediate<1, 33>();
1025   }
isImm8s4() const1026   bool isImm8s4() const {
1027     return isImmediateS4<-1020, 1020>();
1028   }
isImm0_1020s4() const1029   bool isImm0_1020s4() const {
1030     return isImmediateS4<0, 1020>();
1031   }
isImm0_508s4() const1032   bool isImm0_508s4() const {
1033     return isImmediateS4<0, 508>();
1034   }
isImm0_508s4Neg() const1035   bool isImm0_508s4Neg() 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     // explicitly exclude zero. we want that to use the normal 0_508 version.
1041     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
1042   }
1043 
isImm0_4095Neg() const1044   bool isImm0_4095Neg() const {
1045     if (!isImm()) return false;
1046     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1047     if (!CE) return false;
1048     // isImm0_4095Neg is used with 32-bit immediates only.
1049     // 32-bit immediates are zero extended to 64-bit when parsed,
1050     // thus simple -CE->getValue() results in a big negative number,
1051     // not a small positive number as intended
1052     if ((CE->getValue() >> 32) > 0) return false;
1053     uint32_t Value = -static_cast<uint32_t>(CE->getValue());
1054     return Value > 0 && Value < 4096;
1055   }
1056 
isImm0_7() const1057   bool isImm0_7() const {
1058     return isImmediate<0, 7>();
1059   }
1060 
isImm1_16() const1061   bool isImm1_16() const {
1062     return isImmediate<1, 16>();
1063   }
1064 
isImm1_32() const1065   bool isImm1_32() const {
1066     return isImmediate<1, 32>();
1067   }
1068 
isImm8_255() const1069   bool isImm8_255() const {
1070     return isImmediate<8, 255>();
1071   }
1072 
isImm256_65535Expr() const1073   bool isImm256_65535Expr() const {
1074     if (!isImm()) return false;
1075     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1076     // If it's not a constant expression, it'll generate a fixup and be
1077     // handled later.
1078     if (!CE) return true;
1079     int64_t Value = CE->getValue();
1080     return Value >= 256 && Value < 65536;
1081   }
1082 
isImm0_65535Expr() const1083   bool isImm0_65535Expr() const {
1084     if (!isImm()) return false;
1085     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1086     // If it's not a constant expression, it'll generate a fixup and be
1087     // handled later.
1088     if (!CE) return true;
1089     int64_t Value = CE->getValue();
1090     return Value >= 0 && Value < 65536;
1091   }
1092 
isImm24bit() const1093   bool isImm24bit() const {
1094     return isImmediate<0, 0xffffff + 1>();
1095   }
1096 
isImmThumbSR() const1097   bool isImmThumbSR() const {
1098     return isImmediate<1, 33>();
1099   }
1100 
isPKHLSLImm() const1101   bool isPKHLSLImm() const {
1102     return isImmediate<0, 32>();
1103   }
1104 
isPKHASRImm() const1105   bool isPKHASRImm() const {
1106     return isImmediate<0, 33>();
1107   }
1108 
isAdrLabel() const1109   bool isAdrLabel() const {
1110     // If we have an immediate that's not a constant, treat it as a label
1111     // reference needing a fixup.
1112     if (isImm() && !isa<MCConstantExpr>(getImm()))
1113       return true;
1114 
1115     // If it is a constant, it must fit into a modified immediate encoding.
1116     if (!isImm()) return false;
1117     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1118     if (!CE) return false;
1119     int64_t Value = CE->getValue();
1120     return (ARM_AM::getSOImmVal(Value) != -1 ||
1121             ARM_AM::getSOImmVal(-Value) != -1);
1122   }
1123 
isT2SOImm() const1124   bool isT2SOImm() const {
1125     // If we have an immediate that's not a constant, treat it as an expression
1126     // needing a fixup.
1127     if (isImm() && !isa<MCConstantExpr>(getImm())) {
1128       // We want to avoid matching :upper16: and :lower16: as we want these
1129       // expressions to match in isImm0_65535Expr()
1130       const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(getImm());
1131       return (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
1132                              ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16));
1133     }
1134     if (!isImm()) return false;
1135     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1136     if (!CE) return false;
1137     int64_t Value = CE->getValue();
1138     return ARM_AM::getT2SOImmVal(Value) != -1;
1139   }
1140 
isT2SOImmNot() const1141   bool isT2SOImmNot() const {
1142     if (!isImm()) return false;
1143     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1144     if (!CE) return false;
1145     int64_t Value = CE->getValue();
1146     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1147       ARM_AM::getT2SOImmVal(~Value) != -1;
1148   }
1149 
isT2SOImmNeg() const1150   bool isT2SOImmNeg() const {
1151     if (!isImm()) return false;
1152     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1153     if (!CE) return false;
1154     int64_t Value = CE->getValue();
1155     // Only use this when not representable as a plain so_imm.
1156     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1157       ARM_AM::getT2SOImmVal(-Value) != -1;
1158   }
1159 
isSetEndImm() const1160   bool isSetEndImm() const {
1161     if (!isImm()) return false;
1162     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1163     if (!CE) return false;
1164     int64_t Value = CE->getValue();
1165     return Value == 1 || Value == 0;
1166   }
1167 
isReg() const1168   bool isReg() const override { return Kind == k_Register; }
isRegList() const1169   bool isRegList() const { return Kind == k_RegisterList; }
isDPRRegList() const1170   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
isSPRRegList() const1171   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
isToken() const1172   bool isToken() const override { return Kind == k_Token; }
isMemBarrierOpt() const1173   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
isInstSyncBarrierOpt() const1174   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
isTraceSyncBarrierOpt() const1175   bool isTraceSyncBarrierOpt() const { return Kind == k_TraceSyncBarrierOpt; }
isMem() const1176   bool isMem() const override {
1177     if (Kind != k_Memory)
1178       return false;
1179     if (Memory.BaseRegNum &&
1180         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.BaseRegNum))
1181       return false;
1182     if (Memory.OffsetRegNum &&
1183         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.OffsetRegNum))
1184       return false;
1185     return true;
1186   }
isShifterImm() const1187   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
isRegShiftedReg() const1188   bool isRegShiftedReg() const {
1189     return Kind == k_ShiftedRegister &&
1190            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1191                RegShiftedReg.SrcReg) &&
1192            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1193                RegShiftedReg.ShiftReg);
1194   }
isRegShiftedImm() const1195   bool isRegShiftedImm() const {
1196     return Kind == k_ShiftedImmediate &&
1197            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1198                RegShiftedImm.SrcReg);
1199   }
isRotImm() const1200   bool isRotImm() const { return Kind == k_RotateImmediate; }
isModImm() const1201   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1202 
isModImmNot() const1203   bool isModImmNot() const {
1204     if (!isImm()) return false;
1205     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1206     if (!CE) return false;
1207     int64_t Value = CE->getValue();
1208     return ARM_AM::getSOImmVal(~Value) != -1;
1209   }
1210 
isModImmNeg() const1211   bool isModImmNeg() const {
1212     if (!isImm()) return false;
1213     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1214     if (!CE) return false;
1215     int64_t Value = CE->getValue();
1216     return ARM_AM::getSOImmVal(Value) == -1 &&
1217       ARM_AM::getSOImmVal(-Value) != -1;
1218   }
1219 
isThumbModImmNeg1_7() const1220   bool isThumbModImmNeg1_7() const {
1221     if (!isImm()) return false;
1222     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1223     if (!CE) return false;
1224     int32_t Value = -(int32_t)CE->getValue();
1225     return 0 < Value && Value < 8;
1226   }
1227 
isThumbModImmNeg8_255() const1228   bool isThumbModImmNeg8_255() const {
1229     if (!isImm()) return false;
1230     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1231     if (!CE) return false;
1232     int32_t Value = -(int32_t)CE->getValue();
1233     return 7 < Value && Value < 256;
1234   }
1235 
isConstantPoolImm() const1236   bool isConstantPoolImm() const { return Kind == k_ConstantPoolImmediate; }
isBitfield() const1237   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
isPostIdxRegShifted() const1238   bool isPostIdxRegShifted() const {
1239     return Kind == k_PostIndexRegister &&
1240            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(PostIdxReg.RegNum);
1241   }
isPostIdxReg() const1242   bool isPostIdxReg() const {
1243     return isPostIdxRegShifted() && PostIdxReg.ShiftTy == ARM_AM::no_shift;
1244   }
isMemNoOffset(bool alignOK=false,unsigned Alignment=0) const1245   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1246     if (!isMem())
1247       return false;
1248     // No offset of any kind.
1249     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1250      (alignOK || Memory.Alignment == Alignment);
1251   }
isMemPCRelImm12() const1252   bool isMemPCRelImm12() const {
1253     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1254       return false;
1255     // Base register must be PC.
1256     if (Memory.BaseRegNum != ARM::PC)
1257       return false;
1258     // Immediate offset in range [-4095, 4095].
1259     if (!Memory.OffsetImm) return true;
1260     int64_t Val = Memory.OffsetImm->getValue();
1261     return (Val > -4096 && Val < 4096) ||
1262            (Val == std::numeric_limits<int32_t>::min());
1263   }
1264 
isAlignedMemory() const1265   bool isAlignedMemory() const {
1266     return isMemNoOffset(true);
1267   }
1268 
isAlignedMemoryNone() const1269   bool isAlignedMemoryNone() const {
1270     return isMemNoOffset(false, 0);
1271   }
1272 
isDupAlignedMemoryNone() const1273   bool isDupAlignedMemoryNone() const {
1274     return isMemNoOffset(false, 0);
1275   }
1276 
isAlignedMemory16() const1277   bool isAlignedMemory16() const {
1278     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1279       return true;
1280     return isMemNoOffset(false, 0);
1281   }
1282 
isDupAlignedMemory16() const1283   bool isDupAlignedMemory16() const {
1284     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1285       return true;
1286     return isMemNoOffset(false, 0);
1287   }
1288 
isAlignedMemory32() const1289   bool isAlignedMemory32() const {
1290     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1291       return true;
1292     return isMemNoOffset(false, 0);
1293   }
1294 
isDupAlignedMemory32() const1295   bool isDupAlignedMemory32() const {
1296     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1297       return true;
1298     return isMemNoOffset(false, 0);
1299   }
1300 
isAlignedMemory64() const1301   bool isAlignedMemory64() const {
1302     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1303       return true;
1304     return isMemNoOffset(false, 0);
1305   }
1306 
isDupAlignedMemory64() const1307   bool isDupAlignedMemory64() const {
1308     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1309       return true;
1310     return isMemNoOffset(false, 0);
1311   }
1312 
isAlignedMemory64or128() const1313   bool isAlignedMemory64or128() const {
1314     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1315       return true;
1316     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1317       return true;
1318     return isMemNoOffset(false, 0);
1319   }
1320 
isDupAlignedMemory64or128() const1321   bool isDupAlignedMemory64or128() const {
1322     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1323       return true;
1324     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1325       return true;
1326     return isMemNoOffset(false, 0);
1327   }
1328 
isAlignedMemory64or128or256() const1329   bool isAlignedMemory64or128or256() const {
1330     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1331       return true;
1332     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1333       return true;
1334     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1335       return true;
1336     return isMemNoOffset(false, 0);
1337   }
1338 
isAddrMode2() const1339   bool isAddrMode2() const {
1340     if (!isMem() || Memory.Alignment != 0) return false;
1341     // Check for register offset.
1342     if (Memory.OffsetRegNum) return true;
1343     // Immediate offset in range [-4095, 4095].
1344     if (!Memory.OffsetImm) return true;
1345     int64_t Val = Memory.OffsetImm->getValue();
1346     return Val > -4096 && Val < 4096;
1347   }
1348 
isAM2OffsetImm() const1349   bool isAM2OffsetImm() const {
1350     if (!isImm()) return false;
1351     // Immediate offset in range [-4095, 4095].
1352     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1353     if (!CE) return false;
1354     int64_t Val = CE->getValue();
1355     return (Val == std::numeric_limits<int32_t>::min()) ||
1356            (Val > -4096 && Val < 4096);
1357   }
1358 
isAddrMode3() const1359   bool isAddrMode3() const {
1360     // If we have an immediate that's not a constant, treat it as a label
1361     // reference needing a fixup. If it is a constant, it's something else
1362     // and we reject it.
1363     if (isImm() && !isa<MCConstantExpr>(getImm()))
1364       return true;
1365     if (!isMem() || Memory.Alignment != 0) return false;
1366     // No shifts are legal for AM3.
1367     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1368     // Check for register offset.
1369     if (Memory.OffsetRegNum) return true;
1370     // Immediate offset in range [-255, 255].
1371     if (!Memory.OffsetImm) return true;
1372     int64_t Val = Memory.OffsetImm->getValue();
1373     // The #-0 offset is encoded as std::numeric_limits<int32_t>::min(), and we
1374     // have to check for this too.
1375     return (Val > -256 && Val < 256) ||
1376            Val == std::numeric_limits<int32_t>::min();
1377   }
1378 
isAM3Offset() const1379   bool isAM3Offset() const {
1380     if (isPostIdxReg())
1381       return true;
1382     if (!isImm())
1383       return false;
1384     // Immediate offset in range [-255, 255].
1385     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1386     if (!CE) return false;
1387     int64_t Val = CE->getValue();
1388     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1389     return (Val > -256 && Val < 256) ||
1390            Val == std::numeric_limits<int32_t>::min();
1391   }
1392 
isAddrMode5() const1393   bool isAddrMode5() const {
1394     // If we have an immediate that's not a constant, treat it as a label
1395     // reference needing a fixup. If it is a constant, it's something else
1396     // and we reject it.
1397     if (isImm() && !isa<MCConstantExpr>(getImm()))
1398       return true;
1399     if (!isMem() || Memory.Alignment != 0) return false;
1400     // Check for register offset.
1401     if (Memory.OffsetRegNum) return false;
1402     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1403     if (!Memory.OffsetImm) return true;
1404     int64_t Val = Memory.OffsetImm->getValue();
1405     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1406       Val == std::numeric_limits<int32_t>::min();
1407   }
1408 
isAddrMode5FP16() const1409   bool isAddrMode5FP16() const {
1410     // If we have an immediate that's not a constant, treat it as a label
1411     // reference needing a fixup. If it is a constant, it's something else
1412     // and we reject it.
1413     if (isImm() && !isa<MCConstantExpr>(getImm()))
1414       return true;
1415     if (!isMem() || Memory.Alignment != 0) return false;
1416     // Check for register offset.
1417     if (Memory.OffsetRegNum) return false;
1418     // Immediate offset in range [-510, 510] and a multiple of 2.
1419     if (!Memory.OffsetImm) return true;
1420     int64_t Val = Memory.OffsetImm->getValue();
1421     return (Val >= -510 && Val <= 510 && ((Val & 1) == 0)) ||
1422            Val == std::numeric_limits<int32_t>::min();
1423   }
1424 
isMemTBB() const1425   bool isMemTBB() const {
1426     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1427         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1428       return false;
1429     return true;
1430   }
1431 
isMemTBH() const1432   bool isMemTBH() const {
1433     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1434         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1435         Memory.Alignment != 0 )
1436       return false;
1437     return true;
1438   }
1439 
isMemRegOffset() const1440   bool isMemRegOffset() const {
1441     if (!isMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1442       return false;
1443     return true;
1444   }
1445 
isT2MemRegOffset() const1446   bool isT2MemRegOffset() const {
1447     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1448         Memory.Alignment != 0 || Memory.BaseRegNum == ARM::PC)
1449       return false;
1450     // Only lsl #{0, 1, 2, 3} allowed.
1451     if (Memory.ShiftType == ARM_AM::no_shift)
1452       return true;
1453     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1454       return false;
1455     return true;
1456   }
1457 
isMemThumbRR() const1458   bool isMemThumbRR() const {
1459     // Thumb reg+reg addressing is simple. Just two registers, a base and
1460     // an offset. No shifts, negations or any other complicating factors.
1461     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1462         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1463       return false;
1464     return isARMLowRegister(Memory.BaseRegNum) &&
1465       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1466   }
1467 
isMemThumbRIs4() const1468   bool isMemThumbRIs4() const {
1469     if (!isMem() || Memory.OffsetRegNum != 0 ||
1470         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1471       return false;
1472     // Immediate offset, multiple of 4 in range [0, 124].
1473     if (!Memory.OffsetImm) return true;
1474     int64_t Val = Memory.OffsetImm->getValue();
1475     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1476   }
1477 
isMemThumbRIs2() const1478   bool isMemThumbRIs2() const {
1479     if (!isMem() || Memory.OffsetRegNum != 0 ||
1480         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1481       return false;
1482     // Immediate offset, multiple of 4 in range [0, 62].
1483     if (!Memory.OffsetImm) return true;
1484     int64_t Val = Memory.OffsetImm->getValue();
1485     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1486   }
1487 
isMemThumbRIs1() const1488   bool isMemThumbRIs1() const {
1489     if (!isMem() || Memory.OffsetRegNum != 0 ||
1490         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1491       return false;
1492     // Immediate offset in range [0, 31].
1493     if (!Memory.OffsetImm) return true;
1494     int64_t Val = Memory.OffsetImm->getValue();
1495     return Val >= 0 && Val <= 31;
1496   }
1497 
isMemThumbSPI() const1498   bool isMemThumbSPI() const {
1499     if (!isMem() || Memory.OffsetRegNum != 0 ||
1500         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1501       return false;
1502     // Immediate offset, multiple of 4 in range [0, 1020].
1503     if (!Memory.OffsetImm) return true;
1504     int64_t Val = Memory.OffsetImm->getValue();
1505     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1506   }
1507 
isMemImm8s4Offset() const1508   bool isMemImm8s4Offset() const {
1509     // If we have an immediate that's not a constant, treat it as a label
1510     // reference needing a fixup. If it is a constant, it's something else
1511     // and we reject it.
1512     if (isImm() && !isa<MCConstantExpr>(getImm()))
1513       return true;
1514     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1515       return false;
1516     // Immediate offset a multiple of 4 in range [-1020, 1020].
1517     if (!Memory.OffsetImm) return true;
1518     int64_t Val = Memory.OffsetImm->getValue();
1519     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1520     return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) ||
1521            Val == std::numeric_limits<int32_t>::min();
1522   }
1523 
isMemImm0_1020s4Offset() const1524   bool isMemImm0_1020s4Offset() const {
1525     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1526       return false;
1527     // Immediate offset a multiple of 4 in range [0, 1020].
1528     if (!Memory.OffsetImm) return true;
1529     int64_t Val = Memory.OffsetImm->getValue();
1530     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1531   }
1532 
isMemImm8Offset() const1533   bool isMemImm8Offset() const {
1534     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1535       return false;
1536     // Base reg of PC isn't allowed for these encodings.
1537     if (Memory.BaseRegNum == ARM::PC) return false;
1538     // Immediate offset in range [-255, 255].
1539     if (!Memory.OffsetImm) return true;
1540     int64_t Val = Memory.OffsetImm->getValue();
1541     return (Val == std::numeric_limits<int32_t>::min()) ||
1542            (Val > -256 && Val < 256);
1543   }
1544 
isMemPosImm8Offset() const1545   bool isMemPosImm8Offset() const {
1546     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1547       return false;
1548     // Immediate offset in range [0, 255].
1549     if (!Memory.OffsetImm) return true;
1550     int64_t Val = Memory.OffsetImm->getValue();
1551     return Val >= 0 && Val < 256;
1552   }
1553 
isMemNegImm8Offset() const1554   bool isMemNegImm8Offset() const {
1555     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1556       return false;
1557     // Base reg of PC isn't allowed for these encodings.
1558     if (Memory.BaseRegNum == ARM::PC) return false;
1559     // Immediate offset in range [-255, -1].
1560     if (!Memory.OffsetImm) return false;
1561     int64_t Val = Memory.OffsetImm->getValue();
1562     return (Val == std::numeric_limits<int32_t>::min()) ||
1563            (Val > -256 && Val < 0);
1564   }
1565 
isMemUImm12Offset() const1566   bool isMemUImm12Offset() const {
1567     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1568       return false;
1569     // Immediate offset in range [0, 4095].
1570     if (!Memory.OffsetImm) return true;
1571     int64_t Val = Memory.OffsetImm->getValue();
1572     return (Val >= 0 && Val < 4096);
1573   }
1574 
isMemImm12Offset() const1575   bool isMemImm12Offset() const {
1576     // If we have an immediate that's not a constant, treat it as a label
1577     // reference needing a fixup. If it is a constant, it's something else
1578     // and we reject it.
1579 
1580     if (isImm() && !isa<MCConstantExpr>(getImm()))
1581       return true;
1582 
1583     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1584       return false;
1585     // Immediate offset in range [-4095, 4095].
1586     if (!Memory.OffsetImm) return true;
1587     int64_t Val = Memory.OffsetImm->getValue();
1588     return (Val > -4096 && Val < 4096) ||
1589            (Val == std::numeric_limits<int32_t>::min());
1590   }
1591 
isConstPoolAsmImm() const1592   bool isConstPoolAsmImm() const {
1593     // Delay processing of Constant Pool Immediate, this will turn into
1594     // a constant. Match no other operand
1595     return (isConstantPoolImm());
1596   }
1597 
isPostIdxImm8() const1598   bool isPostIdxImm8() const {
1599     if (!isImm()) return false;
1600     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1601     if (!CE) return false;
1602     int64_t Val = CE->getValue();
1603     return (Val > -256 && Val < 256) ||
1604            (Val == std::numeric_limits<int32_t>::min());
1605   }
1606 
isPostIdxImm8s4() const1607   bool isPostIdxImm8s4() const {
1608     if (!isImm()) return false;
1609     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1610     if (!CE) return false;
1611     int64_t Val = CE->getValue();
1612     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
1613            (Val == std::numeric_limits<int32_t>::min());
1614   }
1615 
isMSRMask() const1616   bool isMSRMask() const { return Kind == k_MSRMask; }
isBankedReg() const1617   bool isBankedReg() const { return Kind == k_BankedReg; }
isProcIFlags() const1618   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
1619 
1620   // NEON operands.
isSingleSpacedVectorList() const1621   bool isSingleSpacedVectorList() const {
1622     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
1623   }
1624 
isDoubleSpacedVectorList() const1625   bool isDoubleSpacedVectorList() const {
1626     return Kind == k_VectorList && VectorList.isDoubleSpaced;
1627   }
1628 
isVecListOneD() const1629   bool isVecListOneD() const {
1630     if (!isSingleSpacedVectorList()) return false;
1631     return VectorList.Count == 1;
1632   }
1633 
isVecListDPair() const1634   bool isVecListDPair() const {
1635     if (!isSingleSpacedVectorList()) return false;
1636     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1637               .contains(VectorList.RegNum));
1638   }
1639 
isVecListThreeD() const1640   bool isVecListThreeD() const {
1641     if (!isSingleSpacedVectorList()) return false;
1642     return VectorList.Count == 3;
1643   }
1644 
isVecListFourD() const1645   bool isVecListFourD() const {
1646     if (!isSingleSpacedVectorList()) return false;
1647     return VectorList.Count == 4;
1648   }
1649 
isVecListDPairSpaced() const1650   bool isVecListDPairSpaced() const {
1651     if (Kind != k_VectorList) return false;
1652     if (isSingleSpacedVectorList()) return false;
1653     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
1654               .contains(VectorList.RegNum));
1655   }
1656 
isVecListThreeQ() const1657   bool isVecListThreeQ() const {
1658     if (!isDoubleSpacedVectorList()) return false;
1659     return VectorList.Count == 3;
1660   }
1661 
isVecListFourQ() const1662   bool isVecListFourQ() const {
1663     if (!isDoubleSpacedVectorList()) return false;
1664     return VectorList.Count == 4;
1665   }
1666 
isSingleSpacedVectorAllLanes() const1667   bool isSingleSpacedVectorAllLanes() const {
1668     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
1669   }
1670 
isDoubleSpacedVectorAllLanes() const1671   bool isDoubleSpacedVectorAllLanes() const {
1672     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
1673   }
1674 
isVecListOneDAllLanes() const1675   bool isVecListOneDAllLanes() const {
1676     if (!isSingleSpacedVectorAllLanes()) return false;
1677     return VectorList.Count == 1;
1678   }
1679 
isVecListDPairAllLanes() const1680   bool isVecListDPairAllLanes() const {
1681     if (!isSingleSpacedVectorAllLanes()) return false;
1682     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1683               .contains(VectorList.RegNum));
1684   }
1685 
isVecListDPairSpacedAllLanes() const1686   bool isVecListDPairSpacedAllLanes() const {
1687     if (!isDoubleSpacedVectorAllLanes()) return false;
1688     return VectorList.Count == 2;
1689   }
1690 
isVecListThreeDAllLanes() const1691   bool isVecListThreeDAllLanes() const {
1692     if (!isSingleSpacedVectorAllLanes()) return false;
1693     return VectorList.Count == 3;
1694   }
1695 
isVecListThreeQAllLanes() const1696   bool isVecListThreeQAllLanes() const {
1697     if (!isDoubleSpacedVectorAllLanes()) return false;
1698     return VectorList.Count == 3;
1699   }
1700 
isVecListFourDAllLanes() const1701   bool isVecListFourDAllLanes() const {
1702     if (!isSingleSpacedVectorAllLanes()) return false;
1703     return VectorList.Count == 4;
1704   }
1705 
isVecListFourQAllLanes() const1706   bool isVecListFourQAllLanes() const {
1707     if (!isDoubleSpacedVectorAllLanes()) return false;
1708     return VectorList.Count == 4;
1709   }
1710 
isSingleSpacedVectorIndexed() const1711   bool isSingleSpacedVectorIndexed() const {
1712     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
1713   }
1714 
isDoubleSpacedVectorIndexed() const1715   bool isDoubleSpacedVectorIndexed() const {
1716     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
1717   }
1718 
isVecListOneDByteIndexed() const1719   bool isVecListOneDByteIndexed() const {
1720     if (!isSingleSpacedVectorIndexed()) return false;
1721     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
1722   }
1723 
isVecListOneDHWordIndexed() const1724   bool isVecListOneDHWordIndexed() const {
1725     if (!isSingleSpacedVectorIndexed()) return false;
1726     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
1727   }
1728 
isVecListOneDWordIndexed() const1729   bool isVecListOneDWordIndexed() const {
1730     if (!isSingleSpacedVectorIndexed()) return false;
1731     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
1732   }
1733 
isVecListTwoDByteIndexed() const1734   bool isVecListTwoDByteIndexed() const {
1735     if (!isSingleSpacedVectorIndexed()) return false;
1736     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
1737   }
1738 
isVecListTwoDHWordIndexed() const1739   bool isVecListTwoDHWordIndexed() const {
1740     if (!isSingleSpacedVectorIndexed()) return false;
1741     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1742   }
1743 
isVecListTwoQWordIndexed() const1744   bool isVecListTwoQWordIndexed() const {
1745     if (!isDoubleSpacedVectorIndexed()) return false;
1746     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1747   }
1748 
isVecListTwoQHWordIndexed() const1749   bool isVecListTwoQHWordIndexed() const {
1750     if (!isDoubleSpacedVectorIndexed()) return false;
1751     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1752   }
1753 
isVecListTwoDWordIndexed() const1754   bool isVecListTwoDWordIndexed() const {
1755     if (!isSingleSpacedVectorIndexed()) return false;
1756     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1757   }
1758 
isVecListThreeDByteIndexed() const1759   bool isVecListThreeDByteIndexed() const {
1760     if (!isSingleSpacedVectorIndexed()) return false;
1761     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
1762   }
1763 
isVecListThreeDHWordIndexed() const1764   bool isVecListThreeDHWordIndexed() const {
1765     if (!isSingleSpacedVectorIndexed()) return false;
1766     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1767   }
1768 
isVecListThreeQWordIndexed() const1769   bool isVecListThreeQWordIndexed() const {
1770     if (!isDoubleSpacedVectorIndexed()) return false;
1771     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1772   }
1773 
isVecListThreeQHWordIndexed() const1774   bool isVecListThreeQHWordIndexed() const {
1775     if (!isDoubleSpacedVectorIndexed()) return false;
1776     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1777   }
1778 
isVecListThreeDWordIndexed() const1779   bool isVecListThreeDWordIndexed() const {
1780     if (!isSingleSpacedVectorIndexed()) return false;
1781     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1782   }
1783 
isVecListFourDByteIndexed() const1784   bool isVecListFourDByteIndexed() const {
1785     if (!isSingleSpacedVectorIndexed()) return false;
1786     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
1787   }
1788 
isVecListFourDHWordIndexed() const1789   bool isVecListFourDHWordIndexed() const {
1790     if (!isSingleSpacedVectorIndexed()) return false;
1791     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1792   }
1793 
isVecListFourQWordIndexed() const1794   bool isVecListFourQWordIndexed() const {
1795     if (!isDoubleSpacedVectorIndexed()) return false;
1796     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1797   }
1798 
isVecListFourQHWordIndexed() const1799   bool isVecListFourQHWordIndexed() const {
1800     if (!isDoubleSpacedVectorIndexed()) return false;
1801     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1802   }
1803 
isVecListFourDWordIndexed() const1804   bool isVecListFourDWordIndexed() const {
1805     if (!isSingleSpacedVectorIndexed()) return false;
1806     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1807   }
1808 
isVectorIndex8() const1809   bool isVectorIndex8() const {
1810     if (Kind != k_VectorIndex) return false;
1811     return VectorIndex.Val < 8;
1812   }
1813 
isVectorIndex16() const1814   bool isVectorIndex16() const {
1815     if (Kind != k_VectorIndex) return false;
1816     return VectorIndex.Val < 4;
1817   }
1818 
isVectorIndex32() const1819   bool isVectorIndex32() const {
1820     if (Kind != k_VectorIndex) return false;
1821     return VectorIndex.Val < 2;
1822   }
isVectorIndex64() const1823   bool isVectorIndex64() const {
1824     if (Kind != k_VectorIndex) return false;
1825     return VectorIndex.Val < 1;
1826   }
1827 
isNEONi8splat() const1828   bool isNEONi8splat() const {
1829     if (!isImm()) return false;
1830     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1831     // Must be a constant.
1832     if (!CE) return false;
1833     int64_t Value = CE->getValue();
1834     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
1835     // value.
1836     return Value >= 0 && Value < 256;
1837   }
1838 
isNEONi16splat() const1839   bool isNEONi16splat() const {
1840     if (isNEONByteReplicate(2))
1841       return false; // Leave that for bytes replication and forbid by default.
1842     if (!isImm())
1843       return false;
1844     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1845     // Must be a constant.
1846     if (!CE) return false;
1847     unsigned Value = CE->getValue();
1848     return ARM_AM::isNEONi16splat(Value);
1849   }
1850 
isNEONi16splatNot() const1851   bool isNEONi16splatNot() const {
1852     if (!isImm())
1853       return false;
1854     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1855     // Must be a constant.
1856     if (!CE) return false;
1857     unsigned Value = CE->getValue();
1858     return ARM_AM::isNEONi16splat(~Value & 0xffff);
1859   }
1860 
isNEONi32splat() const1861   bool isNEONi32splat() const {
1862     if (isNEONByteReplicate(4))
1863       return false; // Leave that for bytes replication and forbid by default.
1864     if (!isImm())
1865       return false;
1866     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1867     // Must be a constant.
1868     if (!CE) return false;
1869     unsigned Value = CE->getValue();
1870     return ARM_AM::isNEONi32splat(Value);
1871   }
1872 
isNEONi32splatNot() const1873   bool isNEONi32splatNot() const {
1874     if (!isImm())
1875       return false;
1876     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1877     // Must be a constant.
1878     if (!CE) return false;
1879     unsigned Value = CE->getValue();
1880     return ARM_AM::isNEONi32splat(~Value);
1881   }
1882 
isValidNEONi32vmovImm(int64_t Value)1883   static bool isValidNEONi32vmovImm(int64_t Value) {
1884     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1885     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1886     return ((Value & 0xffffffffffffff00) == 0) ||
1887            ((Value & 0xffffffffffff00ff) == 0) ||
1888            ((Value & 0xffffffffff00ffff) == 0) ||
1889            ((Value & 0xffffffff00ffffff) == 0) ||
1890            ((Value & 0xffffffffffff00ff) == 0xff) ||
1891            ((Value & 0xffffffffff00ffff) == 0xffff);
1892   }
1893 
isNEONReplicate(unsigned Width,unsigned NumElems,bool Inv) const1894   bool isNEONReplicate(unsigned Width, unsigned NumElems, bool Inv) const {
1895     assert((Width == 8 || Width == 16 || Width == 32) &&
1896            "Invalid element width");
1897     assert(NumElems * Width <= 64 && "Invalid result width");
1898 
1899     if (!isImm())
1900       return false;
1901     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1902     // Must be a constant.
1903     if (!CE)
1904       return false;
1905     int64_t Value = CE->getValue();
1906     if (!Value)
1907       return false; // Don't bother with zero.
1908     if (Inv)
1909       Value = ~Value;
1910 
1911     uint64_t Mask = (1ull << Width) - 1;
1912     uint64_t Elem = Value & Mask;
1913     if (Width == 16 && (Elem & 0x00ff) != 0 && (Elem & 0xff00) != 0)
1914       return false;
1915     if (Width == 32 && !isValidNEONi32vmovImm(Elem))
1916       return false;
1917 
1918     for (unsigned i = 1; i < NumElems; ++i) {
1919       Value >>= Width;
1920       if ((Value & Mask) != Elem)
1921         return false;
1922     }
1923     return true;
1924   }
1925 
isNEONByteReplicate(unsigned NumBytes) const1926   bool isNEONByteReplicate(unsigned NumBytes) const {
1927     return isNEONReplicate(8, NumBytes, false);
1928   }
1929 
checkNeonReplicateArgs(unsigned FromW,unsigned ToW)1930   static void checkNeonReplicateArgs(unsigned FromW, unsigned ToW) {
1931     assert((FromW == 8 || FromW == 16 || FromW == 32) &&
1932            "Invalid source width");
1933     assert((ToW == 16 || ToW == 32 || ToW == 64) &&
1934            "Invalid destination width");
1935     assert(FromW < ToW && "ToW is not less than FromW");
1936   }
1937 
1938   template<unsigned FromW, unsigned ToW>
isNEONmovReplicate() const1939   bool isNEONmovReplicate() const {
1940     checkNeonReplicateArgs(FromW, ToW);
1941     if (ToW == 64 && isNEONi64splat())
1942       return false;
1943     return isNEONReplicate(FromW, ToW / FromW, false);
1944   }
1945 
1946   template<unsigned FromW, unsigned ToW>
isNEONinvReplicate() const1947   bool isNEONinvReplicate() const {
1948     checkNeonReplicateArgs(FromW, ToW);
1949     return isNEONReplicate(FromW, ToW / FromW, true);
1950   }
1951 
isNEONi32vmov() const1952   bool isNEONi32vmov() const {
1953     if (isNEONByteReplicate(4))
1954       return false; // Let it to be classified as byte-replicate case.
1955     if (!isImm())
1956       return false;
1957     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1958     // Must be a constant.
1959     if (!CE)
1960       return false;
1961     return isValidNEONi32vmovImm(CE->getValue());
1962   }
1963 
isNEONi32vmovNeg() const1964   bool isNEONi32vmovNeg() const {
1965     if (!isImm()) return false;
1966     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1967     // Must be a constant.
1968     if (!CE) return false;
1969     return isValidNEONi32vmovImm(~CE->getValue());
1970   }
1971 
isNEONi64splat() const1972   bool isNEONi64splat() const {
1973     if (!isImm()) return false;
1974     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1975     // Must be a constant.
1976     if (!CE) return false;
1977     uint64_t Value = CE->getValue();
1978     // i64 value with each byte being either 0 or 0xff.
1979     for (unsigned i = 0; i < 8; ++i, Value >>= 8)
1980       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
1981     return true;
1982   }
1983 
1984   template<int64_t Angle, int64_t Remainder>
isComplexRotation() const1985   bool isComplexRotation() const {
1986     if (!isImm()) return false;
1987 
1988     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1989     if (!CE) return false;
1990     uint64_t Value = CE->getValue();
1991 
1992     return (Value % Angle == Remainder && Value <= 270);
1993   }
1994 
addExpr(MCInst & Inst,const MCExpr * Expr) const1995   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
1996     // Add as immediates when possible.  Null MCExpr = 0.
1997     if (!Expr)
1998       Inst.addOperand(MCOperand::createImm(0));
1999     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
2000       Inst.addOperand(MCOperand::createImm(CE->getValue()));
2001     else
2002       Inst.addOperand(MCOperand::createExpr(Expr));
2003   }
2004 
addARMBranchTargetOperands(MCInst & Inst,unsigned N) const2005   void addARMBranchTargetOperands(MCInst &Inst, unsigned N) const {
2006     assert(N == 1 && "Invalid number of operands!");
2007     addExpr(Inst, getImm());
2008   }
2009 
addThumbBranchTargetOperands(MCInst & Inst,unsigned N) const2010   void addThumbBranchTargetOperands(MCInst &Inst, unsigned N) const {
2011     assert(N == 1 && "Invalid number of operands!");
2012     addExpr(Inst, getImm());
2013   }
2014 
addCondCodeOperands(MCInst & Inst,unsigned N) const2015   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
2016     assert(N == 2 && "Invalid number of operands!");
2017     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
2018     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
2019     Inst.addOperand(MCOperand::createReg(RegNum));
2020   }
2021 
addCoprocNumOperands(MCInst & Inst,unsigned N) const2022   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
2023     assert(N == 1 && "Invalid number of operands!");
2024     Inst.addOperand(MCOperand::createImm(getCoproc()));
2025   }
2026 
addCoprocRegOperands(MCInst & Inst,unsigned N) const2027   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
2028     assert(N == 1 && "Invalid number of operands!");
2029     Inst.addOperand(MCOperand::createImm(getCoproc()));
2030   }
2031 
addCoprocOptionOperands(MCInst & Inst,unsigned N) const2032   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
2033     assert(N == 1 && "Invalid number of operands!");
2034     Inst.addOperand(MCOperand::createImm(CoprocOption.Val));
2035   }
2036 
addITMaskOperands(MCInst & Inst,unsigned N) const2037   void addITMaskOperands(MCInst &Inst, unsigned N) const {
2038     assert(N == 1 && "Invalid number of operands!");
2039     Inst.addOperand(MCOperand::createImm(ITMask.Mask));
2040   }
2041 
addITCondCodeOperands(MCInst & Inst,unsigned N) const2042   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
2043     assert(N == 1 && "Invalid number of operands!");
2044     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
2045   }
2046 
addCCOutOperands(MCInst & Inst,unsigned N) const2047   void addCCOutOperands(MCInst &Inst, unsigned N) const {
2048     assert(N == 1 && "Invalid number of operands!");
2049     Inst.addOperand(MCOperand::createReg(getReg()));
2050   }
2051 
addRegOperands(MCInst & Inst,unsigned N) const2052   void addRegOperands(MCInst &Inst, unsigned N) const {
2053     assert(N == 1 && "Invalid number of operands!");
2054     Inst.addOperand(MCOperand::createReg(getReg()));
2055   }
2056 
addRegShiftedRegOperands(MCInst & Inst,unsigned N) const2057   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
2058     assert(N == 3 && "Invalid number of operands!");
2059     assert(isRegShiftedReg() &&
2060            "addRegShiftedRegOperands() on non-RegShiftedReg!");
2061     Inst.addOperand(MCOperand::createReg(RegShiftedReg.SrcReg));
2062     Inst.addOperand(MCOperand::createReg(RegShiftedReg.ShiftReg));
2063     Inst.addOperand(MCOperand::createImm(
2064       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
2065   }
2066 
addRegShiftedImmOperands(MCInst & Inst,unsigned N) const2067   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
2068     assert(N == 2 && "Invalid number of operands!");
2069     assert(isRegShiftedImm() &&
2070            "addRegShiftedImmOperands() on non-RegShiftedImm!");
2071     Inst.addOperand(MCOperand::createReg(RegShiftedImm.SrcReg));
2072     // Shift of #32 is encoded as 0 where permitted
2073     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
2074     Inst.addOperand(MCOperand::createImm(
2075       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
2076   }
2077 
addShifterImmOperands(MCInst & Inst,unsigned N) const2078   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
2079     assert(N == 1 && "Invalid number of operands!");
2080     Inst.addOperand(MCOperand::createImm((ShifterImm.isASR << 5) |
2081                                          ShifterImm.Imm));
2082   }
2083 
addRegListOperands(MCInst & Inst,unsigned N) const2084   void addRegListOperands(MCInst &Inst, unsigned N) const {
2085     assert(N == 1 && "Invalid number of operands!");
2086     const SmallVectorImpl<unsigned> &RegList = getRegList();
2087     for (SmallVectorImpl<unsigned>::const_iterator
2088            I = RegList.begin(), E = RegList.end(); I != E; ++I)
2089       Inst.addOperand(MCOperand::createReg(*I));
2090   }
2091 
addDPRRegListOperands(MCInst & Inst,unsigned N) const2092   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
2093     addRegListOperands(Inst, N);
2094   }
2095 
addSPRRegListOperands(MCInst & Inst,unsigned N) const2096   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
2097     addRegListOperands(Inst, N);
2098   }
2099 
addRotImmOperands(MCInst & Inst,unsigned N) const2100   void addRotImmOperands(MCInst &Inst, unsigned N) const {
2101     assert(N == 1 && "Invalid number of operands!");
2102     // Encoded as val>>3. The printer handles display as 8, 16, 24.
2103     Inst.addOperand(MCOperand::createImm(RotImm.Imm >> 3));
2104   }
2105 
addModImmOperands(MCInst & Inst,unsigned N) const2106   void addModImmOperands(MCInst &Inst, unsigned N) const {
2107     assert(N == 1 && "Invalid number of operands!");
2108 
2109     // Support for fixups (MCFixup)
2110     if (isImm())
2111       return addImmOperands(Inst, N);
2112 
2113     Inst.addOperand(MCOperand::createImm(ModImm.Bits | (ModImm.Rot << 7)));
2114   }
2115 
addModImmNotOperands(MCInst & Inst,unsigned N) const2116   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
2117     assert(N == 1 && "Invalid number of operands!");
2118     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2119     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
2120     Inst.addOperand(MCOperand::createImm(Enc));
2121   }
2122 
addModImmNegOperands(MCInst & Inst,unsigned N) const2123   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
2124     assert(N == 1 && "Invalid number of operands!");
2125     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2126     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
2127     Inst.addOperand(MCOperand::createImm(Enc));
2128   }
2129 
addThumbModImmNeg8_255Operands(MCInst & Inst,unsigned N) const2130   void addThumbModImmNeg8_255Operands(MCInst &Inst, unsigned N) const {
2131     assert(N == 1 && "Invalid number of operands!");
2132     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2133     uint32_t Val = -CE->getValue();
2134     Inst.addOperand(MCOperand::createImm(Val));
2135   }
2136 
addThumbModImmNeg1_7Operands(MCInst & Inst,unsigned N) const2137   void addThumbModImmNeg1_7Operands(MCInst &Inst, unsigned N) const {
2138     assert(N == 1 && "Invalid number of operands!");
2139     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2140     uint32_t Val = -CE->getValue();
2141     Inst.addOperand(MCOperand::createImm(Val));
2142   }
2143 
addBitfieldOperands(MCInst & Inst,unsigned N) const2144   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
2145     assert(N == 1 && "Invalid number of operands!");
2146     // Munge the lsb/width into a bitfield mask.
2147     unsigned lsb = Bitfield.LSB;
2148     unsigned width = Bitfield.Width;
2149     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
2150     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
2151                       (32 - (lsb + width)));
2152     Inst.addOperand(MCOperand::createImm(Mask));
2153   }
2154 
addImmOperands(MCInst & Inst,unsigned N) const2155   void addImmOperands(MCInst &Inst, unsigned N) const {
2156     assert(N == 1 && "Invalid number of operands!");
2157     addExpr(Inst, getImm());
2158   }
2159 
addFBits16Operands(MCInst & Inst,unsigned N) const2160   void addFBits16Operands(MCInst &Inst, unsigned N) const {
2161     assert(N == 1 && "Invalid number of operands!");
2162     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2163     Inst.addOperand(MCOperand::createImm(16 - CE->getValue()));
2164   }
2165 
addFBits32Operands(MCInst & Inst,unsigned N) const2166   void addFBits32Operands(MCInst &Inst, unsigned N) const {
2167     assert(N == 1 && "Invalid number of operands!");
2168     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2169     Inst.addOperand(MCOperand::createImm(32 - CE->getValue()));
2170   }
2171 
addFPImmOperands(MCInst & Inst,unsigned N) const2172   void addFPImmOperands(MCInst &Inst, unsigned N) const {
2173     assert(N == 1 && "Invalid number of operands!");
2174     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2175     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
2176     Inst.addOperand(MCOperand::createImm(Val));
2177   }
2178 
addImm8s4Operands(MCInst & Inst,unsigned N) const2179   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
2180     assert(N == 1 && "Invalid number of operands!");
2181     // FIXME: We really want to scale the value here, but the LDRD/STRD
2182     // instruction don't encode operands that way yet.
2183     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2184     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2185   }
2186 
addImm0_1020s4Operands(MCInst & Inst,unsigned N) const2187   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
2188     assert(N == 1 && "Invalid number of operands!");
2189     // The immediate is scaled by four in the encoding and is stored
2190     // in the MCInst as such. Lop off the low two bits here.
2191     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2192     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2193   }
2194 
addImm0_508s4NegOperands(MCInst & Inst,unsigned N) const2195   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
2196     assert(N == 1 && "Invalid number of operands!");
2197     // The immediate is scaled by four in the encoding and is stored
2198     // in the MCInst as such. Lop off the low two bits here.
2199     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2200     Inst.addOperand(MCOperand::createImm(-(CE->getValue() / 4)));
2201   }
2202 
addImm0_508s4Operands(MCInst & Inst,unsigned N) const2203   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
2204     assert(N == 1 && "Invalid number of operands!");
2205     // The immediate is scaled by four in the encoding and is stored
2206     // in the MCInst as such. Lop off the low two bits here.
2207     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2208     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2209   }
2210 
addImm1_16Operands(MCInst & Inst,unsigned N) const2211   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
2212     assert(N == 1 && "Invalid number of operands!");
2213     // The constant encodes as the immediate-1, and we store in the instruction
2214     // the bits as encoded, so subtract off one here.
2215     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2216     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2217   }
2218 
addImm1_32Operands(MCInst & Inst,unsigned N) const2219   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
2220     assert(N == 1 && "Invalid number of operands!");
2221     // The constant encodes as the immediate-1, and we store in the instruction
2222     // the bits as encoded, so subtract off one here.
2223     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2224     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2225   }
2226 
addImmThumbSROperands(MCInst & Inst,unsigned N) const2227   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
2228     assert(N == 1 && "Invalid number of operands!");
2229     // The constant encodes as the immediate, except for 32, which encodes as
2230     // zero.
2231     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2232     unsigned Imm = CE->getValue();
2233     Inst.addOperand(MCOperand::createImm((Imm == 32 ? 0 : Imm)));
2234   }
2235 
addPKHASRImmOperands(MCInst & Inst,unsigned N) const2236   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
2237     assert(N == 1 && "Invalid number of operands!");
2238     // An ASR value of 32 encodes as 0, so that's how we want to add it to
2239     // the instruction as well.
2240     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2241     int Val = CE->getValue();
2242     Inst.addOperand(MCOperand::createImm(Val == 32 ? 0 : Val));
2243   }
2244 
addT2SOImmNotOperands(MCInst & Inst,unsigned N) const2245   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
2246     assert(N == 1 && "Invalid number of operands!");
2247     // The operand is actually a t2_so_imm, but we have its bitwise
2248     // negation in the assembly source, so twiddle it here.
2249     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2250     Inst.addOperand(MCOperand::createImm(~(uint32_t)CE->getValue()));
2251   }
2252 
addT2SOImmNegOperands(MCInst & Inst,unsigned N) const2253   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
2254     assert(N == 1 && "Invalid number of operands!");
2255     // The operand is actually a t2_so_imm, but we have its
2256     // negation in the assembly source, so twiddle it here.
2257     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2258     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2259   }
2260 
addImm0_4095NegOperands(MCInst & Inst,unsigned N) const2261   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
2262     assert(N == 1 && "Invalid number of operands!");
2263     // The operand is actually an imm0_4095, but we have its
2264     // negation in the assembly source, so twiddle it here.
2265     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2266     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2267   }
2268 
addUnsignedOffset_b8s2Operands(MCInst & Inst,unsigned N) const2269   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
2270     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
2271       Inst.addOperand(MCOperand::createImm(CE->getValue() >> 2));
2272       return;
2273     }
2274 
2275     const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2276     assert(SR && "Unknown value type!");
2277     Inst.addOperand(MCOperand::createExpr(SR));
2278   }
2279 
addThumbMemPCOperands(MCInst & Inst,unsigned N) const2280   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
2281     assert(N == 1 && "Invalid number of operands!");
2282     if (isImm()) {
2283       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2284       if (CE) {
2285         Inst.addOperand(MCOperand::createImm(CE->getValue()));
2286         return;
2287       }
2288 
2289       const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2290 
2291       assert(SR && "Unknown value type!");
2292       Inst.addOperand(MCOperand::createExpr(SR));
2293       return;
2294     }
2295 
2296     assert(isMem()  && "Unknown value type!");
2297     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
2298     Inst.addOperand(MCOperand::createImm(Memory.OffsetImm->getValue()));
2299   }
2300 
addMemBarrierOptOperands(MCInst & Inst,unsigned N) const2301   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
2302     assert(N == 1 && "Invalid number of operands!");
2303     Inst.addOperand(MCOperand::createImm(unsigned(getMemBarrierOpt())));
2304   }
2305 
addInstSyncBarrierOptOperands(MCInst & Inst,unsigned N) const2306   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2307     assert(N == 1 && "Invalid number of operands!");
2308     Inst.addOperand(MCOperand::createImm(unsigned(getInstSyncBarrierOpt())));
2309   }
2310 
addTraceSyncBarrierOptOperands(MCInst & Inst,unsigned N) const2311   void addTraceSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2312     assert(N == 1 && "Invalid number of operands!");
2313     Inst.addOperand(MCOperand::createImm(unsigned(getTraceSyncBarrierOpt())));
2314   }
2315 
addMemNoOffsetOperands(MCInst & Inst,unsigned N) const2316   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
2317     assert(N == 1 && "Invalid number of operands!");
2318     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2319   }
2320 
addMemPCRelImm12Operands(MCInst & Inst,unsigned N) const2321   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
2322     assert(N == 1 && "Invalid number of operands!");
2323     int32_t Imm = Memory.OffsetImm->getValue();
2324     Inst.addOperand(MCOperand::createImm(Imm));
2325   }
2326 
addAdrLabelOperands(MCInst & Inst,unsigned N) const2327   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
2328     assert(N == 1 && "Invalid number of operands!");
2329     assert(isImm() && "Not an immediate!");
2330 
2331     // If we have an immediate that's not a constant, treat it as a label
2332     // reference needing a fixup.
2333     if (!isa<MCConstantExpr>(getImm())) {
2334       Inst.addOperand(MCOperand::createExpr(getImm()));
2335       return;
2336     }
2337 
2338     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2339     int Val = CE->getValue();
2340     Inst.addOperand(MCOperand::createImm(Val));
2341   }
2342 
addAlignedMemoryOperands(MCInst & Inst,unsigned N) const2343   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
2344     assert(N == 2 && "Invalid number of operands!");
2345     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2346     Inst.addOperand(MCOperand::createImm(Memory.Alignment));
2347   }
2348 
addDupAlignedMemoryNoneOperands(MCInst & Inst,unsigned N) const2349   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2350     addAlignedMemoryOperands(Inst, N);
2351   }
2352 
addAlignedMemoryNoneOperands(MCInst & Inst,unsigned N) const2353   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2354     addAlignedMemoryOperands(Inst, N);
2355   }
2356 
addAlignedMemory16Operands(MCInst & Inst,unsigned N) const2357   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2358     addAlignedMemoryOperands(Inst, N);
2359   }
2360 
addDupAlignedMemory16Operands(MCInst & Inst,unsigned N) const2361   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2362     addAlignedMemoryOperands(Inst, N);
2363   }
2364 
addAlignedMemory32Operands(MCInst & Inst,unsigned N) const2365   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2366     addAlignedMemoryOperands(Inst, N);
2367   }
2368 
addDupAlignedMemory32Operands(MCInst & Inst,unsigned N) const2369   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2370     addAlignedMemoryOperands(Inst, N);
2371   }
2372 
addAlignedMemory64Operands(MCInst & Inst,unsigned N) const2373   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2374     addAlignedMemoryOperands(Inst, N);
2375   }
2376 
addDupAlignedMemory64Operands(MCInst & Inst,unsigned N) const2377   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2378     addAlignedMemoryOperands(Inst, N);
2379   }
2380 
addAlignedMemory64or128Operands(MCInst & Inst,unsigned N) const2381   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2382     addAlignedMemoryOperands(Inst, N);
2383   }
2384 
addDupAlignedMemory64or128Operands(MCInst & Inst,unsigned N) const2385   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2386     addAlignedMemoryOperands(Inst, N);
2387   }
2388 
addAlignedMemory64or128or256Operands(MCInst & Inst,unsigned N) const2389   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2390     addAlignedMemoryOperands(Inst, N);
2391   }
2392 
addAddrMode2Operands(MCInst & Inst,unsigned N) const2393   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2394     assert(N == 3 && "Invalid number of operands!");
2395     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2396     if (!Memory.OffsetRegNum) {
2397       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2398       // Special case for #-0
2399       if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2400       if (Val < 0) Val = -Val;
2401       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2402     } else {
2403       // For register offset, we encode the shift type and negation flag
2404       // here.
2405       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2406                               Memory.ShiftImm, Memory.ShiftType);
2407     }
2408     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2409     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2410     Inst.addOperand(MCOperand::createImm(Val));
2411   }
2412 
addAM2OffsetImmOperands(MCInst & Inst,unsigned N) const2413   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2414     assert(N == 2 && "Invalid number of operands!");
2415     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2416     assert(CE && "non-constant AM2OffsetImm operand!");
2417     int32_t Val = CE->getValue();
2418     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2419     // Special case for #-0
2420     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2421     if (Val < 0) Val = -Val;
2422     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2423     Inst.addOperand(MCOperand::createReg(0));
2424     Inst.addOperand(MCOperand::createImm(Val));
2425   }
2426 
addAddrMode3Operands(MCInst & Inst,unsigned N) const2427   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2428     assert(N == 3 && "Invalid number of operands!");
2429     // If we have an immediate that's not a constant, treat it as a label
2430     // reference needing a fixup. If it is a constant, it's something else
2431     // and we reject it.
2432     if (isImm()) {
2433       Inst.addOperand(MCOperand::createExpr(getImm()));
2434       Inst.addOperand(MCOperand::createReg(0));
2435       Inst.addOperand(MCOperand::createImm(0));
2436       return;
2437     }
2438 
2439     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2440     if (!Memory.OffsetRegNum) {
2441       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2442       // Special case for #-0
2443       if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2444       if (Val < 0) Val = -Val;
2445       Val = ARM_AM::getAM3Opc(AddSub, Val);
2446     } else {
2447       // For register offset, we encode the shift type and negation flag
2448       // here.
2449       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
2450     }
2451     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2452     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2453     Inst.addOperand(MCOperand::createImm(Val));
2454   }
2455 
addAM3OffsetOperands(MCInst & Inst,unsigned N) const2456   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
2457     assert(N == 2 && "Invalid number of operands!");
2458     if (Kind == k_PostIndexRegister) {
2459       int32_t Val =
2460         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
2461       Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2462       Inst.addOperand(MCOperand::createImm(Val));
2463       return;
2464     }
2465 
2466     // Constant offset.
2467     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
2468     int32_t Val = CE->getValue();
2469     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2470     // Special case for #-0
2471     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2472     if (Val < 0) Val = -Val;
2473     Val = ARM_AM::getAM3Opc(AddSub, Val);
2474     Inst.addOperand(MCOperand::createReg(0));
2475     Inst.addOperand(MCOperand::createImm(Val));
2476   }
2477 
addAddrMode5Operands(MCInst & Inst,unsigned N) const2478   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
2479     assert(N == 2 && "Invalid number of operands!");
2480     // If we have an immediate that's not a constant, treat it as a label
2481     // reference needing a fixup. If it is a constant, it's something else
2482     // and we reject it.
2483     if (isImm()) {
2484       Inst.addOperand(MCOperand::createExpr(getImm()));
2485       Inst.addOperand(MCOperand::createImm(0));
2486       return;
2487     }
2488 
2489     // The lower two bits are always zero and as such are not encoded.
2490     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2491     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2492     // Special case for #-0
2493     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2494     if (Val < 0) Val = -Val;
2495     Val = ARM_AM::getAM5Opc(AddSub, Val);
2496     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2497     Inst.addOperand(MCOperand::createImm(Val));
2498   }
2499 
addAddrMode5FP16Operands(MCInst & Inst,unsigned N) const2500   void addAddrMode5FP16Operands(MCInst &Inst, unsigned N) const {
2501     assert(N == 2 && "Invalid number of operands!");
2502     // If we have an immediate that's not a constant, treat it as a label
2503     // reference needing a fixup. If it is a constant, it's something else
2504     // and we reject it.
2505     if (isImm()) {
2506       Inst.addOperand(MCOperand::createExpr(getImm()));
2507       Inst.addOperand(MCOperand::createImm(0));
2508       return;
2509     }
2510 
2511     // The lower bit is always zero and as such is not encoded.
2512     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 2 : 0;
2513     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2514     // Special case for #-0
2515     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2516     if (Val < 0) Val = -Val;
2517     Val = ARM_AM::getAM5FP16Opc(AddSub, Val);
2518     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2519     Inst.addOperand(MCOperand::createImm(Val));
2520   }
2521 
addMemImm8s4OffsetOperands(MCInst & Inst,unsigned N) const2522   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
2523     assert(N == 2 && "Invalid number of operands!");
2524     // If we have an immediate that's not a constant, treat it as a label
2525     // reference needing a fixup. If it is a constant, it's something else
2526     // and we reject it.
2527     if (isImm()) {
2528       Inst.addOperand(MCOperand::createExpr(getImm()));
2529       Inst.addOperand(MCOperand::createImm(0));
2530       return;
2531     }
2532 
2533     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2534     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2535     Inst.addOperand(MCOperand::createImm(Val));
2536   }
2537 
addMemImm0_1020s4OffsetOperands(MCInst & Inst,unsigned N) const2538   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
2539     assert(N == 2 && "Invalid number of operands!");
2540     // The lower two bits are always zero and as such are not encoded.
2541     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2542     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2543     Inst.addOperand(MCOperand::createImm(Val));
2544   }
2545 
addMemImm8OffsetOperands(MCInst & Inst,unsigned N) const2546   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2547     assert(N == 2 && "Invalid number of operands!");
2548     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2549     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2550     Inst.addOperand(MCOperand::createImm(Val));
2551   }
2552 
addMemPosImm8OffsetOperands(MCInst & Inst,unsigned N) const2553   void addMemPosImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2554     addMemImm8OffsetOperands(Inst, N);
2555   }
2556 
addMemNegImm8OffsetOperands(MCInst & Inst,unsigned N) const2557   void addMemNegImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2558     addMemImm8OffsetOperands(Inst, N);
2559   }
2560 
addMemUImm12OffsetOperands(MCInst & Inst,unsigned N) const2561   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2562     assert(N == 2 && "Invalid number of operands!");
2563     // If this is an immediate, it's a label reference.
2564     if (isImm()) {
2565       addExpr(Inst, getImm());
2566       Inst.addOperand(MCOperand::createImm(0));
2567       return;
2568     }
2569 
2570     // Otherwise, it's a normal memory reg+offset.
2571     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2572     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2573     Inst.addOperand(MCOperand::createImm(Val));
2574   }
2575 
addMemImm12OffsetOperands(MCInst & Inst,unsigned N) const2576   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2577     assert(N == 2 && "Invalid number of operands!");
2578     // If this is an immediate, it's a label reference.
2579     if (isImm()) {
2580       addExpr(Inst, getImm());
2581       Inst.addOperand(MCOperand::createImm(0));
2582       return;
2583     }
2584 
2585     // Otherwise, it's a normal memory reg+offset.
2586     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2587     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2588     Inst.addOperand(MCOperand::createImm(Val));
2589   }
2590 
addConstPoolAsmImmOperands(MCInst & Inst,unsigned N) const2591   void addConstPoolAsmImmOperands(MCInst &Inst, unsigned N) const {
2592     assert(N == 1 && "Invalid number of operands!");
2593     // This is container for the immediate that we will create the constant
2594     // pool from
2595     addExpr(Inst, getConstantPoolImm());
2596     return;
2597   }
2598 
addMemTBBOperands(MCInst & Inst,unsigned N) const2599   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
2600     assert(N == 2 && "Invalid number of operands!");
2601     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2602     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2603   }
2604 
addMemTBHOperands(MCInst & Inst,unsigned N) const2605   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
2606     assert(N == 2 && "Invalid number of operands!");
2607     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2608     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2609   }
2610 
addMemRegOffsetOperands(MCInst & Inst,unsigned N) const2611   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2612     assert(N == 3 && "Invalid number of operands!");
2613     unsigned Val =
2614       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2615                         Memory.ShiftImm, Memory.ShiftType);
2616     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2617     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2618     Inst.addOperand(MCOperand::createImm(Val));
2619   }
2620 
addT2MemRegOffsetOperands(MCInst & Inst,unsigned N) const2621   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2622     assert(N == 3 && "Invalid number of operands!");
2623     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2624     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2625     Inst.addOperand(MCOperand::createImm(Memory.ShiftImm));
2626   }
2627 
addMemThumbRROperands(MCInst & Inst,unsigned N) const2628   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
2629     assert(N == 2 && "Invalid number of operands!");
2630     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2631     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2632   }
2633 
addMemThumbRIs4Operands(MCInst & Inst,unsigned N) const2634   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
2635     assert(N == 2 && "Invalid number of operands!");
2636     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2637     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2638     Inst.addOperand(MCOperand::createImm(Val));
2639   }
2640 
addMemThumbRIs2Operands(MCInst & Inst,unsigned N) const2641   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
2642     assert(N == 2 && "Invalid number of operands!");
2643     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
2644     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2645     Inst.addOperand(MCOperand::createImm(Val));
2646   }
2647 
addMemThumbRIs1Operands(MCInst & Inst,unsigned N) const2648   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
2649     assert(N == 2 && "Invalid number of operands!");
2650     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
2651     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2652     Inst.addOperand(MCOperand::createImm(Val));
2653   }
2654 
addMemThumbSPIOperands(MCInst & Inst,unsigned N) const2655   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
2656     assert(N == 2 && "Invalid number of operands!");
2657     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2658     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2659     Inst.addOperand(MCOperand::createImm(Val));
2660   }
2661 
addPostIdxImm8Operands(MCInst & Inst,unsigned N) const2662   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
2663     assert(N == 1 && "Invalid number of operands!");
2664     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2665     assert(CE && "non-constant post-idx-imm8 operand!");
2666     int Imm = CE->getValue();
2667     bool isAdd = Imm >= 0;
2668     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
2669     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
2670     Inst.addOperand(MCOperand::createImm(Imm));
2671   }
2672 
addPostIdxImm8s4Operands(MCInst & Inst,unsigned N) const2673   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
2674     assert(N == 1 && "Invalid number of operands!");
2675     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2676     assert(CE && "non-constant post-idx-imm8s4 operand!");
2677     int Imm = CE->getValue();
2678     bool isAdd = Imm >= 0;
2679     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
2680     // Immediate is scaled by 4.
2681     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
2682     Inst.addOperand(MCOperand::createImm(Imm));
2683   }
2684 
addPostIdxRegOperands(MCInst & Inst,unsigned N) const2685   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
2686     assert(N == 2 && "Invalid number of operands!");
2687     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2688     Inst.addOperand(MCOperand::createImm(PostIdxReg.isAdd));
2689   }
2690 
addPostIdxRegShiftedOperands(MCInst & Inst,unsigned N) const2691   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
2692     assert(N == 2 && "Invalid number of operands!");
2693     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2694     // The sign, shift type, and shift amount are encoded in a single operand
2695     // using the AM2 encoding helpers.
2696     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
2697     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
2698                                      PostIdxReg.ShiftTy);
2699     Inst.addOperand(MCOperand::createImm(Imm));
2700   }
2701 
addMSRMaskOperands(MCInst & Inst,unsigned N) const2702   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
2703     assert(N == 1 && "Invalid number of operands!");
2704     Inst.addOperand(MCOperand::createImm(unsigned(getMSRMask())));
2705   }
2706 
addBankedRegOperands(MCInst & Inst,unsigned N) const2707   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
2708     assert(N == 1 && "Invalid number of operands!");
2709     Inst.addOperand(MCOperand::createImm(unsigned(getBankedReg())));
2710   }
2711 
addProcIFlagsOperands(MCInst & Inst,unsigned N) const2712   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
2713     assert(N == 1 && "Invalid number of operands!");
2714     Inst.addOperand(MCOperand::createImm(unsigned(getProcIFlags())));
2715   }
2716 
addVecListOperands(MCInst & Inst,unsigned N) const2717   void addVecListOperands(MCInst &Inst, unsigned N) const {
2718     assert(N == 1 && "Invalid number of operands!");
2719     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2720   }
2721 
addVecListIndexedOperands(MCInst & Inst,unsigned N) const2722   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
2723     assert(N == 2 && "Invalid number of operands!");
2724     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2725     Inst.addOperand(MCOperand::createImm(VectorList.LaneIndex));
2726   }
2727 
addVectorIndex8Operands(MCInst & Inst,unsigned N) const2728   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
2729     assert(N == 1 && "Invalid number of operands!");
2730     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2731   }
2732 
addVectorIndex16Operands(MCInst & Inst,unsigned N) const2733   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
2734     assert(N == 1 && "Invalid number of operands!");
2735     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2736   }
2737 
addVectorIndex32Operands(MCInst & Inst,unsigned N) const2738   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
2739     assert(N == 1 && "Invalid number of operands!");
2740     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2741   }
2742 
addVectorIndex64Operands(MCInst & Inst,unsigned N) const2743   void addVectorIndex64Operands(MCInst &Inst, unsigned N) const {
2744     assert(N == 1 && "Invalid number of operands!");
2745     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2746   }
2747 
addNEONi8splatOperands(MCInst & Inst,unsigned N) const2748   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
2749     assert(N == 1 && "Invalid number of operands!");
2750     // The immediate encodes the type of constant as well as the value.
2751     // Mask in that this is an i8 splat.
2752     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2753     Inst.addOperand(MCOperand::createImm(CE->getValue() | 0xe00));
2754   }
2755 
addNEONi16splatOperands(MCInst & Inst,unsigned N) const2756   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
2757     assert(N == 1 && "Invalid number of operands!");
2758     // The immediate encodes the type of constant as well as the value.
2759     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2760     unsigned Value = CE->getValue();
2761     Value = ARM_AM::encodeNEONi16splat(Value);
2762     Inst.addOperand(MCOperand::createImm(Value));
2763   }
2764 
addNEONi16splatNotOperands(MCInst & Inst,unsigned N) const2765   void addNEONi16splatNotOperands(MCInst &Inst, unsigned N) const {
2766     assert(N == 1 && "Invalid number of operands!");
2767     // The immediate encodes the type of constant as well as the value.
2768     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2769     unsigned Value = CE->getValue();
2770     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
2771     Inst.addOperand(MCOperand::createImm(Value));
2772   }
2773 
addNEONi32splatOperands(MCInst & Inst,unsigned N) const2774   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
2775     assert(N == 1 && "Invalid number of operands!");
2776     // The immediate encodes the type of constant as well as the value.
2777     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2778     unsigned Value = CE->getValue();
2779     Value = ARM_AM::encodeNEONi32splat(Value);
2780     Inst.addOperand(MCOperand::createImm(Value));
2781   }
2782 
addNEONi32splatNotOperands(MCInst & Inst,unsigned N) const2783   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
2784     assert(N == 1 && "Invalid number of operands!");
2785     // The immediate encodes the type of constant as well as the value.
2786     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2787     unsigned Value = CE->getValue();
2788     Value = ARM_AM::encodeNEONi32splat(~Value);
2789     Inst.addOperand(MCOperand::createImm(Value));
2790   }
2791 
addNEONi8ReplicateOperands(MCInst & Inst,bool Inv) const2792   void addNEONi8ReplicateOperands(MCInst &Inst, bool Inv) const {
2793     // The immediate encodes the type of constant as well as the value.
2794     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2795     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2796             Inst.getOpcode() == ARM::VMOVv16i8) &&
2797           "All instructions that wants to replicate non-zero byte "
2798           "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2799     unsigned Value = CE->getValue();
2800     if (Inv)
2801       Value = ~Value;
2802     unsigned B = Value & 0xff;
2803     B |= 0xe00; // cmode = 0b1110
2804     Inst.addOperand(MCOperand::createImm(B));
2805   }
2806 
addNEONinvi8ReplicateOperands(MCInst & Inst,unsigned N) const2807   void addNEONinvi8ReplicateOperands(MCInst &Inst, unsigned N) const {
2808     assert(N == 1 && "Invalid number of operands!");
2809     addNEONi8ReplicateOperands(Inst, true);
2810   }
2811 
encodeNeonVMOVImmediate(unsigned Value)2812   static unsigned encodeNeonVMOVImmediate(unsigned Value) {
2813     if (Value >= 256 && Value <= 0xffff)
2814       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2815     else if (Value > 0xffff && Value <= 0xffffff)
2816       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2817     else if (Value > 0xffffff)
2818       Value = (Value >> 24) | 0x600;
2819     return Value;
2820   }
2821 
addNEONi32vmovOperands(MCInst & Inst,unsigned N) const2822   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
2823     assert(N == 1 && "Invalid number of operands!");
2824     // The immediate encodes the type of constant as well as the value.
2825     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2826     unsigned Value = encodeNeonVMOVImmediate(CE->getValue());
2827     Inst.addOperand(MCOperand::createImm(Value));
2828   }
2829 
addNEONvmovi8ReplicateOperands(MCInst & Inst,unsigned N) const2830   void addNEONvmovi8ReplicateOperands(MCInst &Inst, unsigned N) const {
2831     assert(N == 1 && "Invalid number of operands!");
2832     addNEONi8ReplicateOperands(Inst, false);
2833   }
2834 
addNEONvmovi16ReplicateOperands(MCInst & Inst,unsigned N) const2835   void addNEONvmovi16ReplicateOperands(MCInst &Inst, unsigned N) const {
2836     assert(N == 1 && "Invalid number of operands!");
2837     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2838     assert((Inst.getOpcode() == ARM::VMOVv4i16 ||
2839             Inst.getOpcode() == ARM::VMOVv8i16 ||
2840             Inst.getOpcode() == ARM::VMVNv4i16 ||
2841             Inst.getOpcode() == ARM::VMVNv8i16) &&
2842           "All instructions that want to replicate non-zero half-word "
2843           "always must be replaced with V{MOV,MVN}v{4,8}i16.");
2844     uint64_t Value = CE->getValue();
2845     unsigned Elem = Value & 0xffff;
2846     if (Elem >= 256)
2847       Elem = (Elem >> 8) | 0x200;
2848     Inst.addOperand(MCOperand::createImm(Elem));
2849   }
2850 
addNEONi32vmovNegOperands(MCInst & Inst,unsigned N) const2851   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
2852     assert(N == 1 && "Invalid number of operands!");
2853     // The immediate encodes the type of constant as well as the value.
2854     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2855     unsigned Value = encodeNeonVMOVImmediate(~CE->getValue());
2856     Inst.addOperand(MCOperand::createImm(Value));
2857   }
2858 
addNEONvmovi32ReplicateOperands(MCInst & Inst,unsigned N) const2859   void addNEONvmovi32ReplicateOperands(MCInst &Inst, unsigned N) const {
2860     assert(N == 1 && "Invalid number of operands!");
2861     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2862     assert((Inst.getOpcode() == ARM::VMOVv2i32 ||
2863             Inst.getOpcode() == ARM::VMOVv4i32 ||
2864             Inst.getOpcode() == ARM::VMVNv2i32 ||
2865             Inst.getOpcode() == ARM::VMVNv4i32) &&
2866           "All instructions that want to replicate non-zero word "
2867           "always must be replaced with V{MOV,MVN}v{2,4}i32.");
2868     uint64_t Value = CE->getValue();
2869     unsigned Elem = encodeNeonVMOVImmediate(Value & 0xffffffff);
2870     Inst.addOperand(MCOperand::createImm(Elem));
2871   }
2872 
addNEONi64splatOperands(MCInst & Inst,unsigned N) const2873   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
2874     assert(N == 1 && "Invalid number of operands!");
2875     // The immediate encodes the type of constant as well as the value.
2876     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2877     uint64_t Value = CE->getValue();
2878     unsigned Imm = 0;
2879     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
2880       Imm |= (Value & 1) << i;
2881     }
2882     Inst.addOperand(MCOperand::createImm(Imm | 0x1e00));
2883   }
2884 
addComplexRotationEvenOperands(MCInst & Inst,unsigned N) const2885   void addComplexRotationEvenOperands(MCInst &Inst, unsigned N) const {
2886     assert(N == 1 && "Invalid number of operands!");
2887     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2888     Inst.addOperand(MCOperand::createImm(CE->getValue() / 90));
2889   }
2890 
addComplexRotationOddOperands(MCInst & Inst,unsigned N) const2891   void addComplexRotationOddOperands(MCInst &Inst, unsigned N) const {
2892     assert(N == 1 && "Invalid number of operands!");
2893     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2894     Inst.addOperand(MCOperand::createImm((CE->getValue() - 90) / 180));
2895   }
2896 
2897   void print(raw_ostream &OS) const override;
2898 
CreateITMask(unsigned Mask,SMLoc S)2899   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
2900     auto Op = make_unique<ARMOperand>(k_ITCondMask);
2901     Op->ITMask.Mask = Mask;
2902     Op->StartLoc = S;
2903     Op->EndLoc = S;
2904     return Op;
2905   }
2906 
CreateCondCode(ARMCC::CondCodes CC,SMLoc S)2907   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
2908                                                     SMLoc S) {
2909     auto Op = make_unique<ARMOperand>(k_CondCode);
2910     Op->CC.Val = CC;
2911     Op->StartLoc = S;
2912     Op->EndLoc = S;
2913     return Op;
2914   }
2915 
CreateCoprocNum(unsigned CopVal,SMLoc S)2916   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
2917     auto Op = make_unique<ARMOperand>(k_CoprocNum);
2918     Op->Cop.Val = CopVal;
2919     Op->StartLoc = S;
2920     Op->EndLoc = S;
2921     return Op;
2922   }
2923 
CreateCoprocReg(unsigned CopVal,SMLoc S)2924   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
2925     auto Op = make_unique<ARMOperand>(k_CoprocReg);
2926     Op->Cop.Val = CopVal;
2927     Op->StartLoc = S;
2928     Op->EndLoc = S;
2929     return Op;
2930   }
2931 
CreateCoprocOption(unsigned Val,SMLoc S,SMLoc E)2932   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
2933                                                         SMLoc E) {
2934     auto Op = make_unique<ARMOperand>(k_CoprocOption);
2935     Op->Cop.Val = Val;
2936     Op->StartLoc = S;
2937     Op->EndLoc = E;
2938     return Op;
2939   }
2940 
CreateCCOut(unsigned RegNum,SMLoc S)2941   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
2942     auto Op = make_unique<ARMOperand>(k_CCOut);
2943     Op->Reg.RegNum = RegNum;
2944     Op->StartLoc = S;
2945     Op->EndLoc = S;
2946     return Op;
2947   }
2948 
CreateToken(StringRef Str,SMLoc S)2949   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
2950     auto Op = make_unique<ARMOperand>(k_Token);
2951     Op->Tok.Data = Str.data();
2952     Op->Tok.Length = Str.size();
2953     Op->StartLoc = S;
2954     Op->EndLoc = S;
2955     return Op;
2956   }
2957 
CreateReg(unsigned RegNum,SMLoc S,SMLoc E)2958   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
2959                                                SMLoc E) {
2960     auto Op = make_unique<ARMOperand>(k_Register);
2961     Op->Reg.RegNum = RegNum;
2962     Op->StartLoc = S;
2963     Op->EndLoc = E;
2964     return Op;
2965   }
2966 
2967   static std::unique_ptr<ARMOperand>
CreateShiftedRegister(ARM_AM::ShiftOpc ShTy,unsigned SrcReg,unsigned ShiftReg,unsigned ShiftImm,SMLoc S,SMLoc E)2968   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2969                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
2970                         SMLoc E) {
2971     auto Op = make_unique<ARMOperand>(k_ShiftedRegister);
2972     Op->RegShiftedReg.ShiftTy = ShTy;
2973     Op->RegShiftedReg.SrcReg = SrcReg;
2974     Op->RegShiftedReg.ShiftReg = ShiftReg;
2975     Op->RegShiftedReg.ShiftImm = ShiftImm;
2976     Op->StartLoc = S;
2977     Op->EndLoc = E;
2978     return Op;
2979   }
2980 
2981   static std::unique_ptr<ARMOperand>
CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy,unsigned SrcReg,unsigned ShiftImm,SMLoc S,SMLoc E)2982   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2983                          unsigned ShiftImm, SMLoc S, SMLoc E) {
2984     auto Op = make_unique<ARMOperand>(k_ShiftedImmediate);
2985     Op->RegShiftedImm.ShiftTy = ShTy;
2986     Op->RegShiftedImm.SrcReg = SrcReg;
2987     Op->RegShiftedImm.ShiftImm = ShiftImm;
2988     Op->StartLoc = S;
2989     Op->EndLoc = E;
2990     return Op;
2991   }
2992 
CreateShifterImm(bool isASR,unsigned Imm,SMLoc S,SMLoc E)2993   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
2994                                                       SMLoc S, SMLoc E) {
2995     auto Op = make_unique<ARMOperand>(k_ShifterImmediate);
2996     Op->ShifterImm.isASR = isASR;
2997     Op->ShifterImm.Imm = Imm;
2998     Op->StartLoc = S;
2999     Op->EndLoc = E;
3000     return Op;
3001   }
3002 
CreateRotImm(unsigned Imm,SMLoc S,SMLoc E)3003   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
3004                                                   SMLoc E) {
3005     auto Op = make_unique<ARMOperand>(k_RotateImmediate);
3006     Op->RotImm.Imm = Imm;
3007     Op->StartLoc = S;
3008     Op->EndLoc = E;
3009     return Op;
3010   }
3011 
CreateModImm(unsigned Bits,unsigned Rot,SMLoc S,SMLoc E)3012   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
3013                                                   SMLoc S, SMLoc E) {
3014     auto Op = make_unique<ARMOperand>(k_ModifiedImmediate);
3015     Op->ModImm.Bits = Bits;
3016     Op->ModImm.Rot = Rot;
3017     Op->StartLoc = S;
3018     Op->EndLoc = E;
3019     return Op;
3020   }
3021 
3022   static std::unique_ptr<ARMOperand>
CreateConstantPoolImm(const MCExpr * Val,SMLoc S,SMLoc E)3023   CreateConstantPoolImm(const MCExpr *Val, SMLoc S, SMLoc E) {
3024     auto Op = make_unique<ARMOperand>(k_ConstantPoolImmediate);
3025     Op->Imm.Val = Val;
3026     Op->StartLoc = S;
3027     Op->EndLoc = E;
3028     return Op;
3029   }
3030 
3031   static std::unique_ptr<ARMOperand>
CreateBitfield(unsigned LSB,unsigned Width,SMLoc S,SMLoc E)3032   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
3033     auto Op = make_unique<ARMOperand>(k_BitfieldDescriptor);
3034     Op->Bitfield.LSB = LSB;
3035     Op->Bitfield.Width = Width;
3036     Op->StartLoc = S;
3037     Op->EndLoc = E;
3038     return Op;
3039   }
3040 
3041   static std::unique_ptr<ARMOperand>
CreateRegList(SmallVectorImpl<std::pair<unsigned,unsigned>> & Regs,SMLoc StartLoc,SMLoc EndLoc)3042   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
3043                 SMLoc StartLoc, SMLoc EndLoc) {
3044     assert(Regs.size() > 0 && "RegList contains no registers?");
3045     KindTy Kind = k_RegisterList;
3046 
3047     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Regs.front().second))
3048       Kind = k_DPRRegisterList;
3049     else if (ARMMCRegisterClasses[ARM::SPRRegClassID].
3050              contains(Regs.front().second))
3051       Kind = k_SPRRegisterList;
3052 
3053     // Sort based on the register encoding values.
3054     array_pod_sort(Regs.begin(), Regs.end());
3055 
3056     auto Op = make_unique<ARMOperand>(Kind);
3057     for (SmallVectorImpl<std::pair<unsigned, unsigned>>::const_iterator
3058            I = Regs.begin(), E = Regs.end(); I != E; ++I)
3059       Op->Registers.push_back(I->second);
3060     Op->StartLoc = StartLoc;
3061     Op->EndLoc = EndLoc;
3062     return Op;
3063   }
3064 
CreateVectorList(unsigned RegNum,unsigned Count,bool isDoubleSpaced,SMLoc S,SMLoc E)3065   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
3066                                                       unsigned Count,
3067                                                       bool isDoubleSpaced,
3068                                                       SMLoc S, SMLoc E) {
3069     auto Op = make_unique<ARMOperand>(k_VectorList);
3070     Op->VectorList.RegNum = RegNum;
3071     Op->VectorList.Count = Count;
3072     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3073     Op->StartLoc = S;
3074     Op->EndLoc = E;
3075     return Op;
3076   }
3077 
3078   static std::unique_ptr<ARMOperand>
CreateVectorListAllLanes(unsigned RegNum,unsigned Count,bool isDoubleSpaced,SMLoc S,SMLoc E)3079   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
3080                            SMLoc S, SMLoc E) {
3081     auto Op = make_unique<ARMOperand>(k_VectorListAllLanes);
3082     Op->VectorList.RegNum = RegNum;
3083     Op->VectorList.Count = Count;
3084     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3085     Op->StartLoc = S;
3086     Op->EndLoc = E;
3087     return Op;
3088   }
3089 
3090   static std::unique_ptr<ARMOperand>
CreateVectorListIndexed(unsigned RegNum,unsigned Count,unsigned Index,bool isDoubleSpaced,SMLoc S,SMLoc E)3091   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
3092                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
3093     auto Op = make_unique<ARMOperand>(k_VectorListIndexed);
3094     Op->VectorList.RegNum = RegNum;
3095     Op->VectorList.Count = Count;
3096     Op->VectorList.LaneIndex = Index;
3097     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3098     Op->StartLoc = S;
3099     Op->EndLoc = E;
3100     return Op;
3101   }
3102 
3103   static std::unique_ptr<ARMOperand>
CreateVectorIndex(unsigned Idx,SMLoc S,SMLoc E,MCContext & Ctx)3104   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
3105     auto Op = make_unique<ARMOperand>(k_VectorIndex);
3106     Op->VectorIndex.Val = Idx;
3107     Op->StartLoc = S;
3108     Op->EndLoc = E;
3109     return Op;
3110   }
3111 
CreateImm(const MCExpr * Val,SMLoc S,SMLoc E)3112   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
3113                                                SMLoc E) {
3114     auto Op = make_unique<ARMOperand>(k_Immediate);
3115     Op->Imm.Val = Val;
3116     Op->StartLoc = S;
3117     Op->EndLoc = E;
3118     return Op;
3119   }
3120 
3121   static std::unique_ptr<ARMOperand>
CreateMem(unsigned BaseRegNum,const MCConstantExpr * OffsetImm,unsigned OffsetRegNum,ARM_AM::ShiftOpc ShiftType,unsigned ShiftImm,unsigned Alignment,bool isNegative,SMLoc S,SMLoc E,SMLoc AlignmentLoc=SMLoc ())3122   CreateMem(unsigned BaseRegNum, const MCConstantExpr *OffsetImm,
3123             unsigned OffsetRegNum, ARM_AM::ShiftOpc ShiftType,
3124             unsigned ShiftImm, unsigned Alignment, bool isNegative, SMLoc S,
3125             SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
3126     auto Op = make_unique<ARMOperand>(k_Memory);
3127     Op->Memory.BaseRegNum = BaseRegNum;
3128     Op->Memory.OffsetImm = OffsetImm;
3129     Op->Memory.OffsetRegNum = OffsetRegNum;
3130     Op->Memory.ShiftType = ShiftType;
3131     Op->Memory.ShiftImm = ShiftImm;
3132     Op->Memory.Alignment = Alignment;
3133     Op->Memory.isNegative = isNegative;
3134     Op->StartLoc = S;
3135     Op->EndLoc = E;
3136     Op->AlignmentLoc = AlignmentLoc;
3137     return Op;
3138   }
3139 
3140   static std::unique_ptr<ARMOperand>
CreatePostIdxReg(unsigned RegNum,bool isAdd,ARM_AM::ShiftOpc ShiftTy,unsigned ShiftImm,SMLoc S,SMLoc E)3141   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
3142                    unsigned ShiftImm, SMLoc S, SMLoc E) {
3143     auto Op = make_unique<ARMOperand>(k_PostIndexRegister);
3144     Op->PostIdxReg.RegNum = RegNum;
3145     Op->PostIdxReg.isAdd = isAdd;
3146     Op->PostIdxReg.ShiftTy = ShiftTy;
3147     Op->PostIdxReg.ShiftImm = ShiftImm;
3148     Op->StartLoc = S;
3149     Op->EndLoc = E;
3150     return Op;
3151   }
3152 
CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,SMLoc S)3153   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
3154                                                          SMLoc S) {
3155     auto Op = make_unique<ARMOperand>(k_MemBarrierOpt);
3156     Op->MBOpt.Val = Opt;
3157     Op->StartLoc = S;
3158     Op->EndLoc = S;
3159     return Op;
3160   }
3161 
3162   static std::unique_ptr<ARMOperand>
CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt,SMLoc S)3163   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
3164     auto Op = make_unique<ARMOperand>(k_InstSyncBarrierOpt);
3165     Op->ISBOpt.Val = Opt;
3166     Op->StartLoc = S;
3167     Op->EndLoc = S;
3168     return Op;
3169   }
3170 
3171   static std::unique_ptr<ARMOperand>
CreateTraceSyncBarrierOpt(ARM_TSB::TraceSyncBOpt Opt,SMLoc S)3172   CreateTraceSyncBarrierOpt(ARM_TSB::TraceSyncBOpt Opt, SMLoc S) {
3173     auto Op = make_unique<ARMOperand>(k_TraceSyncBarrierOpt);
3174     Op->TSBOpt.Val = Opt;
3175     Op->StartLoc = S;
3176     Op->EndLoc = S;
3177     return Op;
3178   }
3179 
CreateProcIFlags(ARM_PROC::IFlags IFlags,SMLoc S)3180   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
3181                                                       SMLoc S) {
3182     auto Op = make_unique<ARMOperand>(k_ProcIFlags);
3183     Op->IFlags.Val = IFlags;
3184     Op->StartLoc = S;
3185     Op->EndLoc = S;
3186     return Op;
3187   }
3188 
CreateMSRMask(unsigned MMask,SMLoc S)3189   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
3190     auto Op = make_unique<ARMOperand>(k_MSRMask);
3191     Op->MMask.Val = MMask;
3192     Op->StartLoc = S;
3193     Op->EndLoc = S;
3194     return Op;
3195   }
3196 
CreateBankedReg(unsigned Reg,SMLoc S)3197   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
3198     auto Op = make_unique<ARMOperand>(k_BankedReg);
3199     Op->BankedReg.Val = Reg;
3200     Op->StartLoc = S;
3201     Op->EndLoc = S;
3202     return Op;
3203   }
3204 };
3205 
3206 } // end anonymous namespace.
3207 
print(raw_ostream & OS) const3208 void ARMOperand::print(raw_ostream &OS) const {
3209   auto RegName = [](unsigned Reg) {
3210     if (Reg)
3211       return ARMInstPrinter::getRegisterName(Reg);
3212     else
3213       return "noreg";
3214   };
3215 
3216   switch (Kind) {
3217   case k_CondCode:
3218     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
3219     break;
3220   case k_CCOut:
3221     OS << "<ccout " << RegName(getReg()) << ">";
3222     break;
3223   case k_ITCondMask: {
3224     static const char *const MaskStr[] = {
3225       "(invalid)", "(teee)", "(tee)", "(teet)",
3226       "(te)",      "(tete)", "(tet)", "(tett)",
3227       "(t)",       "(ttee)", "(tte)", "(ttet)",
3228       "(tt)",      "(ttte)", "(ttt)", "(tttt)"
3229     };
3230     assert((ITMask.Mask & 0xf) == ITMask.Mask);
3231     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
3232     break;
3233   }
3234   case k_CoprocNum:
3235     OS << "<coprocessor number: " << getCoproc() << ">";
3236     break;
3237   case k_CoprocReg:
3238     OS << "<coprocessor register: " << getCoproc() << ">";
3239     break;
3240   case k_CoprocOption:
3241     OS << "<coprocessor option: " << CoprocOption.Val << ">";
3242     break;
3243   case k_MSRMask:
3244     OS << "<mask: " << getMSRMask() << ">";
3245     break;
3246   case k_BankedReg:
3247     OS << "<banked reg: " << getBankedReg() << ">";
3248     break;
3249   case k_Immediate:
3250     OS << *getImm();
3251     break;
3252   case k_MemBarrierOpt:
3253     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
3254     break;
3255   case k_InstSyncBarrierOpt:
3256     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
3257     break;
3258   case k_TraceSyncBarrierOpt:
3259     OS << "<ARM_TSB::" << TraceSyncBOptToString(getTraceSyncBarrierOpt()) << ">";
3260     break;
3261   case k_Memory:
3262     OS << "<memory";
3263     if (Memory.BaseRegNum)
3264       OS << " base:" << RegName(Memory.BaseRegNum);
3265     if (Memory.OffsetImm)
3266       OS << " offset-imm:" << *Memory.OffsetImm;
3267     if (Memory.OffsetRegNum)
3268       OS << " offset-reg:" << (Memory.isNegative ? "-" : "")
3269          << RegName(Memory.OffsetRegNum);
3270     if (Memory.ShiftType != ARM_AM::no_shift) {
3271       OS << " shift-type:" << ARM_AM::getShiftOpcStr(Memory.ShiftType);
3272       OS << " shift-imm:" << Memory.ShiftImm;
3273     }
3274     if (Memory.Alignment)
3275       OS << " alignment:" << Memory.Alignment;
3276     OS << ">";
3277     break;
3278   case k_PostIndexRegister:
3279     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
3280        << RegName(PostIdxReg.RegNum);
3281     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
3282       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
3283          << PostIdxReg.ShiftImm;
3284     OS << ">";
3285     break;
3286   case k_ProcIFlags: {
3287     OS << "<ARM_PROC::";
3288     unsigned IFlags = getProcIFlags();
3289     for (int i=2; i >= 0; --i)
3290       if (IFlags & (1 << i))
3291         OS << ARM_PROC::IFlagsToString(1 << i);
3292     OS << ">";
3293     break;
3294   }
3295   case k_Register:
3296     OS << "<register " << RegName(getReg()) << ">";
3297     break;
3298   case k_ShifterImmediate:
3299     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
3300        << " #" << ShifterImm.Imm << ">";
3301     break;
3302   case k_ShiftedRegister:
3303     OS << "<so_reg_reg " << RegName(RegShiftedReg.SrcReg) << " "
3304        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy) << " "
3305        << RegName(RegShiftedReg.ShiftReg) << ">";
3306     break;
3307   case k_ShiftedImmediate:
3308     OS << "<so_reg_imm " << RegName(RegShiftedImm.SrcReg) << " "
3309        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy) << " #"
3310        << RegShiftedImm.ShiftImm << ">";
3311     break;
3312   case k_RotateImmediate:
3313     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
3314     break;
3315   case k_ModifiedImmediate:
3316     OS << "<mod_imm #" << ModImm.Bits << ", #"
3317        <<  ModImm.Rot << ")>";
3318     break;
3319   case k_ConstantPoolImmediate:
3320     OS << "<constant_pool_imm #" << *getConstantPoolImm();
3321     break;
3322   case k_BitfieldDescriptor:
3323     OS << "<bitfield " << "lsb: " << Bitfield.LSB
3324        << ", width: " << Bitfield.Width << ">";
3325     break;
3326   case k_RegisterList:
3327   case k_DPRRegisterList:
3328   case k_SPRRegisterList: {
3329     OS << "<register_list ";
3330 
3331     const SmallVectorImpl<unsigned> &RegList = getRegList();
3332     for (SmallVectorImpl<unsigned>::const_iterator
3333            I = RegList.begin(), E = RegList.end(); I != E; ) {
3334       OS << RegName(*I);
3335       if (++I < E) OS << ", ";
3336     }
3337 
3338     OS << ">";
3339     break;
3340   }
3341   case k_VectorList:
3342     OS << "<vector_list " << VectorList.Count << " * "
3343        << RegName(VectorList.RegNum) << ">";
3344     break;
3345   case k_VectorListAllLanes:
3346     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
3347        << RegName(VectorList.RegNum) << ">";
3348     break;
3349   case k_VectorListIndexed:
3350     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
3351        << VectorList.Count << " * " << RegName(VectorList.RegNum) << ">";
3352     break;
3353   case k_Token:
3354     OS << "'" << getToken() << "'";
3355     break;
3356   case k_VectorIndex:
3357     OS << "<vectorindex " << getVectorIndex() << ">";
3358     break;
3359   }
3360 }
3361 
3362 /// @name Auto-generated Match Functions
3363 /// {
3364 
3365 static unsigned MatchRegisterName(StringRef Name);
3366 
3367 /// }
3368 
ParseRegister(unsigned & RegNo,SMLoc & StartLoc,SMLoc & EndLoc)3369 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
3370                                  SMLoc &StartLoc, SMLoc &EndLoc) {
3371   const AsmToken &Tok = getParser().getTok();
3372   StartLoc = Tok.getLoc();
3373   EndLoc = Tok.getEndLoc();
3374   RegNo = tryParseRegister();
3375 
3376   return (RegNo == (unsigned)-1);
3377 }
3378 
3379 /// Try to parse a register name.  The token must be an Identifier when called,
3380 /// and if it is a register name the token is eaten and the register number is
3381 /// returned.  Otherwise return -1.
tryParseRegister()3382 int ARMAsmParser::tryParseRegister() {
3383   MCAsmParser &Parser = getParser();
3384   const AsmToken &Tok = Parser.getTok();
3385   if (Tok.isNot(AsmToken::Identifier)) return -1;
3386 
3387   std::string lowerCase = Tok.getString().lower();
3388   unsigned RegNum = MatchRegisterName(lowerCase);
3389   if (!RegNum) {
3390     RegNum = StringSwitch<unsigned>(lowerCase)
3391       .Case("r13", ARM::SP)
3392       .Case("r14", ARM::LR)
3393       .Case("r15", ARM::PC)
3394       .Case("ip", ARM::R12)
3395       // Additional register name aliases for 'gas' compatibility.
3396       .Case("a1", ARM::R0)
3397       .Case("a2", ARM::R1)
3398       .Case("a3", ARM::R2)
3399       .Case("a4", ARM::R3)
3400       .Case("v1", ARM::R4)
3401       .Case("v2", ARM::R5)
3402       .Case("v3", ARM::R6)
3403       .Case("v4", ARM::R7)
3404       .Case("v5", ARM::R8)
3405       .Case("v6", ARM::R9)
3406       .Case("v7", ARM::R10)
3407       .Case("v8", ARM::R11)
3408       .Case("sb", ARM::R9)
3409       .Case("sl", ARM::R10)
3410       .Case("fp", ARM::R11)
3411       .Default(0);
3412   }
3413   if (!RegNum) {
3414     // Check for aliases registered via .req. Canonicalize to lower case.
3415     // That's more consistent since register names are case insensitive, and
3416     // it's how the original entry was passed in from MC/MCParser/AsmParser.
3417     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
3418     // If no match, return failure.
3419     if (Entry == RegisterReqs.end())
3420       return -1;
3421     Parser.Lex(); // Eat identifier token.
3422     return Entry->getValue();
3423   }
3424 
3425   // Some FPUs only have 16 D registers, so D16-D31 are invalid
3426   if (hasD16() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
3427     return -1;
3428 
3429   Parser.Lex(); // Eat identifier token.
3430 
3431   return RegNum;
3432 }
3433 
3434 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
3435 // If a recoverable error occurs, return 1. If an irrecoverable error
3436 // occurs, return -1. An irrecoverable error is one where tokens have been
3437 // consumed in the process of trying to parse the shifter (i.e., when it is
3438 // indeed a shifter operand, but malformed).
tryParseShiftRegister(OperandVector & Operands)3439 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
3440   MCAsmParser &Parser = getParser();
3441   SMLoc S = Parser.getTok().getLoc();
3442   const AsmToken &Tok = Parser.getTok();
3443   if (Tok.isNot(AsmToken::Identifier))
3444     return -1;
3445 
3446   std::string lowerCase = Tok.getString().lower();
3447   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
3448       .Case("asl", ARM_AM::lsl)
3449       .Case("lsl", ARM_AM::lsl)
3450       .Case("lsr", ARM_AM::lsr)
3451       .Case("asr", ARM_AM::asr)
3452       .Case("ror", ARM_AM::ror)
3453       .Case("rrx", ARM_AM::rrx)
3454       .Default(ARM_AM::no_shift);
3455 
3456   if (ShiftTy == ARM_AM::no_shift)
3457     return 1;
3458 
3459   Parser.Lex(); // Eat the operator.
3460 
3461   // The source register for the shift has already been added to the
3462   // operand list, so we need to pop it off and combine it into the shifted
3463   // register operand instead.
3464   std::unique_ptr<ARMOperand> PrevOp(
3465       (ARMOperand *)Operands.pop_back_val().release());
3466   if (!PrevOp->isReg())
3467     return Error(PrevOp->getStartLoc(), "shift must be of a register");
3468   int SrcReg = PrevOp->getReg();
3469 
3470   SMLoc EndLoc;
3471   int64_t Imm = 0;
3472   int ShiftReg = 0;
3473   if (ShiftTy == ARM_AM::rrx) {
3474     // RRX Doesn't have an explicit shift amount. The encoder expects
3475     // the shift register to be the same as the source register. Seems odd,
3476     // but OK.
3477     ShiftReg = SrcReg;
3478   } else {
3479     // Figure out if this is shifted by a constant or a register (for non-RRX).
3480     if (Parser.getTok().is(AsmToken::Hash) ||
3481         Parser.getTok().is(AsmToken::Dollar)) {
3482       Parser.Lex(); // Eat hash.
3483       SMLoc ImmLoc = Parser.getTok().getLoc();
3484       const MCExpr *ShiftExpr = nullptr;
3485       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
3486         Error(ImmLoc, "invalid immediate shift value");
3487         return -1;
3488       }
3489       // The expression must be evaluatable as an immediate.
3490       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
3491       if (!CE) {
3492         Error(ImmLoc, "invalid immediate shift value");
3493         return -1;
3494       }
3495       // Range check the immediate.
3496       // lsl, ror: 0 <= imm <= 31
3497       // lsr, asr: 0 <= imm <= 32
3498       Imm = CE->getValue();
3499       if (Imm < 0 ||
3500           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
3501           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
3502         Error(ImmLoc, "immediate shift value out of range");
3503         return -1;
3504       }
3505       // shift by zero is a nop. Always send it through as lsl.
3506       // ('as' compatibility)
3507       if (Imm == 0)
3508         ShiftTy = ARM_AM::lsl;
3509     } else if (Parser.getTok().is(AsmToken::Identifier)) {
3510       SMLoc L = Parser.getTok().getLoc();
3511       EndLoc = Parser.getTok().getEndLoc();
3512       ShiftReg = tryParseRegister();
3513       if (ShiftReg == -1) {
3514         Error(L, "expected immediate or register in shift operand");
3515         return -1;
3516       }
3517     } else {
3518       Error(Parser.getTok().getLoc(),
3519             "expected immediate or register in shift operand");
3520       return -1;
3521     }
3522   }
3523 
3524   if (ShiftReg && ShiftTy != ARM_AM::rrx)
3525     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
3526                                                          ShiftReg, Imm,
3527                                                          S, EndLoc));
3528   else
3529     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
3530                                                           S, EndLoc));
3531 
3532   return 0;
3533 }
3534 
3535 /// Try to parse a register name.  The token must be an Identifier when called.
3536 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
3537 /// if there is a "writeback". 'true' if it's not a register.
3538 ///
3539 /// TODO this is likely to change to allow different register types and or to
3540 /// parse for a specific register type.
tryParseRegisterWithWriteBack(OperandVector & Operands)3541 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
3542   MCAsmParser &Parser = getParser();
3543   SMLoc RegStartLoc = Parser.getTok().getLoc();
3544   SMLoc RegEndLoc = Parser.getTok().getEndLoc();
3545   int RegNo = tryParseRegister();
3546   if (RegNo == -1)
3547     return true;
3548 
3549   Operands.push_back(ARMOperand::CreateReg(RegNo, RegStartLoc, RegEndLoc));
3550 
3551   const AsmToken &ExclaimTok = Parser.getTok();
3552   if (ExclaimTok.is(AsmToken::Exclaim)) {
3553     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
3554                                                ExclaimTok.getLoc()));
3555     Parser.Lex(); // Eat exclaim token
3556     return false;
3557   }
3558 
3559   // Also check for an index operand. This is only legal for vector registers,
3560   // but that'll get caught OK in operand matching, so we don't need to
3561   // explicitly filter everything else out here.
3562   if (Parser.getTok().is(AsmToken::LBrac)) {
3563     SMLoc SIdx = Parser.getTok().getLoc();
3564     Parser.Lex(); // Eat left bracket token.
3565 
3566     const MCExpr *ImmVal;
3567     if (getParser().parseExpression(ImmVal))
3568       return true;
3569     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
3570     if (!MCE)
3571       return TokError("immediate value expected for vector index");
3572 
3573     if (Parser.getTok().isNot(AsmToken::RBrac))
3574       return Error(Parser.getTok().getLoc(), "']' expected");
3575 
3576     SMLoc E = Parser.getTok().getEndLoc();
3577     Parser.Lex(); // Eat right bracket token.
3578 
3579     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
3580                                                      SIdx, E,
3581                                                      getContext()));
3582   }
3583 
3584   return false;
3585 }
3586 
3587 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
3588 /// instruction with a symbolic operand name.
3589 /// We accept "crN" syntax for GAS compatibility.
3590 /// <operand-name> ::= <prefix><number>
3591 /// If CoprocOp is 'c', then:
3592 ///   <prefix> ::= c | cr
3593 /// If CoprocOp is 'p', then :
3594 ///   <prefix> ::= p
3595 /// <number> ::= integer in range [0, 15]
MatchCoprocessorOperandName(StringRef Name,char CoprocOp)3596 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
3597   // Use the same layout as the tablegen'erated register name matcher. Ugly,
3598   // but efficient.
3599   if (Name.size() < 2 || Name[0] != CoprocOp)
3600     return -1;
3601   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
3602 
3603   switch (Name.size()) {
3604   default: return -1;
3605   case 1:
3606     switch (Name[0]) {
3607     default:  return -1;
3608     case '0': return 0;
3609     case '1': return 1;
3610     case '2': return 2;
3611     case '3': return 3;
3612     case '4': return 4;
3613     case '5': return 5;
3614     case '6': return 6;
3615     case '7': return 7;
3616     case '8': return 8;
3617     case '9': return 9;
3618     }
3619   case 2:
3620     if (Name[0] != '1')
3621       return -1;
3622     switch (Name[1]) {
3623     default:  return -1;
3624     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
3625     // However, old cores (v5/v6) did use them in that way.
3626     case '0': return 10;
3627     case '1': return 11;
3628     case '2': return 12;
3629     case '3': return 13;
3630     case '4': return 14;
3631     case '5': return 15;
3632     }
3633   }
3634 }
3635 
3636 /// parseITCondCode - Try to parse a condition code for an IT instruction.
3637 OperandMatchResultTy
parseITCondCode(OperandVector & Operands)3638 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
3639   MCAsmParser &Parser = getParser();
3640   SMLoc S = Parser.getTok().getLoc();
3641   const AsmToken &Tok = Parser.getTok();
3642   if (!Tok.is(AsmToken::Identifier))
3643     return MatchOperand_NoMatch;
3644   unsigned CC = ARMCondCodeFromString(Tok.getString());
3645   if (CC == ~0U)
3646     return MatchOperand_NoMatch;
3647   Parser.Lex(); // Eat the token.
3648 
3649   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
3650 
3651   return MatchOperand_Success;
3652 }
3653 
3654 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
3655 /// token must be an Identifier when called, and if it is a coprocessor
3656 /// number, the token is eaten and the operand is added to the operand list.
3657 OperandMatchResultTy
parseCoprocNumOperand(OperandVector & Operands)3658 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
3659   MCAsmParser &Parser = getParser();
3660   SMLoc S = Parser.getTok().getLoc();
3661   const AsmToken &Tok = Parser.getTok();
3662   if (Tok.isNot(AsmToken::Identifier))
3663     return MatchOperand_NoMatch;
3664 
3665   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
3666   if (Num == -1)
3667     return MatchOperand_NoMatch;
3668   // ARMv7 and v8 don't allow cp10/cp11 due to VFP/NEON specific instructions
3669   if ((hasV7Ops() || hasV8Ops()) && (Num == 10 || Num == 11))
3670     return MatchOperand_NoMatch;
3671 
3672   Parser.Lex(); // Eat identifier token.
3673   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
3674   return MatchOperand_Success;
3675 }
3676 
3677 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
3678 /// token must be an Identifier when called, and if it is a coprocessor
3679 /// number, the token is eaten and the operand is added to the operand list.
3680 OperandMatchResultTy
parseCoprocRegOperand(OperandVector & Operands)3681 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
3682   MCAsmParser &Parser = getParser();
3683   SMLoc S = Parser.getTok().getLoc();
3684   const AsmToken &Tok = Parser.getTok();
3685   if (Tok.isNot(AsmToken::Identifier))
3686     return MatchOperand_NoMatch;
3687 
3688   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
3689   if (Reg == -1)
3690     return MatchOperand_NoMatch;
3691 
3692   Parser.Lex(); // Eat identifier token.
3693   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
3694   return MatchOperand_Success;
3695 }
3696 
3697 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
3698 /// coproc_option : '{' imm0_255 '}'
3699 OperandMatchResultTy
parseCoprocOptionOperand(OperandVector & Operands)3700 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
3701   MCAsmParser &Parser = getParser();
3702   SMLoc S = Parser.getTok().getLoc();
3703 
3704   // If this isn't a '{', this isn't a coprocessor immediate operand.
3705   if (Parser.getTok().isNot(AsmToken::LCurly))
3706     return MatchOperand_NoMatch;
3707   Parser.Lex(); // Eat the '{'
3708 
3709   const MCExpr *Expr;
3710   SMLoc Loc = Parser.getTok().getLoc();
3711   if (getParser().parseExpression(Expr)) {
3712     Error(Loc, "illegal expression");
3713     return MatchOperand_ParseFail;
3714   }
3715   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
3716   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
3717     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
3718     return MatchOperand_ParseFail;
3719   }
3720   int Val = CE->getValue();
3721 
3722   // Check for and consume the closing '}'
3723   if (Parser.getTok().isNot(AsmToken::RCurly))
3724     return MatchOperand_ParseFail;
3725   SMLoc E = Parser.getTok().getEndLoc();
3726   Parser.Lex(); // Eat the '}'
3727 
3728   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
3729   return MatchOperand_Success;
3730 }
3731 
3732 // For register list parsing, we need to map from raw GPR register numbering
3733 // to the enumeration values. The enumeration values aren't sorted by
3734 // register number due to our using "sp", "lr" and "pc" as canonical names.
getNextRegister(unsigned Reg)3735 static unsigned getNextRegister(unsigned Reg) {
3736   // If this is a GPR, we need to do it manually, otherwise we can rely
3737   // on the sort ordering of the enumeration since the other reg-classes
3738   // are sane.
3739   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3740     return Reg + 1;
3741   switch(Reg) {
3742   default: llvm_unreachable("Invalid GPR number!");
3743   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
3744   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
3745   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
3746   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
3747   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
3748   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
3749   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
3750   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
3751   }
3752 }
3753 
3754 /// Parse a register list.
parseRegisterList(OperandVector & Operands)3755 bool ARMAsmParser::parseRegisterList(OperandVector &Operands) {
3756   MCAsmParser &Parser = getParser();
3757   if (Parser.getTok().isNot(AsmToken::LCurly))
3758     return TokError("Token is not a Left Curly Brace");
3759   SMLoc S = Parser.getTok().getLoc();
3760   Parser.Lex(); // Eat '{' token.
3761   SMLoc RegLoc = Parser.getTok().getLoc();
3762 
3763   // Check the first register in the list to see what register class
3764   // this is a list of.
3765   int Reg = tryParseRegister();
3766   if (Reg == -1)
3767     return Error(RegLoc, "register expected");
3768 
3769   // The reglist instructions have at most 16 registers, so reserve
3770   // space for that many.
3771   int EReg = 0;
3772   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
3773 
3774   // Allow Q regs and just interpret them as the two D sub-registers.
3775   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3776     Reg = getDRegFromQReg(Reg);
3777     EReg = MRI->getEncodingValue(Reg);
3778     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3779     ++Reg;
3780   }
3781   const MCRegisterClass *RC;
3782   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3783     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
3784   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
3785     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
3786   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
3787     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
3788   else
3789     return Error(RegLoc, "invalid register in register list");
3790 
3791   // Store the register.
3792   EReg = MRI->getEncodingValue(Reg);
3793   Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3794 
3795   // This starts immediately after the first register token in the list,
3796   // so we can see either a comma or a minus (range separator) as a legal
3797   // next token.
3798   while (Parser.getTok().is(AsmToken::Comma) ||
3799          Parser.getTok().is(AsmToken::Minus)) {
3800     if (Parser.getTok().is(AsmToken::Minus)) {
3801       Parser.Lex(); // Eat the minus.
3802       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3803       int EndReg = tryParseRegister();
3804       if (EndReg == -1)
3805         return Error(AfterMinusLoc, "register expected");
3806       // Allow Q regs and just interpret them as the two D sub-registers.
3807       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3808         EndReg = getDRegFromQReg(EndReg) + 1;
3809       // If the register is the same as the start reg, there's nothing
3810       // more to do.
3811       if (Reg == EndReg)
3812         continue;
3813       // The register must be in the same register class as the first.
3814       if (!RC->contains(EndReg))
3815         return Error(AfterMinusLoc, "invalid register in register list");
3816       // Ranges must go from low to high.
3817       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
3818         return Error(AfterMinusLoc, "bad range in register list");
3819 
3820       // Add all the registers in the range to the register list.
3821       while (Reg != EndReg) {
3822         Reg = getNextRegister(Reg);
3823         EReg = MRI->getEncodingValue(Reg);
3824         Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3825       }
3826       continue;
3827     }
3828     Parser.Lex(); // Eat the comma.
3829     RegLoc = Parser.getTok().getLoc();
3830     int OldReg = Reg;
3831     const AsmToken RegTok = Parser.getTok();
3832     Reg = tryParseRegister();
3833     if (Reg == -1)
3834       return Error(RegLoc, "register expected");
3835     // Allow Q regs and just interpret them as the two D sub-registers.
3836     bool isQReg = false;
3837     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3838       Reg = getDRegFromQReg(Reg);
3839       isQReg = true;
3840     }
3841     // The register must be in the same register class as the first.
3842     if (!RC->contains(Reg))
3843       return Error(RegLoc, "invalid register in register list");
3844     // List must be monotonically increasing.
3845     if (MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
3846       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3847         Warning(RegLoc, "register list not in ascending order");
3848       else
3849         return Error(RegLoc, "register list not in ascending order");
3850     }
3851     if (MRI->getEncodingValue(Reg) == MRI->getEncodingValue(OldReg)) {
3852       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
3853               ") in register list");
3854       continue;
3855     }
3856     // VFP register lists must also be contiguous.
3857     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
3858         Reg != OldReg + 1)
3859       return Error(RegLoc, "non-contiguous register range");
3860     EReg = MRI->getEncodingValue(Reg);
3861     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3862     if (isQReg) {
3863       EReg = MRI->getEncodingValue(++Reg);
3864       Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3865     }
3866   }
3867 
3868   if (Parser.getTok().isNot(AsmToken::RCurly))
3869     return Error(Parser.getTok().getLoc(), "'}' expected");
3870   SMLoc E = Parser.getTok().getEndLoc();
3871   Parser.Lex(); // Eat '}' token.
3872 
3873   // Push the register list operand.
3874   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
3875 
3876   // The ARM system instruction variants for LDM/STM have a '^' token here.
3877   if (Parser.getTok().is(AsmToken::Caret)) {
3878     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
3879     Parser.Lex(); // Eat '^' token.
3880   }
3881 
3882   return false;
3883 }
3884 
3885 // Helper function to parse the lane index for vector lists.
3886 OperandMatchResultTy ARMAsmParser::
parseVectorLane(VectorLaneTy & LaneKind,unsigned & Index,SMLoc & EndLoc)3887 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
3888   MCAsmParser &Parser = getParser();
3889   Index = 0; // Always return a defined index value.
3890   if (Parser.getTok().is(AsmToken::LBrac)) {
3891     Parser.Lex(); // Eat the '['.
3892     if (Parser.getTok().is(AsmToken::RBrac)) {
3893       // "Dn[]" is the 'all lanes' syntax.
3894       LaneKind = AllLanes;
3895       EndLoc = Parser.getTok().getEndLoc();
3896       Parser.Lex(); // Eat the ']'.
3897       return MatchOperand_Success;
3898     }
3899 
3900     // There's an optional '#' token here. Normally there wouldn't be, but
3901     // inline assemble puts one in, and it's friendly to accept that.
3902     if (Parser.getTok().is(AsmToken::Hash))
3903       Parser.Lex(); // Eat '#' or '$'.
3904 
3905     const MCExpr *LaneIndex;
3906     SMLoc Loc = Parser.getTok().getLoc();
3907     if (getParser().parseExpression(LaneIndex)) {
3908       Error(Loc, "illegal expression");
3909       return MatchOperand_ParseFail;
3910     }
3911     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
3912     if (!CE) {
3913       Error(Loc, "lane index must be empty or an integer");
3914       return MatchOperand_ParseFail;
3915     }
3916     if (Parser.getTok().isNot(AsmToken::RBrac)) {
3917       Error(Parser.getTok().getLoc(), "']' expected");
3918       return MatchOperand_ParseFail;
3919     }
3920     EndLoc = Parser.getTok().getEndLoc();
3921     Parser.Lex(); // Eat the ']'.
3922     int64_t Val = CE->getValue();
3923 
3924     // FIXME: Make this range check context sensitive for .8, .16, .32.
3925     if (Val < 0 || Val > 7) {
3926       Error(Parser.getTok().getLoc(), "lane index out of range");
3927       return MatchOperand_ParseFail;
3928     }
3929     Index = Val;
3930     LaneKind = IndexedLane;
3931     return MatchOperand_Success;
3932   }
3933   LaneKind = NoLanes;
3934   return MatchOperand_Success;
3935 }
3936 
3937 // parse a vector register list
3938 OperandMatchResultTy
parseVectorList(OperandVector & Operands)3939 ARMAsmParser::parseVectorList(OperandVector &Operands) {
3940   MCAsmParser &Parser = getParser();
3941   VectorLaneTy LaneKind;
3942   unsigned LaneIndex;
3943   SMLoc S = Parser.getTok().getLoc();
3944   // As an extension (to match gas), support a plain D register or Q register
3945   // (without encosing curly braces) as a single or double entry list,
3946   // respectively.
3947   if (Parser.getTok().is(AsmToken::Identifier)) {
3948     SMLoc E = Parser.getTok().getEndLoc();
3949     int Reg = tryParseRegister();
3950     if (Reg == -1)
3951       return MatchOperand_NoMatch;
3952     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
3953       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3954       if (Res != MatchOperand_Success)
3955         return Res;
3956       switch (LaneKind) {
3957       case NoLanes:
3958         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
3959         break;
3960       case AllLanes:
3961         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
3962                                                                 S, E));
3963         break;
3964       case IndexedLane:
3965         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
3966                                                                LaneIndex,
3967                                                                false, S, E));
3968         break;
3969       }
3970       return MatchOperand_Success;
3971     }
3972     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3973       Reg = getDRegFromQReg(Reg);
3974       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3975       if (Res != MatchOperand_Success)
3976         return Res;
3977       switch (LaneKind) {
3978       case NoLanes:
3979         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3980                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3981         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
3982         break;
3983       case AllLanes:
3984         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3985                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3986         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
3987                                                                 S, E));
3988         break;
3989       case IndexedLane:
3990         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
3991                                                                LaneIndex,
3992                                                                false, S, E));
3993         break;
3994       }
3995       return MatchOperand_Success;
3996     }
3997     Error(S, "vector register expected");
3998     return MatchOperand_ParseFail;
3999   }
4000 
4001   if (Parser.getTok().isNot(AsmToken::LCurly))
4002     return MatchOperand_NoMatch;
4003 
4004   Parser.Lex(); // Eat '{' token.
4005   SMLoc RegLoc = Parser.getTok().getLoc();
4006 
4007   int Reg = tryParseRegister();
4008   if (Reg == -1) {
4009     Error(RegLoc, "register expected");
4010     return MatchOperand_ParseFail;
4011   }
4012   unsigned Count = 1;
4013   int Spacing = 0;
4014   unsigned FirstReg = Reg;
4015   // The list is of D registers, but we also allow Q regs and just interpret
4016   // them as the two D sub-registers.
4017   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4018     FirstReg = Reg = getDRegFromQReg(Reg);
4019     Spacing = 1; // double-spacing requires explicit D registers, otherwise
4020                  // it's ambiguous with four-register single spaced.
4021     ++Reg;
4022     ++Count;
4023   }
4024 
4025   SMLoc E;
4026   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
4027     return MatchOperand_ParseFail;
4028 
4029   while (Parser.getTok().is(AsmToken::Comma) ||
4030          Parser.getTok().is(AsmToken::Minus)) {
4031     if (Parser.getTok().is(AsmToken::Minus)) {
4032       if (!Spacing)
4033         Spacing = 1; // Register range implies a single spaced list.
4034       else if (Spacing == 2) {
4035         Error(Parser.getTok().getLoc(),
4036               "sequential registers in double spaced list");
4037         return MatchOperand_ParseFail;
4038       }
4039       Parser.Lex(); // Eat the minus.
4040       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
4041       int EndReg = tryParseRegister();
4042       if (EndReg == -1) {
4043         Error(AfterMinusLoc, "register expected");
4044         return MatchOperand_ParseFail;
4045       }
4046       // Allow Q regs and just interpret them as the two D sub-registers.
4047       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
4048         EndReg = getDRegFromQReg(EndReg) + 1;
4049       // If the register is the same as the start reg, there's nothing
4050       // more to do.
4051       if (Reg == EndReg)
4052         continue;
4053       // The register must be in the same register class as the first.
4054       if (!ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg)) {
4055         Error(AfterMinusLoc, "invalid register in register list");
4056         return MatchOperand_ParseFail;
4057       }
4058       // Ranges must go from low to high.
4059       if (Reg > EndReg) {
4060         Error(AfterMinusLoc, "bad range in register list");
4061         return MatchOperand_ParseFail;
4062       }
4063       // Parse the lane specifier if present.
4064       VectorLaneTy NextLaneKind;
4065       unsigned NextLaneIndex;
4066       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
4067           MatchOperand_Success)
4068         return MatchOperand_ParseFail;
4069       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4070         Error(AfterMinusLoc, "mismatched lane index in register list");
4071         return MatchOperand_ParseFail;
4072       }
4073 
4074       // Add all the registers in the range to the register list.
4075       Count += EndReg - Reg;
4076       Reg = EndReg;
4077       continue;
4078     }
4079     Parser.Lex(); // Eat the comma.
4080     RegLoc = Parser.getTok().getLoc();
4081     int OldReg = Reg;
4082     Reg = tryParseRegister();
4083     if (Reg == -1) {
4084       Error(RegLoc, "register expected");
4085       return MatchOperand_ParseFail;
4086     }
4087     // vector register lists must be contiguous.
4088     // It's OK to use the enumeration values directly here rather, as the
4089     // VFP register classes have the enum sorted properly.
4090     //
4091     // The list is of D registers, but we also allow Q regs and just interpret
4092     // them as the two D sub-registers.
4093     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4094       if (!Spacing)
4095         Spacing = 1; // Register range implies a single spaced list.
4096       else if (Spacing == 2) {
4097         Error(RegLoc,
4098               "invalid register in double-spaced list (must be 'D' register')");
4099         return MatchOperand_ParseFail;
4100       }
4101       Reg = getDRegFromQReg(Reg);
4102       if (Reg != OldReg + 1) {
4103         Error(RegLoc, "non-contiguous register range");
4104         return MatchOperand_ParseFail;
4105       }
4106       ++Reg;
4107       Count += 2;
4108       // Parse the lane specifier if present.
4109       VectorLaneTy NextLaneKind;
4110       unsigned NextLaneIndex;
4111       SMLoc LaneLoc = Parser.getTok().getLoc();
4112       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
4113           MatchOperand_Success)
4114         return MatchOperand_ParseFail;
4115       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4116         Error(LaneLoc, "mismatched lane index in register list");
4117         return MatchOperand_ParseFail;
4118       }
4119       continue;
4120     }
4121     // Normal D register.
4122     // Figure out the register spacing (single or double) of the list if
4123     // we don't know it already.
4124     if (!Spacing)
4125       Spacing = 1 + (Reg == OldReg + 2);
4126 
4127     // Just check that it's contiguous and keep going.
4128     if (Reg != OldReg + Spacing) {
4129       Error(RegLoc, "non-contiguous register range");
4130       return MatchOperand_ParseFail;
4131     }
4132     ++Count;
4133     // Parse the lane specifier if present.
4134     VectorLaneTy NextLaneKind;
4135     unsigned NextLaneIndex;
4136     SMLoc EndLoc = Parser.getTok().getLoc();
4137     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
4138       return MatchOperand_ParseFail;
4139     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4140       Error(EndLoc, "mismatched lane index in register list");
4141       return MatchOperand_ParseFail;
4142     }
4143   }
4144 
4145   if (Parser.getTok().isNot(AsmToken::RCurly)) {
4146     Error(Parser.getTok().getLoc(), "'}' expected");
4147     return MatchOperand_ParseFail;
4148   }
4149   E = Parser.getTok().getEndLoc();
4150   Parser.Lex(); // Eat '}' token.
4151 
4152   switch (LaneKind) {
4153   case NoLanes:
4154     // Two-register operands have been converted to the
4155     // composite register classes.
4156     if (Count == 2) {
4157       const MCRegisterClass *RC = (Spacing == 1) ?
4158         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
4159         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
4160       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
4161     }
4162     Operands.push_back(ARMOperand::CreateVectorList(FirstReg, Count,
4163                                                     (Spacing == 2), S, E));
4164     break;
4165   case AllLanes:
4166     // Two-register operands have been converted to the
4167     // composite register classes.
4168     if (Count == 2) {
4169       const MCRegisterClass *RC = (Spacing == 1) ?
4170         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
4171         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
4172       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
4173     }
4174     Operands.push_back(ARMOperand::CreateVectorListAllLanes(FirstReg, Count,
4175                                                             (Spacing == 2),
4176                                                             S, E));
4177     break;
4178   case IndexedLane:
4179     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
4180                                                            LaneIndex,
4181                                                            (Spacing == 2),
4182                                                            S, E));
4183     break;
4184   }
4185   return MatchOperand_Success;
4186 }
4187 
4188 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
4189 OperandMatchResultTy
parseMemBarrierOptOperand(OperandVector & Operands)4190 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
4191   MCAsmParser &Parser = getParser();
4192   SMLoc S = Parser.getTok().getLoc();
4193   const AsmToken &Tok = Parser.getTok();
4194   unsigned Opt;
4195 
4196   if (Tok.is(AsmToken::Identifier)) {
4197     StringRef OptStr = Tok.getString();
4198 
4199     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
4200       .Case("sy",    ARM_MB::SY)
4201       .Case("st",    ARM_MB::ST)
4202       .Case("ld",    ARM_MB::LD)
4203       .Case("sh",    ARM_MB::ISH)
4204       .Case("ish",   ARM_MB::ISH)
4205       .Case("shst",  ARM_MB::ISHST)
4206       .Case("ishst", ARM_MB::ISHST)
4207       .Case("ishld", ARM_MB::ISHLD)
4208       .Case("nsh",   ARM_MB::NSH)
4209       .Case("un",    ARM_MB::NSH)
4210       .Case("nshst", ARM_MB::NSHST)
4211       .Case("nshld", ARM_MB::NSHLD)
4212       .Case("unst",  ARM_MB::NSHST)
4213       .Case("osh",   ARM_MB::OSH)
4214       .Case("oshst", ARM_MB::OSHST)
4215       .Case("oshld", ARM_MB::OSHLD)
4216       .Default(~0U);
4217 
4218     // ishld, oshld, nshld and ld are only available from ARMv8.
4219     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
4220                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
4221       Opt = ~0U;
4222 
4223     if (Opt == ~0U)
4224       return MatchOperand_NoMatch;
4225 
4226     Parser.Lex(); // Eat identifier token.
4227   } else if (Tok.is(AsmToken::Hash) ||
4228              Tok.is(AsmToken::Dollar) ||
4229              Tok.is(AsmToken::Integer)) {
4230     if (Parser.getTok().isNot(AsmToken::Integer))
4231       Parser.Lex(); // Eat '#' or '$'.
4232     SMLoc Loc = Parser.getTok().getLoc();
4233 
4234     const MCExpr *MemBarrierID;
4235     if (getParser().parseExpression(MemBarrierID)) {
4236       Error(Loc, "illegal expression");
4237       return MatchOperand_ParseFail;
4238     }
4239 
4240     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
4241     if (!CE) {
4242       Error(Loc, "constant expression expected");
4243       return MatchOperand_ParseFail;
4244     }
4245 
4246     int Val = CE->getValue();
4247     if (Val & ~0xf) {
4248       Error(Loc, "immediate value out of range");
4249       return MatchOperand_ParseFail;
4250     }
4251 
4252     Opt = ARM_MB::RESERVED_0 + Val;
4253   } else
4254     return MatchOperand_ParseFail;
4255 
4256   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
4257   return MatchOperand_Success;
4258 }
4259 
4260 OperandMatchResultTy
parseTraceSyncBarrierOptOperand(OperandVector & Operands)4261 ARMAsmParser::parseTraceSyncBarrierOptOperand(OperandVector &Operands) {
4262   MCAsmParser &Parser = getParser();
4263   SMLoc S = Parser.getTok().getLoc();
4264   const AsmToken &Tok = Parser.getTok();
4265 
4266   if (Tok.isNot(AsmToken::Identifier))
4267      return MatchOperand_NoMatch;
4268 
4269   if (!Tok.getString().equals_lower("csync"))
4270     return MatchOperand_NoMatch;
4271 
4272   Parser.Lex(); // Eat identifier token.
4273 
4274   Operands.push_back(ARMOperand::CreateTraceSyncBarrierOpt(ARM_TSB::CSYNC, S));
4275   return MatchOperand_Success;
4276 }
4277 
4278 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
4279 OperandMatchResultTy
parseInstSyncBarrierOptOperand(OperandVector & Operands)4280 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
4281   MCAsmParser &Parser = getParser();
4282   SMLoc S = Parser.getTok().getLoc();
4283   const AsmToken &Tok = Parser.getTok();
4284   unsigned Opt;
4285 
4286   if (Tok.is(AsmToken::Identifier)) {
4287     StringRef OptStr = Tok.getString();
4288 
4289     if (OptStr.equals_lower("sy"))
4290       Opt = ARM_ISB::SY;
4291     else
4292       return MatchOperand_NoMatch;
4293 
4294     Parser.Lex(); // Eat identifier token.
4295   } else if (Tok.is(AsmToken::Hash) ||
4296              Tok.is(AsmToken::Dollar) ||
4297              Tok.is(AsmToken::Integer)) {
4298     if (Parser.getTok().isNot(AsmToken::Integer))
4299       Parser.Lex(); // Eat '#' or '$'.
4300     SMLoc Loc = Parser.getTok().getLoc();
4301 
4302     const MCExpr *ISBarrierID;
4303     if (getParser().parseExpression(ISBarrierID)) {
4304       Error(Loc, "illegal expression");
4305       return MatchOperand_ParseFail;
4306     }
4307 
4308     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
4309     if (!CE) {
4310       Error(Loc, "constant expression expected");
4311       return MatchOperand_ParseFail;
4312     }
4313 
4314     int Val = CE->getValue();
4315     if (Val & ~0xf) {
4316       Error(Loc, "immediate value out of range");
4317       return MatchOperand_ParseFail;
4318     }
4319 
4320     Opt = ARM_ISB::RESERVED_0 + Val;
4321   } else
4322     return MatchOperand_ParseFail;
4323 
4324   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
4325           (ARM_ISB::InstSyncBOpt)Opt, S));
4326   return MatchOperand_Success;
4327 }
4328 
4329 
4330 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
4331 OperandMatchResultTy
parseProcIFlagsOperand(OperandVector & Operands)4332 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
4333   MCAsmParser &Parser = getParser();
4334   SMLoc S = Parser.getTok().getLoc();
4335   const AsmToken &Tok = Parser.getTok();
4336   if (!Tok.is(AsmToken::Identifier))
4337     return MatchOperand_NoMatch;
4338   StringRef IFlagsStr = Tok.getString();
4339 
4340   // An iflags string of "none" is interpreted to mean that none of the AIF
4341   // bits are set.  Not a terribly useful instruction, but a valid encoding.
4342   unsigned IFlags = 0;
4343   if (IFlagsStr != "none") {
4344         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
4345       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1).lower())
4346         .Case("a", ARM_PROC::A)
4347         .Case("i", ARM_PROC::I)
4348         .Case("f", ARM_PROC::F)
4349         .Default(~0U);
4350 
4351       // If some specific iflag is already set, it means that some letter is
4352       // present more than once, this is not acceptable.
4353       if (Flag == ~0U || (IFlags & Flag))
4354         return MatchOperand_NoMatch;
4355 
4356       IFlags |= Flag;
4357     }
4358   }
4359 
4360   Parser.Lex(); // Eat identifier token.
4361   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
4362   return MatchOperand_Success;
4363 }
4364 
4365 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
4366 OperandMatchResultTy
parseMSRMaskOperand(OperandVector & Operands)4367 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
4368   MCAsmParser &Parser = getParser();
4369   SMLoc S = Parser.getTok().getLoc();
4370   const AsmToken &Tok = Parser.getTok();
4371 
4372   if (Tok.is(AsmToken::Integer)) {
4373     int64_t Val = Tok.getIntVal();
4374     if (Val > 255 || Val < 0) {
4375       return MatchOperand_NoMatch;
4376     }
4377     unsigned SYSmvalue = Val & 0xFF;
4378     Parser.Lex();
4379     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
4380     return MatchOperand_Success;
4381   }
4382 
4383   if (!Tok.is(AsmToken::Identifier))
4384     return MatchOperand_NoMatch;
4385   StringRef Mask = Tok.getString();
4386 
4387   if (isMClass()) {
4388     auto TheReg = ARMSysReg::lookupMClassSysRegByName(Mask.lower());
4389     if (!TheReg || !TheReg->hasRequiredFeatures(getSTI().getFeatureBits()))
4390       return MatchOperand_NoMatch;
4391 
4392     unsigned SYSmvalue = TheReg->Encoding & 0xFFF;
4393 
4394     Parser.Lex(); // Eat identifier token.
4395     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
4396     return MatchOperand_Success;
4397   }
4398 
4399   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
4400   size_t Start = 0, Next = Mask.find('_');
4401   StringRef Flags = "";
4402   std::string SpecReg = Mask.slice(Start, Next).lower();
4403   if (Next != StringRef::npos)
4404     Flags = Mask.slice(Next+1, Mask.size());
4405 
4406   // FlagsVal contains the complete mask:
4407   // 3-0: Mask
4408   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4409   unsigned FlagsVal = 0;
4410 
4411   if (SpecReg == "apsr") {
4412     FlagsVal = StringSwitch<unsigned>(Flags)
4413     .Case("nzcvq",  0x8) // same as CPSR_f
4414     .Case("g",      0x4) // same as CPSR_s
4415     .Case("nzcvqg", 0xc) // same as CPSR_fs
4416     .Default(~0U);
4417 
4418     if (FlagsVal == ~0U) {
4419       if (!Flags.empty())
4420         return MatchOperand_NoMatch;
4421       else
4422         FlagsVal = 8; // No flag
4423     }
4424   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
4425     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
4426     if (Flags == "all" || Flags == "")
4427       Flags = "fc";
4428     for (int i = 0, e = Flags.size(); i != e; ++i) {
4429       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
4430       .Case("c", 1)
4431       .Case("x", 2)
4432       .Case("s", 4)
4433       .Case("f", 8)
4434       .Default(~0U);
4435 
4436       // If some specific flag is already set, it means that some letter is
4437       // present more than once, this is not acceptable.
4438       if (Flag == ~0U || (FlagsVal & Flag))
4439         return MatchOperand_NoMatch;
4440       FlagsVal |= Flag;
4441     }
4442   } else // No match for special register.
4443     return MatchOperand_NoMatch;
4444 
4445   // Special register without flags is NOT equivalent to "fc" flags.
4446   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
4447   // two lines would enable gas compatibility at the expense of breaking
4448   // round-tripping.
4449   //
4450   // if (!FlagsVal)
4451   //  FlagsVal = 0x9;
4452 
4453   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4454   if (SpecReg == "spsr")
4455     FlagsVal |= 16;
4456 
4457   Parser.Lex(); // Eat identifier token.
4458   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4459   return MatchOperand_Success;
4460 }
4461 
4462 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
4463 /// use in the MRS/MSR instructions added to support virtualization.
4464 OperandMatchResultTy
parseBankedRegOperand(OperandVector & Operands)4465 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
4466   MCAsmParser &Parser = getParser();
4467   SMLoc S = Parser.getTok().getLoc();
4468   const AsmToken &Tok = Parser.getTok();
4469   if (!Tok.is(AsmToken::Identifier))
4470     return MatchOperand_NoMatch;
4471   StringRef RegName = Tok.getString();
4472 
4473   auto TheReg = ARMBankedReg::lookupBankedRegByName(RegName.lower());
4474   if (!TheReg)
4475     return MatchOperand_NoMatch;
4476   unsigned Encoding = TheReg->Encoding;
4477 
4478   Parser.Lex(); // Eat identifier token.
4479   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
4480   return MatchOperand_Success;
4481 }
4482 
4483 OperandMatchResultTy
parsePKHImm(OperandVector & Operands,StringRef Op,int Low,int High)4484 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
4485                           int High) {
4486   MCAsmParser &Parser = getParser();
4487   const AsmToken &Tok = Parser.getTok();
4488   if (Tok.isNot(AsmToken::Identifier)) {
4489     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4490     return MatchOperand_ParseFail;
4491   }
4492   StringRef ShiftName = Tok.getString();
4493   std::string LowerOp = Op.lower();
4494   std::string UpperOp = Op.upper();
4495   if (ShiftName != LowerOp && ShiftName != UpperOp) {
4496     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4497     return MatchOperand_ParseFail;
4498   }
4499   Parser.Lex(); // Eat shift type token.
4500 
4501   // There must be a '#' and a shift amount.
4502   if (Parser.getTok().isNot(AsmToken::Hash) &&
4503       Parser.getTok().isNot(AsmToken::Dollar)) {
4504     Error(Parser.getTok().getLoc(), "'#' expected");
4505     return MatchOperand_ParseFail;
4506   }
4507   Parser.Lex(); // Eat hash token.
4508 
4509   const MCExpr *ShiftAmount;
4510   SMLoc Loc = Parser.getTok().getLoc();
4511   SMLoc EndLoc;
4512   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4513     Error(Loc, "illegal expression");
4514     return MatchOperand_ParseFail;
4515   }
4516   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4517   if (!CE) {
4518     Error(Loc, "constant expression expected");
4519     return MatchOperand_ParseFail;
4520   }
4521   int Val = CE->getValue();
4522   if (Val < Low || Val > High) {
4523     Error(Loc, "immediate value out of range");
4524     return MatchOperand_ParseFail;
4525   }
4526 
4527   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
4528 
4529   return MatchOperand_Success;
4530 }
4531 
4532 OperandMatchResultTy
parseSetEndImm(OperandVector & Operands)4533 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
4534   MCAsmParser &Parser = getParser();
4535   const AsmToken &Tok = Parser.getTok();
4536   SMLoc S = Tok.getLoc();
4537   if (Tok.isNot(AsmToken::Identifier)) {
4538     Error(S, "'be' or 'le' operand expected");
4539     return MatchOperand_ParseFail;
4540   }
4541   int Val = StringSwitch<int>(Tok.getString().lower())
4542     .Case("be", 1)
4543     .Case("le", 0)
4544     .Default(-1);
4545   Parser.Lex(); // Eat the token.
4546 
4547   if (Val == -1) {
4548     Error(S, "'be' or 'le' operand expected");
4549     return MatchOperand_ParseFail;
4550   }
4551   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
4552                                                                   getContext()),
4553                                            S, Tok.getEndLoc()));
4554   return MatchOperand_Success;
4555 }
4556 
4557 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
4558 /// instructions. Legal values are:
4559 ///     lsl #n  'n' in [0,31]
4560 ///     asr #n  'n' in [1,32]
4561 ///             n == 32 encoded as n == 0.
4562 OperandMatchResultTy
parseShifterImm(OperandVector & Operands)4563 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
4564   MCAsmParser &Parser = getParser();
4565   const AsmToken &Tok = Parser.getTok();
4566   SMLoc S = Tok.getLoc();
4567   if (Tok.isNot(AsmToken::Identifier)) {
4568     Error(S, "shift operator 'asr' or 'lsl' expected");
4569     return MatchOperand_ParseFail;
4570   }
4571   StringRef ShiftName = Tok.getString();
4572   bool isASR;
4573   if (ShiftName == "lsl" || ShiftName == "LSL")
4574     isASR = false;
4575   else if (ShiftName == "asr" || ShiftName == "ASR")
4576     isASR = true;
4577   else {
4578     Error(S, "shift operator 'asr' or 'lsl' expected");
4579     return MatchOperand_ParseFail;
4580   }
4581   Parser.Lex(); // Eat the operator.
4582 
4583   // A '#' and a shift amount.
4584   if (Parser.getTok().isNot(AsmToken::Hash) &&
4585       Parser.getTok().isNot(AsmToken::Dollar)) {
4586     Error(Parser.getTok().getLoc(), "'#' expected");
4587     return MatchOperand_ParseFail;
4588   }
4589   Parser.Lex(); // Eat hash token.
4590   SMLoc ExLoc = Parser.getTok().getLoc();
4591 
4592   const MCExpr *ShiftAmount;
4593   SMLoc EndLoc;
4594   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4595     Error(ExLoc, "malformed shift expression");
4596     return MatchOperand_ParseFail;
4597   }
4598   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4599   if (!CE) {
4600     Error(ExLoc, "shift amount must be an immediate");
4601     return MatchOperand_ParseFail;
4602   }
4603 
4604   int64_t Val = CE->getValue();
4605   if (isASR) {
4606     // Shift amount must be in [1,32]
4607     if (Val < 1 || Val > 32) {
4608       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
4609       return MatchOperand_ParseFail;
4610     }
4611     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
4612     if (isThumb() && Val == 32) {
4613       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
4614       return MatchOperand_ParseFail;
4615     }
4616     if (Val == 32) Val = 0;
4617   } else {
4618     // Shift amount must be in [1,32]
4619     if (Val < 0 || Val > 31) {
4620       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
4621       return MatchOperand_ParseFail;
4622     }
4623   }
4624 
4625   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
4626 
4627   return MatchOperand_Success;
4628 }
4629 
4630 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
4631 /// of instructions. Legal values are:
4632 ///     ror #n  'n' in {0, 8, 16, 24}
4633 OperandMatchResultTy
parseRotImm(OperandVector & Operands)4634 ARMAsmParser::parseRotImm(OperandVector &Operands) {
4635   MCAsmParser &Parser = getParser();
4636   const AsmToken &Tok = Parser.getTok();
4637   SMLoc S = Tok.getLoc();
4638   if (Tok.isNot(AsmToken::Identifier))
4639     return MatchOperand_NoMatch;
4640   StringRef ShiftName = Tok.getString();
4641   if (ShiftName != "ror" && ShiftName != "ROR")
4642     return MatchOperand_NoMatch;
4643   Parser.Lex(); // Eat the operator.
4644 
4645   // A '#' and a rotate amount.
4646   if (Parser.getTok().isNot(AsmToken::Hash) &&
4647       Parser.getTok().isNot(AsmToken::Dollar)) {
4648     Error(Parser.getTok().getLoc(), "'#' expected");
4649     return MatchOperand_ParseFail;
4650   }
4651   Parser.Lex(); // Eat hash token.
4652   SMLoc ExLoc = Parser.getTok().getLoc();
4653 
4654   const MCExpr *ShiftAmount;
4655   SMLoc EndLoc;
4656   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4657     Error(ExLoc, "malformed rotate expression");
4658     return MatchOperand_ParseFail;
4659   }
4660   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4661   if (!CE) {
4662     Error(ExLoc, "rotate amount must be an immediate");
4663     return MatchOperand_ParseFail;
4664   }
4665 
4666   int64_t Val = CE->getValue();
4667   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
4668   // normally, zero is represented in asm by omitting the rotate operand
4669   // entirely.
4670   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
4671     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
4672     return MatchOperand_ParseFail;
4673   }
4674 
4675   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
4676 
4677   return MatchOperand_Success;
4678 }
4679 
4680 OperandMatchResultTy
parseModImm(OperandVector & Operands)4681 ARMAsmParser::parseModImm(OperandVector &Operands) {
4682   MCAsmParser &Parser = getParser();
4683   MCAsmLexer &Lexer = getLexer();
4684   int64_t Imm1, Imm2;
4685 
4686   SMLoc S = Parser.getTok().getLoc();
4687 
4688   // 1) A mod_imm operand can appear in the place of a register name:
4689   //   add r0, #mod_imm
4690   //   add r0, r0, #mod_imm
4691   // to correctly handle the latter, we bail out as soon as we see an
4692   // identifier.
4693   //
4694   // 2) Similarly, we do not want to parse into complex operands:
4695   //   mov r0, #mod_imm
4696   //   mov r0, :lower16:(_foo)
4697   if (Parser.getTok().is(AsmToken::Identifier) ||
4698       Parser.getTok().is(AsmToken::Colon))
4699     return MatchOperand_NoMatch;
4700 
4701   // Hash (dollar) is optional as per the ARMARM
4702   if (Parser.getTok().is(AsmToken::Hash) ||
4703       Parser.getTok().is(AsmToken::Dollar)) {
4704     // Avoid parsing into complex operands (#:)
4705     if (Lexer.peekTok().is(AsmToken::Colon))
4706       return MatchOperand_NoMatch;
4707 
4708     // Eat the hash (dollar)
4709     Parser.Lex();
4710   }
4711 
4712   SMLoc Sx1, Ex1;
4713   Sx1 = Parser.getTok().getLoc();
4714   const MCExpr *Imm1Exp;
4715   if (getParser().parseExpression(Imm1Exp, Ex1)) {
4716     Error(Sx1, "malformed expression");
4717     return MatchOperand_ParseFail;
4718   }
4719 
4720   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
4721 
4722   if (CE) {
4723     // Immediate must fit within 32-bits
4724     Imm1 = CE->getValue();
4725     int Enc = ARM_AM::getSOImmVal(Imm1);
4726     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
4727       // We have a match!
4728       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
4729                                                   (Enc & 0xF00) >> 7,
4730                                                   Sx1, Ex1));
4731       return MatchOperand_Success;
4732     }
4733 
4734     // We have parsed an immediate which is not for us, fallback to a plain
4735     // immediate. This can happen for instruction aliases. For an example,
4736     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
4737     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
4738     // instruction with a mod_imm operand. The alias is defined such that the
4739     // parser method is shared, that's why we have to do this here.
4740     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
4741       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4742       return MatchOperand_Success;
4743     }
4744   } else {
4745     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
4746     // MCFixup). Fallback to a plain immediate.
4747     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4748     return MatchOperand_Success;
4749   }
4750 
4751   // From this point onward, we expect the input to be a (#bits, #rot) pair
4752   if (Parser.getTok().isNot(AsmToken::Comma)) {
4753     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
4754     return MatchOperand_ParseFail;
4755   }
4756 
4757   if (Imm1 & ~0xFF) {
4758     Error(Sx1, "immediate operand must a number in the range [0, 255]");
4759     return MatchOperand_ParseFail;
4760   }
4761 
4762   // Eat the comma
4763   Parser.Lex();
4764 
4765   // Repeat for #rot
4766   SMLoc Sx2, Ex2;
4767   Sx2 = Parser.getTok().getLoc();
4768 
4769   // Eat the optional hash (dollar)
4770   if (Parser.getTok().is(AsmToken::Hash) ||
4771       Parser.getTok().is(AsmToken::Dollar))
4772     Parser.Lex();
4773 
4774   const MCExpr *Imm2Exp;
4775   if (getParser().parseExpression(Imm2Exp, Ex2)) {
4776     Error(Sx2, "malformed expression");
4777     return MatchOperand_ParseFail;
4778   }
4779 
4780   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
4781 
4782   if (CE) {
4783     Imm2 = CE->getValue();
4784     if (!(Imm2 & ~0x1E)) {
4785       // We have a match!
4786       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
4787       return MatchOperand_Success;
4788     }
4789     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
4790     return MatchOperand_ParseFail;
4791   } else {
4792     Error(Sx2, "constant expression expected");
4793     return MatchOperand_ParseFail;
4794   }
4795 }
4796 
4797 OperandMatchResultTy
parseBitfield(OperandVector & Operands)4798 ARMAsmParser::parseBitfield(OperandVector &Operands) {
4799   MCAsmParser &Parser = getParser();
4800   SMLoc S = Parser.getTok().getLoc();
4801   // The bitfield descriptor is really two operands, the LSB and the width.
4802   if (Parser.getTok().isNot(AsmToken::Hash) &&
4803       Parser.getTok().isNot(AsmToken::Dollar)) {
4804     Error(Parser.getTok().getLoc(), "'#' expected");
4805     return MatchOperand_ParseFail;
4806   }
4807   Parser.Lex(); // Eat hash token.
4808 
4809   const MCExpr *LSBExpr;
4810   SMLoc E = Parser.getTok().getLoc();
4811   if (getParser().parseExpression(LSBExpr)) {
4812     Error(E, "malformed immediate expression");
4813     return MatchOperand_ParseFail;
4814   }
4815   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
4816   if (!CE) {
4817     Error(E, "'lsb' operand must be an immediate");
4818     return MatchOperand_ParseFail;
4819   }
4820 
4821   int64_t LSB = CE->getValue();
4822   // The LSB must be in the range [0,31]
4823   if (LSB < 0 || LSB > 31) {
4824     Error(E, "'lsb' operand must be in the range [0,31]");
4825     return MatchOperand_ParseFail;
4826   }
4827   E = Parser.getTok().getLoc();
4828 
4829   // Expect another immediate operand.
4830   if (Parser.getTok().isNot(AsmToken::Comma)) {
4831     Error(Parser.getTok().getLoc(), "too few operands");
4832     return MatchOperand_ParseFail;
4833   }
4834   Parser.Lex(); // Eat hash token.
4835   if (Parser.getTok().isNot(AsmToken::Hash) &&
4836       Parser.getTok().isNot(AsmToken::Dollar)) {
4837     Error(Parser.getTok().getLoc(), "'#' expected");
4838     return MatchOperand_ParseFail;
4839   }
4840   Parser.Lex(); // Eat hash token.
4841 
4842   const MCExpr *WidthExpr;
4843   SMLoc EndLoc;
4844   if (getParser().parseExpression(WidthExpr, EndLoc)) {
4845     Error(E, "malformed immediate expression");
4846     return MatchOperand_ParseFail;
4847   }
4848   CE = dyn_cast<MCConstantExpr>(WidthExpr);
4849   if (!CE) {
4850     Error(E, "'width' operand must be an immediate");
4851     return MatchOperand_ParseFail;
4852   }
4853 
4854   int64_t Width = CE->getValue();
4855   // The LSB must be in the range [1,32-lsb]
4856   if (Width < 1 || Width > 32 - LSB) {
4857     Error(E, "'width' operand must be in the range [1,32-lsb]");
4858     return MatchOperand_ParseFail;
4859   }
4860 
4861   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
4862 
4863   return MatchOperand_Success;
4864 }
4865 
4866 OperandMatchResultTy
parsePostIdxReg(OperandVector & Operands)4867 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
4868   // Check for a post-index addressing register operand. Specifically:
4869   // postidx_reg := '+' register {, shift}
4870   //              | '-' register {, shift}
4871   //              | register {, shift}
4872 
4873   // This method must return MatchOperand_NoMatch without consuming any tokens
4874   // in the case where there is no match, as other alternatives take other
4875   // parse methods.
4876   MCAsmParser &Parser = getParser();
4877   AsmToken Tok = Parser.getTok();
4878   SMLoc S = Tok.getLoc();
4879   bool haveEaten = false;
4880   bool isAdd = true;
4881   if (Tok.is(AsmToken::Plus)) {
4882     Parser.Lex(); // Eat the '+' token.
4883     haveEaten = true;
4884   } else if (Tok.is(AsmToken::Minus)) {
4885     Parser.Lex(); // Eat the '-' token.
4886     isAdd = false;
4887     haveEaten = true;
4888   }
4889 
4890   SMLoc E = Parser.getTok().getEndLoc();
4891   int Reg = tryParseRegister();
4892   if (Reg == -1) {
4893     if (!haveEaten)
4894       return MatchOperand_NoMatch;
4895     Error(Parser.getTok().getLoc(), "register expected");
4896     return MatchOperand_ParseFail;
4897   }
4898 
4899   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
4900   unsigned ShiftImm = 0;
4901   if (Parser.getTok().is(AsmToken::Comma)) {
4902     Parser.Lex(); // Eat the ','.
4903     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
4904       return MatchOperand_ParseFail;
4905 
4906     // FIXME: Only approximates end...may include intervening whitespace.
4907     E = Parser.getTok().getLoc();
4908   }
4909 
4910   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
4911                                                   ShiftImm, S, E));
4912 
4913   return MatchOperand_Success;
4914 }
4915 
4916 OperandMatchResultTy
parseAM3Offset(OperandVector & Operands)4917 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
4918   // Check for a post-index addressing register operand. Specifically:
4919   // am3offset := '+' register
4920   //              | '-' register
4921   //              | register
4922   //              | # imm
4923   //              | # + imm
4924   //              | # - imm
4925 
4926   // This method must return MatchOperand_NoMatch without consuming any tokens
4927   // in the case where there is no match, as other alternatives take other
4928   // parse methods.
4929   MCAsmParser &Parser = getParser();
4930   AsmToken Tok = Parser.getTok();
4931   SMLoc S = Tok.getLoc();
4932 
4933   // Do immediates first, as we always parse those if we have a '#'.
4934   if (Parser.getTok().is(AsmToken::Hash) ||
4935       Parser.getTok().is(AsmToken::Dollar)) {
4936     Parser.Lex(); // Eat '#' or '$'.
4937     // Explicitly look for a '-', as we need to encode negative zero
4938     // differently.
4939     bool isNegative = Parser.getTok().is(AsmToken::Minus);
4940     const MCExpr *Offset;
4941     SMLoc E;
4942     if (getParser().parseExpression(Offset, E))
4943       return MatchOperand_ParseFail;
4944     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4945     if (!CE) {
4946       Error(S, "constant expression expected");
4947       return MatchOperand_ParseFail;
4948     }
4949     // Negative zero is encoded as the flag value
4950     // std::numeric_limits<int32_t>::min().
4951     int32_t Val = CE->getValue();
4952     if (isNegative && Val == 0)
4953       Val = std::numeric_limits<int32_t>::min();
4954 
4955     Operands.push_back(
4956       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
4957 
4958     return MatchOperand_Success;
4959   }
4960 
4961   bool haveEaten = false;
4962   bool isAdd = true;
4963   if (Tok.is(AsmToken::Plus)) {
4964     Parser.Lex(); // Eat the '+' token.
4965     haveEaten = true;
4966   } else if (Tok.is(AsmToken::Minus)) {
4967     Parser.Lex(); // Eat the '-' token.
4968     isAdd = false;
4969     haveEaten = true;
4970   }
4971 
4972   Tok = Parser.getTok();
4973   int Reg = tryParseRegister();
4974   if (Reg == -1) {
4975     if (!haveEaten)
4976       return MatchOperand_NoMatch;
4977     Error(Tok.getLoc(), "register expected");
4978     return MatchOperand_ParseFail;
4979   }
4980 
4981   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
4982                                                   0, S, Tok.getEndLoc()));
4983 
4984   return MatchOperand_Success;
4985 }
4986 
4987 /// Convert parsed operands to MCInst.  Needed here because this instruction
4988 /// only has two register operands, but multiplication is commutative so
4989 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
cvtThumbMultiply(MCInst & Inst,const OperandVector & Operands)4990 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
4991                                     const OperandVector &Operands) {
4992   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
4993   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
4994   // If we have a three-operand form, make sure to set Rn to be the operand
4995   // that isn't the same as Rd.
4996   unsigned RegOp = 4;
4997   if (Operands.size() == 6 &&
4998       ((ARMOperand &)*Operands[4]).getReg() ==
4999           ((ARMOperand &)*Operands[3]).getReg())
5000     RegOp = 5;
5001   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
5002   Inst.addOperand(Inst.getOperand(0));
5003   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
5004 }
5005 
cvtThumbBranches(MCInst & Inst,const OperandVector & Operands)5006 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
5007                                     const OperandVector &Operands) {
5008   int CondOp = -1, ImmOp = -1;
5009   switch(Inst.getOpcode()) {
5010     case ARM::tB:
5011     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
5012 
5013     case ARM::t2B:
5014     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
5015 
5016     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
5017   }
5018   // first decide whether or not the branch should be conditional
5019   // by looking at it's location relative to an IT block
5020   if(inITBlock()) {
5021     // inside an IT block we cannot have any conditional branches. any
5022     // such instructions needs to be converted to unconditional form
5023     switch(Inst.getOpcode()) {
5024       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
5025       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
5026     }
5027   } else {
5028     // outside IT blocks we can only have unconditional branches with AL
5029     // condition code or conditional branches with non-AL condition code
5030     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
5031     switch(Inst.getOpcode()) {
5032       case ARM::tB:
5033       case ARM::tBcc:
5034         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc);
5035         break;
5036       case ARM::t2B:
5037       case ARM::t2Bcc:
5038         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
5039         break;
5040     }
5041   }
5042 
5043   // now decide on encoding size based on branch target range
5044   switch(Inst.getOpcode()) {
5045     // classify tB as either t2B or t1B based on range of immediate operand
5046     case ARM::tB: {
5047       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
5048       if (!op.isSignedOffset<11, 1>() && isThumb() && hasV8MBaseline())
5049         Inst.setOpcode(ARM::t2B);
5050       break;
5051     }
5052     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
5053     case ARM::tBcc: {
5054       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
5055       if (!op.isSignedOffset<8, 1>() && isThumb() && hasV8MBaseline())
5056         Inst.setOpcode(ARM::t2Bcc);
5057       break;
5058     }
5059   }
5060   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
5061   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
5062 }
5063 
5064 /// Parse an ARM memory expression, return false if successful else return true
5065 /// or an error.  The first token must be a '[' when called.
parseMemory(OperandVector & Operands)5066 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
5067   MCAsmParser &Parser = getParser();
5068   SMLoc S, E;
5069   if (Parser.getTok().isNot(AsmToken::LBrac))
5070     return TokError("Token is not a Left Bracket");
5071   S = Parser.getTok().getLoc();
5072   Parser.Lex(); // Eat left bracket token.
5073 
5074   const AsmToken &BaseRegTok = Parser.getTok();
5075   int BaseRegNum = tryParseRegister();
5076   if (BaseRegNum == -1)
5077     return Error(BaseRegTok.getLoc(), "register expected");
5078 
5079   // The next token must either be a comma, a colon or a closing bracket.
5080   const AsmToken &Tok = Parser.getTok();
5081   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
5082       !Tok.is(AsmToken::RBrac))
5083     return Error(Tok.getLoc(), "malformed memory operand");
5084 
5085   if (Tok.is(AsmToken::RBrac)) {
5086     E = Tok.getEndLoc();
5087     Parser.Lex(); // Eat right bracket token.
5088 
5089     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5090                                              ARM_AM::no_shift, 0, 0, false,
5091                                              S, E));
5092 
5093     // If there's a pre-indexing writeback marker, '!', just add it as a token
5094     // operand. It's rather odd, but syntactically valid.
5095     if (Parser.getTok().is(AsmToken::Exclaim)) {
5096       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5097       Parser.Lex(); // Eat the '!'.
5098     }
5099 
5100     return false;
5101   }
5102 
5103   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
5104          "Lost colon or comma in memory operand?!");
5105   if (Tok.is(AsmToken::Comma)) {
5106     Parser.Lex(); // Eat the comma.
5107   }
5108 
5109   // If we have a ':', it's an alignment specifier.
5110   if (Parser.getTok().is(AsmToken::Colon)) {
5111     Parser.Lex(); // Eat the ':'.
5112     E = Parser.getTok().getLoc();
5113     SMLoc AlignmentLoc = Tok.getLoc();
5114 
5115     const MCExpr *Expr;
5116     if (getParser().parseExpression(Expr))
5117      return true;
5118 
5119     // The expression has to be a constant. Memory references with relocations
5120     // don't come through here, as they use the <label> forms of the relevant
5121     // instructions.
5122     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5123     if (!CE)
5124       return Error (E, "constant expression expected");
5125 
5126     unsigned Align = 0;
5127     switch (CE->getValue()) {
5128     default:
5129       return Error(E,
5130                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
5131     case 16:  Align = 2; break;
5132     case 32:  Align = 4; break;
5133     case 64:  Align = 8; break;
5134     case 128: Align = 16; break;
5135     case 256: Align = 32; break;
5136     }
5137 
5138     // Now we should have the closing ']'
5139     if (Parser.getTok().isNot(AsmToken::RBrac))
5140       return Error(Parser.getTok().getLoc(), "']' expected");
5141     E = Parser.getTok().getEndLoc();
5142     Parser.Lex(); // Eat right bracket token.
5143 
5144     // Don't worry about range checking the value here. That's handled by
5145     // the is*() predicates.
5146     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5147                                              ARM_AM::no_shift, 0, Align,
5148                                              false, S, E, AlignmentLoc));
5149 
5150     // If there's a pre-indexing writeback marker, '!', just add it as a token
5151     // operand.
5152     if (Parser.getTok().is(AsmToken::Exclaim)) {
5153       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5154       Parser.Lex(); // Eat the '!'.
5155     }
5156 
5157     return false;
5158   }
5159 
5160   // If we have a '#', it's an immediate offset, else assume it's a register
5161   // offset. Be friendly and also accept a plain integer (without a leading
5162   // hash) for gas compatibility.
5163   if (Parser.getTok().is(AsmToken::Hash) ||
5164       Parser.getTok().is(AsmToken::Dollar) ||
5165       Parser.getTok().is(AsmToken::Integer)) {
5166     if (Parser.getTok().isNot(AsmToken::Integer))
5167       Parser.Lex(); // Eat '#' or '$'.
5168     E = Parser.getTok().getLoc();
5169 
5170     bool isNegative = getParser().getTok().is(AsmToken::Minus);
5171     const MCExpr *Offset;
5172     if (getParser().parseExpression(Offset))
5173      return true;
5174 
5175     // The expression has to be a constant. Memory references with relocations
5176     // don't come through here, as they use the <label> forms of the relevant
5177     // instructions.
5178     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
5179     if (!CE)
5180       return Error (E, "constant expression expected");
5181 
5182     // If the constant was #-0, represent it as
5183     // std::numeric_limits<int32_t>::min().
5184     int32_t Val = CE->getValue();
5185     if (isNegative && Val == 0)
5186       CE = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
5187                                   getContext());
5188 
5189     // Now we should have the closing ']'
5190     if (Parser.getTok().isNot(AsmToken::RBrac))
5191       return Error(Parser.getTok().getLoc(), "']' expected");
5192     E = Parser.getTok().getEndLoc();
5193     Parser.Lex(); // Eat right bracket token.
5194 
5195     // Don't worry about range checking the value here. That's handled by
5196     // the is*() predicates.
5197     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
5198                                              ARM_AM::no_shift, 0, 0,
5199                                              false, S, E));
5200 
5201     // If there's a pre-indexing writeback marker, '!', just add it as a token
5202     // operand.
5203     if (Parser.getTok().is(AsmToken::Exclaim)) {
5204       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5205       Parser.Lex(); // Eat the '!'.
5206     }
5207 
5208     return false;
5209   }
5210 
5211   // The register offset is optionally preceded by a '+' or '-'
5212   bool isNegative = false;
5213   if (Parser.getTok().is(AsmToken::Minus)) {
5214     isNegative = true;
5215     Parser.Lex(); // Eat the '-'.
5216   } else if (Parser.getTok().is(AsmToken::Plus)) {
5217     // Nothing to do.
5218     Parser.Lex(); // Eat the '+'.
5219   }
5220 
5221   E = Parser.getTok().getLoc();
5222   int OffsetRegNum = tryParseRegister();
5223   if (OffsetRegNum == -1)
5224     return Error(E, "register expected");
5225 
5226   // If there's a shift operator, handle it.
5227   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
5228   unsigned ShiftImm = 0;
5229   if (Parser.getTok().is(AsmToken::Comma)) {
5230     Parser.Lex(); // Eat the ','.
5231     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
5232       return true;
5233   }
5234 
5235   // Now we should have the closing ']'
5236   if (Parser.getTok().isNot(AsmToken::RBrac))
5237     return Error(Parser.getTok().getLoc(), "']' expected");
5238   E = Parser.getTok().getEndLoc();
5239   Parser.Lex(); // Eat right bracket token.
5240 
5241   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
5242                                            ShiftType, ShiftImm, 0, isNegative,
5243                                            S, E));
5244 
5245   // If there's a pre-indexing writeback marker, '!', just add it as a token
5246   // operand.
5247   if (Parser.getTok().is(AsmToken::Exclaim)) {
5248     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5249     Parser.Lex(); // Eat the '!'.
5250   }
5251 
5252   return false;
5253 }
5254 
5255 /// parseMemRegOffsetShift - one of these two:
5256 ///   ( lsl | lsr | asr | ror ) , # shift_amount
5257 ///   rrx
5258 /// return true if it parses a shift otherwise it returns false.
parseMemRegOffsetShift(ARM_AM::ShiftOpc & St,unsigned & Amount)5259 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
5260                                           unsigned &Amount) {
5261   MCAsmParser &Parser = getParser();
5262   SMLoc Loc = Parser.getTok().getLoc();
5263   const AsmToken &Tok = Parser.getTok();
5264   if (Tok.isNot(AsmToken::Identifier))
5265     return Error(Loc, "illegal shift operator");
5266   StringRef ShiftName = Tok.getString();
5267   if (ShiftName == "lsl" || ShiftName == "LSL" ||
5268       ShiftName == "asl" || ShiftName == "ASL")
5269     St = ARM_AM::lsl;
5270   else if (ShiftName == "lsr" || ShiftName == "LSR")
5271     St = ARM_AM::lsr;
5272   else if (ShiftName == "asr" || ShiftName == "ASR")
5273     St = ARM_AM::asr;
5274   else if (ShiftName == "ror" || ShiftName == "ROR")
5275     St = ARM_AM::ror;
5276   else if (ShiftName == "rrx" || ShiftName == "RRX")
5277     St = ARM_AM::rrx;
5278   else
5279     return Error(Loc, "illegal shift operator");
5280   Parser.Lex(); // Eat shift type token.
5281 
5282   // rrx stands alone.
5283   Amount = 0;
5284   if (St != ARM_AM::rrx) {
5285     Loc = Parser.getTok().getLoc();
5286     // A '#' and a shift amount.
5287     const AsmToken &HashTok = Parser.getTok();
5288     if (HashTok.isNot(AsmToken::Hash) &&
5289         HashTok.isNot(AsmToken::Dollar))
5290       return Error(HashTok.getLoc(), "'#' expected");
5291     Parser.Lex(); // Eat hash token.
5292 
5293     const MCExpr *Expr;
5294     if (getParser().parseExpression(Expr))
5295       return true;
5296     // Range check the immediate.
5297     // lsl, ror: 0 <= imm <= 31
5298     // lsr, asr: 0 <= imm <= 32
5299     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5300     if (!CE)
5301       return Error(Loc, "shift amount must be an immediate");
5302     int64_t Imm = CE->getValue();
5303     if (Imm < 0 ||
5304         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
5305         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
5306       return Error(Loc, "immediate shift value out of range");
5307     // If <ShiftTy> #0, turn it into a no_shift.
5308     if (Imm == 0)
5309       St = ARM_AM::lsl;
5310     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
5311     if (Imm == 32)
5312       Imm = 0;
5313     Amount = Imm;
5314   }
5315 
5316   return false;
5317 }
5318 
5319 /// parseFPImm - A floating point immediate expression operand.
5320 OperandMatchResultTy
parseFPImm(OperandVector & Operands)5321 ARMAsmParser::parseFPImm(OperandVector &Operands) {
5322   MCAsmParser &Parser = getParser();
5323   // Anything that can accept a floating point constant as an operand
5324   // needs to go through here, as the regular parseExpression is
5325   // integer only.
5326   //
5327   // This routine still creates a generic Immediate operand, containing
5328   // a bitcast of the 64-bit floating point value. The various operands
5329   // that accept floats can check whether the value is valid for them
5330   // via the standard is*() predicates.
5331 
5332   SMLoc S = Parser.getTok().getLoc();
5333 
5334   if (Parser.getTok().isNot(AsmToken::Hash) &&
5335       Parser.getTok().isNot(AsmToken::Dollar))
5336     return MatchOperand_NoMatch;
5337 
5338   // Disambiguate the VMOV forms that can accept an FP immediate.
5339   // vmov.f32 <sreg>, #imm
5340   // vmov.f64 <dreg>, #imm
5341   // vmov.f32 <dreg>, #imm  @ vector f32x2
5342   // vmov.f32 <qreg>, #imm  @ vector f32x4
5343   //
5344   // There are also the NEON VMOV instructions which expect an
5345   // integer constant. Make sure we don't try to parse an FPImm
5346   // for these:
5347   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
5348   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
5349   bool isVmovf = TyOp.isToken() &&
5350                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64" ||
5351                   TyOp.getToken() == ".f16");
5352   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
5353   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
5354                                          Mnemonic.getToken() == "fconsts");
5355   if (!(isVmovf || isFconst))
5356     return MatchOperand_NoMatch;
5357 
5358   Parser.Lex(); // Eat '#' or '$'.
5359 
5360   // Handle negation, as that still comes through as a separate token.
5361   bool isNegative = false;
5362   if (Parser.getTok().is(AsmToken::Minus)) {
5363     isNegative = true;
5364     Parser.Lex();
5365   }
5366   const AsmToken &Tok = Parser.getTok();
5367   SMLoc Loc = Tok.getLoc();
5368   if (Tok.is(AsmToken::Real) && isVmovf) {
5369     APFloat RealVal(APFloat::IEEEsingle(), Tok.getString());
5370     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
5371     // If we had a '-' in front, toggle the sign bit.
5372     IntVal ^= (uint64_t)isNegative << 31;
5373     Parser.Lex(); // Eat the token.
5374     Operands.push_back(ARMOperand::CreateImm(
5375           MCConstantExpr::create(IntVal, getContext()),
5376           S, Parser.getTok().getLoc()));
5377     return MatchOperand_Success;
5378   }
5379   // Also handle plain integers. Instructions which allow floating point
5380   // immediates also allow a raw encoded 8-bit value.
5381   if (Tok.is(AsmToken::Integer) && isFconst) {
5382     int64_t Val = Tok.getIntVal();
5383     Parser.Lex(); // Eat the token.
5384     if (Val > 255 || Val < 0) {
5385       Error(Loc, "encoded floating point value out of range");
5386       return MatchOperand_ParseFail;
5387     }
5388     float RealVal = ARM_AM::getFPImmFloat(Val);
5389     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
5390 
5391     Operands.push_back(ARMOperand::CreateImm(
5392         MCConstantExpr::create(Val, getContext()), S,
5393         Parser.getTok().getLoc()));
5394     return MatchOperand_Success;
5395   }
5396 
5397   Error(Loc, "invalid floating point immediate");
5398   return MatchOperand_ParseFail;
5399 }
5400 
5401 /// Parse a arm instruction operand.  For now this parses the operand regardless
5402 /// of the mnemonic.
parseOperand(OperandVector & Operands,StringRef Mnemonic)5403 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
5404   MCAsmParser &Parser = getParser();
5405   SMLoc S, E;
5406 
5407   // Check if the current operand has a custom associated parser, if so, try to
5408   // custom parse the operand, or fallback to the general approach.
5409   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
5410   if (ResTy == MatchOperand_Success)
5411     return false;
5412   // If there wasn't a custom match, try the generic matcher below. Otherwise,
5413   // there was a match, but an error occurred, in which case, just return that
5414   // the operand parsing failed.
5415   if (ResTy == MatchOperand_ParseFail)
5416     return true;
5417 
5418   switch (getLexer().getKind()) {
5419   default:
5420     Error(Parser.getTok().getLoc(), "unexpected token in operand");
5421     return true;
5422   case AsmToken::Identifier: {
5423     // If we've seen a branch mnemonic, the next operand must be a label.  This
5424     // is true even if the label is a register name.  So "br r1" means branch to
5425     // label "r1".
5426     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
5427     if (!ExpectLabel) {
5428       if (!tryParseRegisterWithWriteBack(Operands))
5429         return false;
5430       int Res = tryParseShiftRegister(Operands);
5431       if (Res == 0) // success
5432         return false;
5433       else if (Res == -1) // irrecoverable error
5434         return true;
5435       // If this is VMRS, check for the apsr_nzcv operand.
5436       if (Mnemonic == "vmrs" &&
5437           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
5438         S = Parser.getTok().getLoc();
5439         Parser.Lex();
5440         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
5441         return false;
5442       }
5443     }
5444 
5445     // Fall though for the Identifier case that is not a register or a
5446     // special name.
5447     LLVM_FALLTHROUGH;
5448   }
5449   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
5450   case AsmToken::Integer: // things like 1f and 2b as a branch targets
5451   case AsmToken::String:  // quoted label names.
5452   case AsmToken::Dot: {   // . as a branch target
5453     // This was not a register so parse other operands that start with an
5454     // identifier (like labels) as expressions and create them as immediates.
5455     const MCExpr *IdVal;
5456     S = Parser.getTok().getLoc();
5457     if (getParser().parseExpression(IdVal))
5458       return true;
5459     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5460     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
5461     return false;
5462   }
5463   case AsmToken::LBrac:
5464     return parseMemory(Operands);
5465   case AsmToken::LCurly:
5466     return parseRegisterList(Operands);
5467   case AsmToken::Dollar:
5468   case AsmToken::Hash:
5469     // #42 -> immediate.
5470     S = Parser.getTok().getLoc();
5471     Parser.Lex();
5472 
5473     if (Parser.getTok().isNot(AsmToken::Colon)) {
5474       bool isNegative = Parser.getTok().is(AsmToken::Minus);
5475       const MCExpr *ImmVal;
5476       if (getParser().parseExpression(ImmVal))
5477         return true;
5478       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
5479       if (CE) {
5480         int32_t Val = CE->getValue();
5481         if (isNegative && Val == 0)
5482           ImmVal = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
5483                                           getContext());
5484       }
5485       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5486       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
5487 
5488       // There can be a trailing '!' on operands that we want as a separate
5489       // '!' Token operand. Handle that here. For example, the compatibility
5490       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
5491       if (Parser.getTok().is(AsmToken::Exclaim)) {
5492         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
5493                                                    Parser.getTok().getLoc()));
5494         Parser.Lex(); // Eat exclaim token
5495       }
5496       return false;
5497     }
5498     // w/ a ':' after the '#', it's just like a plain ':'.
5499     LLVM_FALLTHROUGH;
5500 
5501   case AsmToken::Colon: {
5502     S = Parser.getTok().getLoc();
5503     // ":lower16:" and ":upper16:" expression prefixes
5504     // FIXME: Check it's an expression prefix,
5505     // e.g. (FOO - :lower16:BAR) isn't legal.
5506     ARMMCExpr::VariantKind RefKind;
5507     if (parsePrefix(RefKind))
5508       return true;
5509 
5510     const MCExpr *SubExprVal;
5511     if (getParser().parseExpression(SubExprVal))
5512       return true;
5513 
5514     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
5515                                               getContext());
5516     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5517     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
5518     return false;
5519   }
5520   case AsmToken::Equal: {
5521     S = Parser.getTok().getLoc();
5522     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
5523       return Error(S, "unexpected token in operand");
5524     Parser.Lex(); // Eat '='
5525     const MCExpr *SubExprVal;
5526     if (getParser().parseExpression(SubExprVal))
5527       return true;
5528     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5529 
5530     // execute-only: we assume that assembly programmers know what they are
5531     // doing and allow literal pool creation here
5532     Operands.push_back(ARMOperand::CreateConstantPoolImm(SubExprVal, S, E));
5533     return false;
5534   }
5535   }
5536 }
5537 
5538 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
5539 //  :lower16: and :upper16:.
parsePrefix(ARMMCExpr::VariantKind & RefKind)5540 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
5541   MCAsmParser &Parser = getParser();
5542   RefKind = ARMMCExpr::VK_ARM_None;
5543 
5544   // consume an optional '#' (GNU compatibility)
5545   if (getLexer().is(AsmToken::Hash))
5546     Parser.Lex();
5547 
5548   // :lower16: and :upper16: modifiers
5549   assert(getLexer().is(AsmToken::Colon) && "expected a :");
5550   Parser.Lex(); // Eat ':'
5551 
5552   if (getLexer().isNot(AsmToken::Identifier)) {
5553     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
5554     return true;
5555   }
5556 
5557   enum {
5558     COFF = (1 << MCObjectFileInfo::IsCOFF),
5559     ELF = (1 << MCObjectFileInfo::IsELF),
5560     MACHO = (1 << MCObjectFileInfo::IsMachO),
5561     WASM = (1 << MCObjectFileInfo::IsWasm),
5562   };
5563   static const struct PrefixEntry {
5564     const char *Spelling;
5565     ARMMCExpr::VariantKind VariantKind;
5566     uint8_t SupportedFormats;
5567   } PrefixEntries[] = {
5568     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
5569     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
5570   };
5571 
5572   StringRef IDVal = Parser.getTok().getIdentifier();
5573 
5574   const auto &Prefix =
5575       std::find_if(std::begin(PrefixEntries), std::end(PrefixEntries),
5576                    [&IDVal](const PrefixEntry &PE) {
5577                       return PE.Spelling == IDVal;
5578                    });
5579   if (Prefix == std::end(PrefixEntries)) {
5580     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
5581     return true;
5582   }
5583 
5584   uint8_t CurrentFormat;
5585   switch (getContext().getObjectFileInfo()->getObjectFileType()) {
5586   case MCObjectFileInfo::IsMachO:
5587     CurrentFormat = MACHO;
5588     break;
5589   case MCObjectFileInfo::IsELF:
5590     CurrentFormat = ELF;
5591     break;
5592   case MCObjectFileInfo::IsCOFF:
5593     CurrentFormat = COFF;
5594     break;
5595   case MCObjectFileInfo::IsWasm:
5596     CurrentFormat = WASM;
5597     break;
5598   }
5599 
5600   if (~Prefix->SupportedFormats & CurrentFormat) {
5601     Error(Parser.getTok().getLoc(),
5602           "cannot represent relocation in the current file format");
5603     return true;
5604   }
5605 
5606   RefKind = Prefix->VariantKind;
5607   Parser.Lex();
5608 
5609   if (getLexer().isNot(AsmToken::Colon)) {
5610     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
5611     return true;
5612   }
5613   Parser.Lex(); // Eat the last ':'
5614 
5615   return false;
5616 }
5617 
5618 /// Given a mnemonic, split out possible predication code and carry
5619 /// setting letters to form a canonical mnemonic and flags.
5620 //
5621 // FIXME: Would be nice to autogen this.
5622 // FIXME: This is a bit of a maze of special cases.
splitMnemonic(StringRef Mnemonic,unsigned & PredicationCode,bool & CarrySetting,unsigned & ProcessorIMod,StringRef & ITMask)5623 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
5624                                       unsigned &PredicationCode,
5625                                       bool &CarrySetting,
5626                                       unsigned &ProcessorIMod,
5627                                       StringRef &ITMask) {
5628   PredicationCode = ARMCC::AL;
5629   CarrySetting = false;
5630   ProcessorIMod = 0;
5631 
5632   // Ignore some mnemonics we know aren't predicated forms.
5633   //
5634   // FIXME: Would be nice to autogen this.
5635   if ((Mnemonic == "movs" && isThumb()) ||
5636       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
5637       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
5638       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
5639       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
5640       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
5641       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
5642       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
5643       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
5644       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
5645       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
5646       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
5647       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
5648       Mnemonic.startswith("vsel") || Mnemonic == "vins" || Mnemonic == "vmovx" ||
5649       Mnemonic == "bxns"  || Mnemonic == "blxns" ||
5650       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
5651       Mnemonic == "vcmla" || Mnemonic == "vcadd" ||
5652       Mnemonic == "vfmal" || Mnemonic == "vfmsl")
5653     return Mnemonic;
5654 
5655   // First, split out any predication code. Ignore mnemonics we know aren't
5656   // predicated but do have a carry-set and so weren't caught above.
5657   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
5658       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
5659       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
5660       Mnemonic != "sbcs" && Mnemonic != "rscs") {
5661     unsigned CC = ARMCondCodeFromString(Mnemonic.substr(Mnemonic.size()-2));
5662     if (CC != ~0U) {
5663       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
5664       PredicationCode = CC;
5665     }
5666   }
5667 
5668   // Next, determine if we have a carry setting bit. We explicitly ignore all
5669   // the instructions we know end in 's'.
5670   if (Mnemonic.endswith("s") &&
5671       !(Mnemonic == "cps" || Mnemonic == "mls" ||
5672         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
5673         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
5674         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
5675         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
5676         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
5677         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
5678         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
5679         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
5680         Mnemonic == "bxns" || Mnemonic == "blxns" ||
5681         (Mnemonic == "movs" && isThumb()))) {
5682     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
5683     CarrySetting = true;
5684   }
5685 
5686   // The "cps" instruction can have a interrupt mode operand which is glued into
5687   // the mnemonic. Check if this is the case, split it and parse the imod op
5688   if (Mnemonic.startswith("cps")) {
5689     // Split out any imod code.
5690     unsigned IMod =
5691       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
5692       .Case("ie", ARM_PROC::IE)
5693       .Case("id", ARM_PROC::ID)
5694       .Default(~0U);
5695     if (IMod != ~0U) {
5696       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
5697       ProcessorIMod = IMod;
5698     }
5699   }
5700 
5701   // The "it" instruction has the condition mask on the end of the mnemonic.
5702   if (Mnemonic.startswith("it")) {
5703     ITMask = Mnemonic.slice(2, Mnemonic.size());
5704     Mnemonic = Mnemonic.slice(0, 2);
5705   }
5706 
5707   return Mnemonic;
5708 }
5709 
5710 /// Given a canonical mnemonic, determine if the instruction ever allows
5711 /// inclusion of carry set or predication code operands.
5712 //
5713 // FIXME: It would be nice to autogen this.
getMnemonicAcceptInfo(StringRef Mnemonic,StringRef FullInst,bool & CanAcceptCarrySet,bool & CanAcceptPredicationCode)5714 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
5715                                          bool &CanAcceptCarrySet,
5716                                          bool &CanAcceptPredicationCode) {
5717   CanAcceptCarrySet =
5718       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5719       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
5720       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
5721       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
5722       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
5723       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
5724       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
5725       (!isThumb() &&
5726        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
5727         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
5728 
5729   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
5730       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
5731       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
5732       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
5733       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
5734       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
5735       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
5736       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
5737       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
5738       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
5739       (FullInst.startswith("vmull") && FullInst.endswith(".p64")) ||
5740       Mnemonic == "vmovx" || Mnemonic == "vins" ||
5741       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
5742       Mnemonic == "vcmla" || Mnemonic == "vcadd" ||
5743       Mnemonic == "vfmal" || Mnemonic == "vfmsl" ||
5744       Mnemonic == "sb"    || Mnemonic == "ssbb"  ||
5745       Mnemonic == "pssbb") {
5746     // These mnemonics are never predicable
5747     CanAcceptPredicationCode = false;
5748   } else if (!isThumb()) {
5749     // Some instructions are only predicable in Thumb mode
5750     CanAcceptPredicationCode =
5751         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
5752         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
5753         Mnemonic != "dmb" && Mnemonic != "dfb" && Mnemonic != "dsb" &&
5754         Mnemonic != "isb" && Mnemonic != "pld" && Mnemonic != "pli" &&
5755         Mnemonic != "pldw" && Mnemonic != "ldc2" && Mnemonic != "ldc2l" &&
5756         Mnemonic != "stc2" && Mnemonic != "stc2l" &&
5757         Mnemonic != "tsb" &&
5758         !Mnemonic.startswith("rfe") && !Mnemonic.startswith("srs");
5759   } else if (isThumbOne()) {
5760     if (hasV6MOps())
5761       CanAcceptPredicationCode = Mnemonic != "movs";
5762     else
5763       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
5764   } else
5765     CanAcceptPredicationCode = true;
5766 }
5767 
5768 // Some Thumb instructions have two operand forms that are not
5769 // available as three operand, convert to two operand form if possible.
5770 //
5771 // FIXME: We would really like to be able to tablegen'erate this.
tryConvertingToTwoOperandForm(StringRef Mnemonic,bool CarrySetting,OperandVector & Operands)5772 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
5773                                                  bool CarrySetting,
5774                                                  OperandVector &Operands) {
5775   if (Operands.size() != 6)
5776     return;
5777 
5778   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5779         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
5780   if (!Op3.isReg() || !Op4.isReg())
5781     return;
5782 
5783   auto Op3Reg = Op3.getReg();
5784   auto Op4Reg = Op4.getReg();
5785 
5786   // For most Thumb2 cases we just generate the 3 operand form and reduce
5787   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
5788   // won't accept SP or PC so we do the transformation here taking care
5789   // with immediate range in the 'add sp, sp #imm' case.
5790   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
5791   if (isThumbTwo()) {
5792     if (Mnemonic != "add")
5793       return;
5794     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
5795                         (Op5.isReg() && Op5.getReg() == ARM::PC);
5796     if (!TryTransform) {
5797       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
5798                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
5799                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
5800                        Op5.isImm() && !Op5.isImm0_508s4());
5801     }
5802     if (!TryTransform)
5803       return;
5804   } else if (!isThumbOne())
5805     return;
5806 
5807   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
5808         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5809         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
5810         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
5811     return;
5812 
5813   // If first 2 operands of a 3 operand instruction are the same
5814   // then transform to 2 operand version of the same instruction
5815   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
5816   bool Transform = Op3Reg == Op4Reg;
5817 
5818   // For communtative operations, we might be able to transform if we swap
5819   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
5820   // as tADDrsp.
5821   const ARMOperand *LastOp = &Op5;
5822   bool Swap = false;
5823   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
5824       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
5825        Mnemonic == "and" || Mnemonic == "eor" ||
5826        Mnemonic == "adc" || Mnemonic == "orr")) {
5827     Swap = true;
5828     LastOp = &Op4;
5829     Transform = true;
5830   }
5831 
5832   // If both registers are the same then remove one of them from
5833   // the operand list, with certain exceptions.
5834   if (Transform) {
5835     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
5836     // 2 operand forms don't exist.
5837     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
5838         LastOp->isReg())
5839       Transform = false;
5840 
5841     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
5842     // 3-bits because the ARMARM says not to.
5843     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
5844       Transform = false;
5845   }
5846 
5847   if (Transform) {
5848     if (Swap)
5849       std::swap(Op4, Op5);
5850     Operands.erase(Operands.begin() + 3);
5851   }
5852 }
5853 
shouldOmitCCOutOperand(StringRef Mnemonic,OperandVector & Operands)5854 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
5855                                           OperandVector &Operands) {
5856   // FIXME: This is all horribly hacky. We really need a better way to deal
5857   // with optional operands like this in the matcher table.
5858 
5859   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
5860   // another does not. Specifically, the MOVW instruction does not. So we
5861   // special case it here and remove the defaulted (non-setting) cc_out
5862   // operand if that's the instruction we're trying to match.
5863   //
5864   // We do this as post-processing of the explicit operands rather than just
5865   // conditionally adding the cc_out in the first place because we need
5866   // to check the type of the parsed immediate operand.
5867   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
5868       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
5869       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
5870       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5871     return true;
5872 
5873   // Register-register 'add' for thumb does not have a cc_out operand
5874   // when there are only two register operands.
5875   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
5876       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5877       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5878       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5879     return true;
5880   // Register-register 'add' for thumb does not have a cc_out operand
5881   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
5882   // have to check the immediate range here since Thumb2 has a variant
5883   // that can handle a different range and has a cc_out operand.
5884   if (((isThumb() && Mnemonic == "add") ||
5885        (isThumbTwo() && Mnemonic == "sub")) &&
5886       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5887       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5888       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
5889       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5890       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
5891        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
5892     return true;
5893   // For Thumb2, add/sub immediate does not have a cc_out operand for the
5894   // imm0_4095 variant. That's the least-preferred variant when
5895   // selecting via the generic "add" mnemonic, so to know that we
5896   // should remove the cc_out operand, we have to explicitly check that
5897   // it's not one of the other variants. Ugh.
5898   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
5899       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5900       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5901       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5902     // Nest conditions rather than one big 'if' statement for readability.
5903     //
5904     // If both registers are low, we're in an IT block, and the immediate is
5905     // in range, we should use encoding T1 instead, which has a cc_out.
5906     if (inITBlock() &&
5907         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
5908         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
5909         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
5910       return false;
5911     // Check against T3. If the second register is the PC, this is an
5912     // alternate form of ADR, which uses encoding T4, so check for that too.
5913     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
5914         static_cast<ARMOperand &>(*Operands[5]).isT2SOImm())
5915       return false;
5916 
5917     // Otherwise, we use encoding T4, which does not have a cc_out
5918     // operand.
5919     return true;
5920   }
5921 
5922   // The thumb2 multiply instruction doesn't have a CCOut register, so
5923   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
5924   // use the 16-bit encoding or not.
5925   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
5926       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5927       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5928       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5929       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
5930       // If the registers aren't low regs, the destination reg isn't the
5931       // same as one of the source regs, or the cc_out operand is zero
5932       // outside of an IT block, we have to use the 32-bit encoding, so
5933       // remove the cc_out operand.
5934       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5935        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5936        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
5937        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5938                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
5939                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5940                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
5941     return true;
5942 
5943   // Also check the 'mul' syntax variant that doesn't specify an explicit
5944   // destination register.
5945   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
5946       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5947       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5948       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5949       // If the registers aren't low regs  or the cc_out operand is zero
5950       // outside of an IT block, we have to use the 32-bit encoding, so
5951       // remove the cc_out operand.
5952       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5953        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5954        !inITBlock()))
5955     return true;
5956 
5957   // Register-register 'add/sub' for thumb does not have a cc_out operand
5958   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
5959   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
5960   // right, this will result in better diagnostics (which operand is off)
5961   // anyway.
5962   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
5963       (Operands.size() == 5 || Operands.size() == 6) &&
5964       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5965       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
5966       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5967       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
5968        (Operands.size() == 6 &&
5969         static_cast<ARMOperand &>(*Operands[5]).isImm())))
5970     return true;
5971 
5972   return false;
5973 }
5974 
shouldOmitPredicateOperand(StringRef Mnemonic,OperandVector & Operands)5975 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
5976                                               OperandVector &Operands) {
5977   // VRINT{Z, X} have a predicate operand in VFP, but not in NEON
5978   unsigned RegIdx = 3;
5979   if ((Mnemonic == "vrintz" || Mnemonic == "vrintx") &&
5980       (static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32" ||
5981        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f16")) {
5982     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
5983         (static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32" ||
5984          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f16"))
5985       RegIdx = 4;
5986 
5987     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
5988         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
5989              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
5990          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
5991              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
5992       return true;
5993   }
5994   return false;
5995 }
5996 
isDataTypeToken(StringRef Tok)5997 static bool isDataTypeToken(StringRef Tok) {
5998   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
5999     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
6000     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
6001     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
6002     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
6003     Tok == ".f" || Tok == ".d";
6004 }
6005 
6006 // FIXME: This bit should probably be handled via an explicit match class
6007 // in the .td files that matches the suffix instead of having it be
6008 // a literal string token the way it is now.
doesIgnoreDataTypeSuffix(StringRef Mnemonic,StringRef DT)6009 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
6010   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
6011 }
6012 
6013 static void applyMnemonicAliases(StringRef &Mnemonic, uint64_t Features,
6014                                  unsigned VariantID);
6015 
6016 // The GNU assembler has aliases of ldrd and strd with the second register
6017 // omitted. We don't have a way to do that in tablegen, so fix it up here.
6018 //
6019 // We have to be careful to not emit an invalid Rt2 here, because the rest of
6020 // the assmebly parser could then generate confusing diagnostics refering to
6021 // it. If we do find anything that prevents us from doing the transformation we
6022 // bail out, and let the assembly parser report an error on the instruction as
6023 // it is written.
fixupGNULDRDAlias(StringRef Mnemonic,OperandVector & Operands)6024 void ARMAsmParser::fixupGNULDRDAlias(StringRef Mnemonic,
6025                                      OperandVector &Operands) {
6026   if (Mnemonic != "ldrd" && Mnemonic != "strd")
6027     return;
6028   if (Operands.size() < 4)
6029     return;
6030 
6031   ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
6032   ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6033 
6034   if (!Op2.isReg())
6035     return;
6036   if (!Op3.isMem())
6037     return;
6038 
6039   const MCRegisterClass &GPR = MRI->getRegClass(ARM::GPRRegClassID);
6040   if (!GPR.contains(Op2.getReg()))
6041     return;
6042 
6043   unsigned RtEncoding = MRI->getEncodingValue(Op2.getReg());
6044   if (!isThumb() && (RtEncoding & 1)) {
6045     // In ARM mode, the registers must be from an aligned pair, this
6046     // restriction does not apply in Thumb mode.
6047     return;
6048   }
6049   if (Op2.getReg() == ARM::PC)
6050     return;
6051   unsigned PairedReg = GPR.getRegister(RtEncoding + 1);
6052   if (!PairedReg || PairedReg == ARM::PC ||
6053       (PairedReg == ARM::SP && !hasV8Ops()))
6054     return;
6055 
6056   Operands.insert(
6057       Operands.begin() + 3,
6058       ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
6059 }
6060 
6061 /// Parse an arm instruction mnemonic followed by its operands.
ParseInstruction(ParseInstructionInfo & Info,StringRef Name,SMLoc NameLoc,OperandVector & Operands)6062 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
6063                                     SMLoc NameLoc, OperandVector &Operands) {
6064   MCAsmParser &Parser = getParser();
6065 
6066   // Apply mnemonic aliases before doing anything else, as the destination
6067   // mnemonic may include suffices and we want to handle them normally.
6068   // The generic tblgen'erated code does this later, at the start of
6069   // MatchInstructionImpl(), but that's too late for aliases that include
6070   // any sort of suffix.
6071   uint64_t AvailableFeatures = getAvailableFeatures();
6072   unsigned AssemblerDialect = getParser().getAssemblerDialect();
6073   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
6074 
6075   // First check for the ARM-specific .req directive.
6076   if (Parser.getTok().is(AsmToken::Identifier) &&
6077       Parser.getTok().getIdentifier() == ".req") {
6078     parseDirectiveReq(Name, NameLoc);
6079     // We always return 'error' for this, as we're done with this
6080     // statement and don't need to match the 'instruction."
6081     return true;
6082   }
6083 
6084   // Create the leading tokens for the mnemonic, split by '.' characters.
6085   size_t Start = 0, Next = Name.find('.');
6086   StringRef Mnemonic = Name.slice(Start, Next);
6087 
6088   // Split out the predication code and carry setting flag from the mnemonic.
6089   unsigned PredicationCode;
6090   unsigned ProcessorIMod;
6091   bool CarrySetting;
6092   StringRef ITMask;
6093   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
6094                            ProcessorIMod, ITMask);
6095 
6096   // In Thumb1, only the branch (B) instruction can be predicated.
6097   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
6098     return Error(NameLoc, "conditional execution not supported in Thumb1");
6099   }
6100 
6101   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
6102 
6103   // Handle the IT instruction ITMask. Convert it to a bitmask. This
6104   // is the mask as it will be for the IT encoding if the conditional
6105   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
6106   // where the conditional bit0 is zero, the instruction post-processing
6107   // will adjust the mask accordingly.
6108   if (Mnemonic == "it") {
6109     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
6110     if (ITMask.size() > 3) {
6111       return Error(Loc, "too many conditions on IT instruction");
6112     }
6113     unsigned Mask = 8;
6114     for (unsigned i = ITMask.size(); i != 0; --i) {
6115       char pos = ITMask[i - 1];
6116       if (pos != 't' && pos != 'e') {
6117         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
6118       }
6119       Mask >>= 1;
6120       if (ITMask[i - 1] == 't')
6121         Mask |= 8;
6122     }
6123     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
6124   }
6125 
6126   // FIXME: This is all a pretty gross hack. We should automatically handle
6127   // optional operands like this via tblgen.
6128 
6129   // Next, add the CCOut and ConditionCode operands, if needed.
6130   //
6131   // For mnemonics which can ever incorporate a carry setting bit or predication
6132   // code, our matching model involves us always generating CCOut and
6133   // ConditionCode operands to match the mnemonic "as written" and then we let
6134   // the matcher deal with finding the right instruction or generating an
6135   // appropriate error.
6136   bool CanAcceptCarrySet, CanAcceptPredicationCode;
6137   getMnemonicAcceptInfo(Mnemonic, Name, CanAcceptCarrySet, CanAcceptPredicationCode);
6138 
6139   // If we had a carry-set on an instruction that can't do that, issue an
6140   // error.
6141   if (!CanAcceptCarrySet && CarrySetting) {
6142     return Error(NameLoc, "instruction '" + Mnemonic +
6143                  "' can not set flags, but 's' suffix specified");
6144   }
6145   // If we had a predication code on an instruction that can't do that, issue an
6146   // error.
6147   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
6148     return Error(NameLoc, "instruction '" + Mnemonic +
6149                  "' is not predicable, but condition code specified");
6150   }
6151 
6152   // Add the carry setting operand, if necessary.
6153   if (CanAcceptCarrySet) {
6154     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
6155     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
6156                                                Loc));
6157   }
6158 
6159   // Add the predication code operand, if necessary.
6160   if (CanAcceptPredicationCode) {
6161     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
6162                                       CarrySetting);
6163     Operands.push_back(ARMOperand::CreateCondCode(
6164                          ARMCC::CondCodes(PredicationCode), Loc));
6165   }
6166 
6167   // Add the processor imod operand, if necessary.
6168   if (ProcessorIMod) {
6169     Operands.push_back(ARMOperand::CreateImm(
6170           MCConstantExpr::create(ProcessorIMod, getContext()),
6171                                  NameLoc, NameLoc));
6172   } else if (Mnemonic == "cps" && isMClass()) {
6173     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
6174   }
6175 
6176   // Add the remaining tokens in the mnemonic.
6177   while (Next != StringRef::npos) {
6178     Start = Next;
6179     Next = Name.find('.', Start + 1);
6180     StringRef ExtraToken = Name.slice(Start, Next);
6181 
6182     // Some NEON instructions have an optional datatype suffix that is
6183     // completely ignored. Check for that.
6184     if (isDataTypeToken(ExtraToken) &&
6185         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
6186       continue;
6187 
6188     // For for ARM mode generate an error if the .n qualifier is used.
6189     if (ExtraToken == ".n" && !isThumb()) {
6190       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
6191       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
6192                    "arm mode");
6193     }
6194 
6195     // The .n qualifier is always discarded as that is what the tables
6196     // and matcher expect.  In ARM mode the .w qualifier has no effect,
6197     // so discard it to avoid errors that can be caused by the matcher.
6198     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
6199       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
6200       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
6201     }
6202   }
6203 
6204   // Read the remaining operands.
6205   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6206     // Read the first operand.
6207     if (parseOperand(Operands, Mnemonic)) {
6208       return true;
6209     }
6210 
6211     while (parseOptionalToken(AsmToken::Comma)) {
6212       // Parse and remember the operand.
6213       if (parseOperand(Operands, Mnemonic)) {
6214         return true;
6215       }
6216     }
6217   }
6218 
6219   if (parseToken(AsmToken::EndOfStatement, "unexpected token in argument list"))
6220     return true;
6221 
6222   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
6223 
6224   // Some instructions, mostly Thumb, have forms for the same mnemonic that
6225   // do and don't have a cc_out optional-def operand. With some spot-checks
6226   // of the operand list, we can figure out which variant we're trying to
6227   // parse and adjust accordingly before actually matching. We shouldn't ever
6228   // try to remove a cc_out operand that was explicitly set on the
6229   // mnemonic, of course (CarrySetting == true). Reason number #317 the
6230   // table driven matcher doesn't fit well with the ARM instruction set.
6231   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
6232     Operands.erase(Operands.begin() + 1);
6233 
6234   // Some instructions have the same mnemonic, but don't always
6235   // have a predicate. Distinguish them here and delete the
6236   // predicate if needed.
6237   if (PredicationCode == ARMCC::AL &&
6238       shouldOmitPredicateOperand(Mnemonic, Operands))
6239     Operands.erase(Operands.begin() + 1);
6240 
6241   // ARM mode 'blx' need special handling, as the register operand version
6242   // is predicable, but the label operand version is not. So, we can't rely
6243   // on the Mnemonic based checking to correctly figure out when to put
6244   // a k_CondCode operand in the list. If we're trying to match the label
6245   // version, remove the k_CondCode operand here.
6246   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
6247       static_cast<ARMOperand &>(*Operands[2]).isImm())
6248     Operands.erase(Operands.begin() + 1);
6249 
6250   // Adjust operands of ldrexd/strexd to MCK_GPRPair.
6251   // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
6252   // a single GPRPair reg operand is used in the .td file to replace the two
6253   // GPRs. However, when parsing from asm, the two GRPs cannot be automatically
6254   // expressed as a GPRPair, so we have to manually merge them.
6255   // FIXME: We would really like to be able to tablegen'erate this.
6256   if (!isThumb() && Operands.size() > 4 &&
6257       (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
6258        Mnemonic == "stlexd")) {
6259     bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
6260     unsigned Idx = isLoad ? 2 : 3;
6261     ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
6262     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
6263 
6264     const MCRegisterClass& MRC = MRI->getRegClass(ARM::GPRRegClassID);
6265     // Adjust only if Op1 and Op2 are GPRs.
6266     if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
6267         MRC.contains(Op2.getReg())) {
6268       unsigned Reg1 = Op1.getReg();
6269       unsigned Reg2 = Op2.getReg();
6270       unsigned Rt = MRI->getEncodingValue(Reg1);
6271       unsigned Rt2 = MRI->getEncodingValue(Reg2);
6272 
6273       // Rt2 must be Rt + 1 and Rt must be even.
6274       if (Rt + 1 != Rt2 || (Rt & 1)) {
6275         return Error(Op2.getStartLoc(),
6276                      isLoad ? "destination operands must be sequential"
6277                             : "source operands must be sequential");
6278       }
6279       unsigned NewReg = MRI->getMatchingSuperReg(Reg1, ARM::gsub_0,
6280           &(MRI->getRegClass(ARM::GPRPairRegClassID)));
6281       Operands[Idx] =
6282           ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
6283       Operands.erase(Operands.begin() + Idx + 1);
6284     }
6285   }
6286 
6287   // GNU Assembler extension (compatibility).
6288   fixupGNULDRDAlias(Mnemonic, Operands);
6289 
6290   // FIXME: As said above, this is all a pretty gross hack.  This instruction
6291   // does not fit with other "subs" and tblgen.
6292   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
6293   // so the Mnemonic is the original name "subs" and delete the predicate
6294   // operand so it will match the table entry.
6295   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
6296       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6297       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
6298       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6299       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
6300       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
6301     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
6302     Operands.erase(Operands.begin() + 1);
6303   }
6304   return false;
6305 }
6306 
6307 // Validate context-sensitive operand constraints.
6308 
6309 // return 'true' if register list contains non-low GPR registers,
6310 // 'false' otherwise. If Reg is in the register list or is HiReg, set
6311 // 'containsReg' to true.
checkLowRegisterList(const MCInst & Inst,unsigned OpNo,unsigned Reg,unsigned HiReg,bool & containsReg)6312 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
6313                                  unsigned Reg, unsigned HiReg,
6314                                  bool &containsReg) {
6315   containsReg = false;
6316   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
6317     unsigned OpReg = Inst.getOperand(i).getReg();
6318     if (OpReg == Reg)
6319       containsReg = true;
6320     // Anything other than a low register isn't legal here.
6321     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
6322       return true;
6323   }
6324   return false;
6325 }
6326 
6327 // Check if the specified regisgter is in the register list of the inst,
6328 // starting at the indicated operand number.
listContainsReg(const MCInst & Inst,unsigned OpNo,unsigned Reg)6329 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
6330   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
6331     unsigned OpReg = Inst.getOperand(i).getReg();
6332     if (OpReg == Reg)
6333       return true;
6334   }
6335   return false;
6336 }
6337 
6338 // Return true if instruction has the interesting property of being
6339 // allowed in IT blocks, but not being predicable.
instIsBreakpoint(const MCInst & Inst)6340 static bool instIsBreakpoint(const MCInst &Inst) {
6341     return Inst.getOpcode() == ARM::tBKPT ||
6342            Inst.getOpcode() == ARM::BKPT ||
6343            Inst.getOpcode() == ARM::tHLT ||
6344            Inst.getOpcode() == ARM::HLT;
6345 }
6346 
validatetLDMRegList(const MCInst & Inst,const OperandVector & Operands,unsigned ListNo,bool IsARPop)6347 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
6348                                        const OperandVector &Operands,
6349                                        unsigned ListNo, bool IsARPop) {
6350   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6351   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6352 
6353   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6354   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
6355   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6356 
6357   if (!IsARPop && ListContainsSP)
6358     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6359                  "SP may not be in the register list");
6360   else if (ListContainsPC && ListContainsLR)
6361     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6362                  "PC and LR may not be in the register list simultaneously");
6363   return false;
6364 }
6365 
validatetSTMRegList(const MCInst & Inst,const OperandVector & Operands,unsigned ListNo)6366 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
6367                                        const OperandVector &Operands,
6368                                        unsigned ListNo) {
6369   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6370   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6371 
6372   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6373   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6374 
6375   if (ListContainsSP && ListContainsPC)
6376     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6377                  "SP and PC may not be in the register list");
6378   else if (ListContainsSP)
6379     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6380                  "SP may not be in the register list");
6381   else if (ListContainsPC)
6382     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6383                  "PC may not be in the register list");
6384   return false;
6385 }
6386 
validateLDRDSTRD(MCInst & Inst,const OperandVector & Operands,bool Load,bool ARMMode,bool Writeback)6387 bool ARMAsmParser::validateLDRDSTRD(MCInst &Inst,
6388                                     const OperandVector &Operands,
6389                                     bool Load, bool ARMMode, bool Writeback) {
6390   unsigned RtIndex = Load || !Writeback ? 0 : 1;
6391   unsigned Rt = MRI->getEncodingValue(Inst.getOperand(RtIndex).getReg());
6392   unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(RtIndex + 1).getReg());
6393 
6394   if (ARMMode) {
6395     // Rt can't be R14.
6396     if (Rt == 14)
6397       return Error(Operands[3]->getStartLoc(),
6398                   "Rt can't be R14");
6399 
6400     // Rt must be even-numbered.
6401     if ((Rt & 1) == 1)
6402       return Error(Operands[3]->getStartLoc(),
6403                    "Rt must be even-numbered");
6404 
6405     // Rt2 must be Rt + 1.
6406     if (Rt2 != Rt + 1) {
6407       if (Load)
6408         return Error(Operands[3]->getStartLoc(),
6409                      "destination operands must be sequential");
6410       else
6411         return Error(Operands[3]->getStartLoc(),
6412                      "source operands must be sequential");
6413     }
6414 
6415     // FIXME: Diagnose m == 15
6416     // FIXME: Diagnose ldrd with m == t || m == t2.
6417   }
6418 
6419   if (!ARMMode && Load) {
6420     if (Rt2 == Rt)
6421       return Error(Operands[3]->getStartLoc(),
6422                    "destination operands can't be identical");
6423   }
6424 
6425   if (Writeback) {
6426     unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
6427 
6428     if (Rn == Rt || Rn == Rt2) {
6429       if (Load)
6430         return Error(Operands[3]->getStartLoc(),
6431                      "base register needs to be different from destination "
6432                      "registers");
6433       else
6434         return Error(Operands[3]->getStartLoc(),
6435                      "source register and base register can't be identical");
6436     }
6437 
6438     // FIXME: Diagnose ldrd/strd with writeback and n == 15.
6439     // (Except the immediate form of ldrd?)
6440   }
6441 
6442   return false;
6443 }
6444 
6445 
6446 // FIXME: We would really like to be able to tablegen'erate this.
validateInstruction(MCInst & Inst,const OperandVector & Operands)6447 bool ARMAsmParser::validateInstruction(MCInst &Inst,
6448                                        const OperandVector &Operands) {
6449   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
6450   SMLoc Loc = Operands[0]->getStartLoc();
6451 
6452   // Check the IT block state first.
6453   // NOTE: BKPT and HLT instructions have the interesting property of being
6454   // allowed in IT blocks, but not being predicable. They just always execute.
6455   if (inITBlock() && !instIsBreakpoint(Inst)) {
6456     // The instruction must be predicable.
6457     if (!MCID.isPredicable())
6458       return Error(Loc, "instructions in IT block must be predicable");
6459     ARMCC::CondCodes Cond = ARMCC::CondCodes(
6460         Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm());
6461     if (Cond != currentITCond()) {
6462       // Find the condition code Operand to get its SMLoc information.
6463       SMLoc CondLoc;
6464       for (unsigned I = 1; I < Operands.size(); ++I)
6465         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
6466           CondLoc = Operands[I]->getStartLoc();
6467       return Error(CondLoc, "incorrect condition in IT block; got '" +
6468                                 StringRef(ARMCondCodeToString(Cond)) +
6469                                 "', but expected '" +
6470                                 ARMCondCodeToString(currentITCond()) + "'");
6471     }
6472   // Check for non-'al' condition codes outside of the IT block.
6473   } else if (isThumbTwo() && MCID.isPredicable() &&
6474              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6475              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
6476              Inst.getOpcode() != ARM::t2Bcc) {
6477     return Error(Loc, "predicated instructions must be in IT block");
6478   } else if (!isThumb() && !useImplicitITARM() && MCID.isPredicable() &&
6479              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6480                  ARMCC::AL) {
6481     return Warning(Loc, "predicated instructions should be in IT block");
6482   }
6483 
6484   // PC-setting instructions in an IT block, but not the last instruction of
6485   // the block, are UNPREDICTABLE.
6486   if (inExplicitITBlock() && !lastInITBlock() && isITBlockTerminator(Inst)) {
6487     return Error(Loc, "instruction must be outside of IT block or the last instruction in an IT block");
6488   }
6489 
6490   const unsigned Opcode = Inst.getOpcode();
6491   switch (Opcode) {
6492   case ARM::t2IT: {
6493     // Encoding is unpredictable if it ever results in a notional 'NV'
6494     // predicate. Since we don't parse 'NV' directly this means an 'AL'
6495     // predicate with an "else" mask bit.
6496     unsigned Cond = Inst.getOperand(0).getImm();
6497     unsigned Mask = Inst.getOperand(1).getImm();
6498 
6499     // Mask hasn't been modified to the IT instruction encoding yet so
6500     // conditions only allowing a 't' are a block of 1s starting at bit 3
6501     // followed by all 0s. Easiest way is to just list the 4 possibilities.
6502     if (Cond == ARMCC::AL && Mask != 8 && Mask != 12 && Mask != 14 &&
6503         Mask != 15)
6504       return Error(Loc, "unpredictable IT predicate sequence");
6505     break;
6506   }
6507   case ARM::LDRD:
6508     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/true,
6509                          /*Writeback*/false))
6510       return true;
6511     break;
6512   case ARM::LDRD_PRE:
6513   case ARM::LDRD_POST:
6514     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/true,
6515                          /*Writeback*/true))
6516       return true;
6517     break;
6518   case ARM::t2LDRDi8:
6519     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/false,
6520                          /*Writeback*/false))
6521       return true;
6522     break;
6523   case ARM::t2LDRD_PRE:
6524   case ARM::t2LDRD_POST:
6525     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/false,
6526                          /*Writeback*/true))
6527       return true;
6528     break;
6529   case ARM::t2BXJ: {
6530     const unsigned RmReg = Inst.getOperand(0).getReg();
6531     // Rm = SP is no longer unpredictable in v8-A
6532     if (RmReg == ARM::SP && !hasV8Ops())
6533       return Error(Operands[2]->getStartLoc(),
6534                    "r13 (SP) is an unpredictable operand to BXJ");
6535     return false;
6536   }
6537   case ARM::STRD:
6538     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/true,
6539                          /*Writeback*/false))
6540       return true;
6541     break;
6542   case ARM::STRD_PRE:
6543   case ARM::STRD_POST:
6544     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/true,
6545                          /*Writeback*/true))
6546       return true;
6547     break;
6548   case ARM::t2STRD_PRE:
6549   case ARM::t2STRD_POST:
6550     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/false,
6551                          /*Writeback*/true))
6552       return true;
6553     break;
6554   case ARM::STR_PRE_IMM:
6555   case ARM::STR_PRE_REG:
6556   case ARM::t2STR_PRE:
6557   case ARM::STR_POST_IMM:
6558   case ARM::STR_POST_REG:
6559   case ARM::t2STR_POST:
6560   case ARM::STRH_PRE:
6561   case ARM::t2STRH_PRE:
6562   case ARM::STRH_POST:
6563   case ARM::t2STRH_POST:
6564   case ARM::STRB_PRE_IMM:
6565   case ARM::STRB_PRE_REG:
6566   case ARM::t2STRB_PRE:
6567   case ARM::STRB_POST_IMM:
6568   case ARM::STRB_POST_REG:
6569   case ARM::t2STRB_POST: {
6570     // Rt must be different from Rn.
6571     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6572     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6573 
6574     if (Rt == Rn)
6575       return Error(Operands[3]->getStartLoc(),
6576                    "source register and base register can't be identical");
6577     return false;
6578   }
6579   case ARM::LDR_PRE_IMM:
6580   case ARM::LDR_PRE_REG:
6581   case ARM::t2LDR_PRE:
6582   case ARM::LDR_POST_IMM:
6583   case ARM::LDR_POST_REG:
6584   case ARM::t2LDR_POST:
6585   case ARM::LDRH_PRE:
6586   case ARM::t2LDRH_PRE:
6587   case ARM::LDRH_POST:
6588   case ARM::t2LDRH_POST:
6589   case ARM::LDRSH_PRE:
6590   case ARM::t2LDRSH_PRE:
6591   case ARM::LDRSH_POST:
6592   case ARM::t2LDRSH_POST:
6593   case ARM::LDRB_PRE_IMM:
6594   case ARM::LDRB_PRE_REG:
6595   case ARM::t2LDRB_PRE:
6596   case ARM::LDRB_POST_IMM:
6597   case ARM::LDRB_POST_REG:
6598   case ARM::t2LDRB_POST:
6599   case ARM::LDRSB_PRE:
6600   case ARM::t2LDRSB_PRE:
6601   case ARM::LDRSB_POST:
6602   case ARM::t2LDRSB_POST: {
6603     // Rt must be different from Rn.
6604     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6605     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6606 
6607     if (Rt == Rn)
6608       return Error(Operands[3]->getStartLoc(),
6609                    "destination register and base register can't be identical");
6610     return false;
6611   }
6612   case ARM::SBFX:
6613   case ARM::t2SBFX:
6614   case ARM::UBFX:
6615   case ARM::t2UBFX: {
6616     // Width must be in range [1, 32-lsb].
6617     unsigned LSB = Inst.getOperand(2).getImm();
6618     unsigned Widthm1 = Inst.getOperand(3).getImm();
6619     if (Widthm1 >= 32 - LSB)
6620       return Error(Operands[5]->getStartLoc(),
6621                    "bitfield width must be in range [1,32-lsb]");
6622     return false;
6623   }
6624   // Notionally handles ARM::tLDMIA_UPD too.
6625   case ARM::tLDMIA: {
6626     // If we're parsing Thumb2, the .w variant is available and handles
6627     // most cases that are normally illegal for a Thumb1 LDM instruction.
6628     // We'll make the transformation in processInstruction() if necessary.
6629     //
6630     // Thumb LDM instructions are writeback iff the base register is not
6631     // in the register list.
6632     unsigned Rn = Inst.getOperand(0).getReg();
6633     bool HasWritebackToken =
6634         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6635          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
6636     bool ListContainsBase;
6637     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
6638       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
6639                    "registers must be in range r0-r7");
6640     // If we should have writeback, then there should be a '!' token.
6641     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
6642       return Error(Operands[2]->getStartLoc(),
6643                    "writeback operator '!' expected");
6644     // If we should not have writeback, there must not be a '!'. This is
6645     // true even for the 32-bit wide encodings.
6646     if (ListContainsBase && HasWritebackToken)
6647       return Error(Operands[3]->getStartLoc(),
6648                    "writeback operator '!' not allowed when base register "
6649                    "in register list");
6650 
6651     if (validatetLDMRegList(Inst, Operands, 3))
6652       return true;
6653     break;
6654   }
6655   case ARM::LDMIA_UPD:
6656   case ARM::LDMDB_UPD:
6657   case ARM::LDMIB_UPD:
6658   case ARM::LDMDA_UPD:
6659     // ARM variants loading and updating the same register are only officially
6660     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
6661     if (!hasV7Ops())
6662       break;
6663     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6664       return Error(Operands.back()->getStartLoc(),
6665                    "writeback register not allowed in register list");
6666     break;
6667   case ARM::t2LDMIA:
6668   case ARM::t2LDMDB:
6669     if (validatetLDMRegList(Inst, Operands, 3))
6670       return true;
6671     break;
6672   case ARM::t2STMIA:
6673   case ARM::t2STMDB:
6674     if (validatetSTMRegList(Inst, Operands, 3))
6675       return true;
6676     break;
6677   case ARM::t2LDMIA_UPD:
6678   case ARM::t2LDMDB_UPD:
6679   case ARM::t2STMIA_UPD:
6680   case ARM::t2STMDB_UPD:
6681     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6682       return Error(Operands.back()->getStartLoc(),
6683                    "writeback register not allowed in register list");
6684 
6685     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
6686       if (validatetLDMRegList(Inst, Operands, 3))
6687         return true;
6688     } else {
6689       if (validatetSTMRegList(Inst, Operands, 3))
6690         return true;
6691     }
6692     break;
6693 
6694   case ARM::sysLDMIA_UPD:
6695   case ARM::sysLDMDA_UPD:
6696   case ARM::sysLDMDB_UPD:
6697   case ARM::sysLDMIB_UPD:
6698     if (!listContainsReg(Inst, 3, ARM::PC))
6699       return Error(Operands[4]->getStartLoc(),
6700                    "writeback register only allowed on system LDM "
6701                    "if PC in register-list");
6702     break;
6703   case ARM::sysSTMIA_UPD:
6704   case ARM::sysSTMDA_UPD:
6705   case ARM::sysSTMDB_UPD:
6706   case ARM::sysSTMIB_UPD:
6707     return Error(Operands[2]->getStartLoc(),
6708                  "system STM cannot have writeback register");
6709   case ARM::tMUL:
6710     // The second source operand must be the same register as the destination
6711     // operand.
6712     //
6713     // In this case, we must directly check the parsed operands because the
6714     // cvtThumbMultiply() function is written in such a way that it guarantees
6715     // this first statement is always true for the new Inst.  Essentially, the
6716     // destination is unconditionally copied into the second source operand
6717     // without checking to see if it matches what we actually parsed.
6718     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
6719                                  ((ARMOperand &)*Operands[5]).getReg()) &&
6720         (((ARMOperand &)*Operands[3]).getReg() !=
6721          ((ARMOperand &)*Operands[4]).getReg())) {
6722       return Error(Operands[3]->getStartLoc(),
6723                    "destination register must match source register");
6724     }
6725     break;
6726 
6727   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
6728   // so only issue a diagnostic for thumb1. The instructions will be
6729   // switched to the t2 encodings in processInstruction() if necessary.
6730   case ARM::tPOP: {
6731     bool ListContainsBase;
6732     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
6733         !isThumbTwo())
6734       return Error(Operands[2]->getStartLoc(),
6735                    "registers must be in range r0-r7 or pc");
6736     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
6737       return true;
6738     break;
6739   }
6740   case ARM::tPUSH: {
6741     bool ListContainsBase;
6742     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
6743         !isThumbTwo())
6744       return Error(Operands[2]->getStartLoc(),
6745                    "registers must be in range r0-r7 or lr");
6746     if (validatetSTMRegList(Inst, Operands, 2))
6747       return true;
6748     break;
6749   }
6750   case ARM::tSTMIA_UPD: {
6751     bool ListContainsBase, InvalidLowList;
6752     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
6753                                           0, ListContainsBase);
6754     if (InvalidLowList && !isThumbTwo())
6755       return Error(Operands[4]->getStartLoc(),
6756                    "registers must be in range r0-r7");
6757 
6758     // This would be converted to a 32-bit stm, but that's not valid if the
6759     // writeback register is in the list.
6760     if (InvalidLowList && ListContainsBase)
6761       return Error(Operands[4]->getStartLoc(),
6762                    "writeback operator '!' not allowed when base register "
6763                    "in register list");
6764 
6765     if (validatetSTMRegList(Inst, Operands, 4))
6766       return true;
6767     break;
6768   }
6769   case ARM::tADDrSP:
6770     // If the non-SP source operand and the destination operand are not the
6771     // same, we need thumb2 (for the wide encoding), or we have an error.
6772     if (!isThumbTwo() &&
6773         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
6774       return Error(Operands[4]->getStartLoc(),
6775                    "source register must be the same as destination");
6776     }
6777     break;
6778 
6779   // Final range checking for Thumb unconditional branch instructions.
6780   case ARM::tB:
6781     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
6782       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6783     break;
6784   case ARM::t2B: {
6785     int op = (Operands[2]->isImm()) ? 2 : 3;
6786     if (!static_cast<ARMOperand &>(*Operands[op]).isSignedOffset<24, 1>())
6787       return Error(Operands[op]->getStartLoc(), "branch target out of range");
6788     break;
6789   }
6790   // Final range checking for Thumb conditional branch instructions.
6791   case ARM::tBcc:
6792     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
6793       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6794     break;
6795   case ARM::t2Bcc: {
6796     int Op = (Operands[2]->isImm()) ? 2 : 3;
6797     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
6798       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
6799     break;
6800   }
6801   case ARM::tCBZ:
6802   case ARM::tCBNZ: {
6803     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<6, 1>())
6804       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6805     break;
6806   }
6807   case ARM::MOVi16:
6808   case ARM::MOVTi16:
6809   case ARM::t2MOVi16:
6810   case ARM::t2MOVTi16:
6811     {
6812     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
6813     // especially when we turn it into a movw and the expression <symbol> does
6814     // not have a :lower16: or :upper16 as part of the expression.  We don't
6815     // want the behavior of silently truncating, which can be unexpected and
6816     // lead to bugs that are difficult to find since this is an easy mistake
6817     // to make.
6818     int i = (Operands[3]->isImm()) ? 3 : 4;
6819     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
6820     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
6821     if (CE) break;
6822     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
6823     if (!E) break;
6824     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
6825     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
6826                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
6827       return Error(
6828           Op.getStartLoc(),
6829           "immediate expression for mov requires :lower16: or :upper16");
6830     break;
6831   }
6832   case ARM::HINT:
6833   case ARM::t2HINT: {
6834     unsigned Imm8 = Inst.getOperand(0).getImm();
6835     unsigned Pred = Inst.getOperand(1).getImm();
6836     // ESB is not predicable (pred must be AL). Without the RAS extension, this
6837     // behaves as any other unallocated hint.
6838     if (Imm8 == 0x10 && Pred != ARMCC::AL && hasRAS())
6839       return Error(Operands[1]->getStartLoc(), "instruction 'esb' is not "
6840                                                "predicable, but condition "
6841                                                "code specified");
6842     if (Imm8 == 0x14 && Pred != ARMCC::AL)
6843       return Error(Operands[1]->getStartLoc(), "instruction 'csdb' is not "
6844                                                "predicable, but condition "
6845                                                "code specified");
6846     break;
6847   }
6848   case ARM::DSB:
6849   case ARM::t2DSB: {
6850 
6851     if (Inst.getNumOperands() < 2)
6852       break;
6853 
6854     unsigned Option = Inst.getOperand(0).getImm();
6855     unsigned Pred = Inst.getOperand(1).getImm();
6856 
6857     // SSBB and PSSBB (DSB #0|#4) are not predicable (pred must be AL).
6858     if (Option == 0 && Pred != ARMCC::AL)
6859       return Error(Operands[1]->getStartLoc(),
6860                    "instruction 'ssbb' is not predicable, but condition code "
6861                    "specified");
6862     if (Option == 4 && Pred != ARMCC::AL)
6863       return Error(Operands[1]->getStartLoc(),
6864                    "instruction 'pssbb' is not predicable, but condition code "
6865                    "specified");
6866     break;
6867   }
6868   case ARM::VMOVRRS: {
6869     // Source registers must be sequential.
6870     const unsigned Sm = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6871     const unsigned Sm1 = MRI->getEncodingValue(Inst.getOperand(3).getReg());
6872     if (Sm1 != Sm + 1)
6873       return Error(Operands[5]->getStartLoc(),
6874                    "source operands must be sequential");
6875     break;
6876   }
6877   case ARM::VMOVSRR: {
6878     // Destination registers must be sequential.
6879     const unsigned Sm = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6880     const unsigned Sm1 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6881     if (Sm1 != Sm + 1)
6882       return Error(Operands[3]->getStartLoc(),
6883                    "destination operands must be sequential");
6884     break;
6885   }
6886   case ARM::VLDMDIA:
6887   case ARM::VSTMDIA: {
6888     ARMOperand &Op = static_cast<ARMOperand&>(*Operands[3]);
6889     auto &RegList = Op.getRegList();
6890     if (RegList.size() < 1 || RegList.size() > 16)
6891       return Error(Operands[3]->getStartLoc(),
6892                    "list of registers must be at least 1 and at most 16");
6893     break;
6894   }
6895   }
6896 
6897   return false;
6898 }
6899 
getRealVSTOpcode(unsigned Opc,unsigned & Spacing)6900 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
6901   switch(Opc) {
6902   default: llvm_unreachable("unexpected opcode!");
6903   // VST1LN
6904   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6905   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6906   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6907   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6908   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6909   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6910   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
6911   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
6912   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
6913 
6914   // VST2LN
6915   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6916   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6917   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6918   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6919   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6920 
6921   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6922   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6923   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6924   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6925   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6926 
6927   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
6928   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
6929   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
6930   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
6931   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
6932 
6933   // VST3LN
6934   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6935   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6936   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6937   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
6938   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6939   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6940   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6941   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6942   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
6943   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6944   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
6945   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
6946   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
6947   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
6948   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
6949 
6950   // VST3
6951   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6952   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6953   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6954   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6955   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6956   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6957   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6958   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6959   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6960   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6961   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6962   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6963   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
6964   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
6965   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
6966   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
6967   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
6968   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
6969 
6970   // VST4LN
6971   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6972   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6973   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6974   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
6975   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6976   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6977   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6978   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6979   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
6980   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6981   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
6982   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
6983   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
6984   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
6985   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
6986 
6987   // VST4
6988   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6989   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6990   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6991   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6992   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6993   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6994   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6995   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6996   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6997   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6998   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6999   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
7000   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
7001   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
7002   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
7003   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
7004   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
7005   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
7006   }
7007 }
7008 
getRealVLDOpcode(unsigned Opc,unsigned & Spacing)7009 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
7010   switch(Opc) {
7011   default: llvm_unreachable("unexpected opcode!");
7012   // VLD1LN
7013   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
7014   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
7015   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
7016   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
7017   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
7018   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
7019   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
7020   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
7021   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
7022 
7023   // VLD2LN
7024   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
7025   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
7026   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
7027   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
7028   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
7029   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
7030   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
7031   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
7032   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
7033   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
7034   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
7035   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
7036   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
7037   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
7038   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
7039 
7040   // VLD3DUP
7041   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
7042   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
7043   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
7044   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
7045   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
7046   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
7047   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
7048   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
7049   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
7050   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
7051   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
7052   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
7053   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
7054   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
7055   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
7056   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
7057   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
7058   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
7059 
7060   // VLD3LN
7061   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
7062   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
7063   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
7064   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
7065   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
7066   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
7067   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
7068   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
7069   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
7070   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
7071   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
7072   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
7073   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
7074   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
7075   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
7076 
7077   // VLD3
7078   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
7079   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
7080   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
7081   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
7082   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
7083   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
7084   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
7085   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
7086   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
7087   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
7088   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
7089   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
7090   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
7091   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
7092   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
7093   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
7094   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
7095   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
7096 
7097   // VLD4LN
7098   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
7099   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
7100   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
7101   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
7102   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
7103   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
7104   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
7105   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
7106   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
7107   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
7108   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
7109   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
7110   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
7111   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
7112   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
7113 
7114   // VLD4DUP
7115   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
7116   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
7117   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
7118   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
7119   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
7120   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
7121   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
7122   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
7123   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
7124   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
7125   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
7126   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
7127   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
7128   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
7129   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
7130   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
7131   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
7132   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
7133 
7134   // VLD4
7135   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
7136   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
7137   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
7138   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
7139   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
7140   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
7141   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
7142   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
7143   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
7144   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
7145   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
7146   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
7147   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
7148   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
7149   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
7150   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
7151   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
7152   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
7153   }
7154 }
7155 
processInstruction(MCInst & Inst,const OperandVector & Operands,MCStreamer & Out)7156 bool ARMAsmParser::processInstruction(MCInst &Inst,
7157                                       const OperandVector &Operands,
7158                                       MCStreamer &Out) {
7159   // Check if we have the wide qualifier, because if it's present we
7160   // must avoid selecting a 16-bit thumb instruction.
7161   bool HasWideQualifier = false;
7162   for (auto &Op : Operands) {
7163     ARMOperand &ARMOp = static_cast<ARMOperand&>(*Op);
7164     if (ARMOp.isToken() && ARMOp.getToken() == ".w") {
7165       HasWideQualifier = true;
7166       break;
7167     }
7168   }
7169 
7170   switch (Inst.getOpcode()) {
7171   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
7172   case ARM::LDRT_POST:
7173   case ARM::LDRBT_POST: {
7174     const unsigned Opcode =
7175       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
7176                                            : ARM::LDRBT_POST_IMM;
7177     MCInst TmpInst;
7178     TmpInst.setOpcode(Opcode);
7179     TmpInst.addOperand(Inst.getOperand(0));
7180     TmpInst.addOperand(Inst.getOperand(1));
7181     TmpInst.addOperand(Inst.getOperand(1));
7182     TmpInst.addOperand(MCOperand::createReg(0));
7183     TmpInst.addOperand(MCOperand::createImm(0));
7184     TmpInst.addOperand(Inst.getOperand(2));
7185     TmpInst.addOperand(Inst.getOperand(3));
7186     Inst = TmpInst;
7187     return true;
7188   }
7189   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
7190   case ARM::STRT_POST:
7191   case ARM::STRBT_POST: {
7192     const unsigned Opcode =
7193       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
7194                                            : ARM::STRBT_POST_IMM;
7195     MCInst TmpInst;
7196     TmpInst.setOpcode(Opcode);
7197     TmpInst.addOperand(Inst.getOperand(1));
7198     TmpInst.addOperand(Inst.getOperand(0));
7199     TmpInst.addOperand(Inst.getOperand(1));
7200     TmpInst.addOperand(MCOperand::createReg(0));
7201     TmpInst.addOperand(MCOperand::createImm(0));
7202     TmpInst.addOperand(Inst.getOperand(2));
7203     TmpInst.addOperand(Inst.getOperand(3));
7204     Inst = TmpInst;
7205     return true;
7206   }
7207   // Alias for alternate form of 'ADR Rd, #imm' instruction.
7208   case ARM::ADDri: {
7209     if (Inst.getOperand(1).getReg() != ARM::PC ||
7210         Inst.getOperand(5).getReg() != 0 ||
7211         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
7212       return false;
7213     MCInst TmpInst;
7214     TmpInst.setOpcode(ARM::ADR);
7215     TmpInst.addOperand(Inst.getOperand(0));
7216     if (Inst.getOperand(2).isImm()) {
7217       // Immediate (mod_imm) will be in its encoded form, we must unencode it
7218       // before passing it to the ADR instruction.
7219       unsigned Enc = Inst.getOperand(2).getImm();
7220       TmpInst.addOperand(MCOperand::createImm(
7221         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
7222     } else {
7223       // Turn PC-relative expression into absolute expression.
7224       // Reading PC provides the start of the current instruction + 8 and
7225       // the transform to adr is biased by that.
7226       MCSymbol *Dot = getContext().createTempSymbol();
7227       Out.EmitLabel(Dot);
7228       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
7229       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
7230                                                      MCSymbolRefExpr::VK_None,
7231                                                      getContext());
7232       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
7233       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
7234                                                      getContext());
7235       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
7236                                                         getContext());
7237       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
7238     }
7239     TmpInst.addOperand(Inst.getOperand(3));
7240     TmpInst.addOperand(Inst.getOperand(4));
7241     Inst = TmpInst;
7242     return true;
7243   }
7244   // Aliases for alternate PC+imm syntax of LDR instructions.
7245   case ARM::t2LDRpcrel:
7246     // Select the narrow version if the immediate will fit.
7247     if (Inst.getOperand(1).getImm() > 0 &&
7248         Inst.getOperand(1).getImm() <= 0xff &&
7249         !HasWideQualifier)
7250       Inst.setOpcode(ARM::tLDRpci);
7251     else
7252       Inst.setOpcode(ARM::t2LDRpci);
7253     return true;
7254   case ARM::t2LDRBpcrel:
7255     Inst.setOpcode(ARM::t2LDRBpci);
7256     return true;
7257   case ARM::t2LDRHpcrel:
7258     Inst.setOpcode(ARM::t2LDRHpci);
7259     return true;
7260   case ARM::t2LDRSBpcrel:
7261     Inst.setOpcode(ARM::t2LDRSBpci);
7262     return true;
7263   case ARM::t2LDRSHpcrel:
7264     Inst.setOpcode(ARM::t2LDRSHpci);
7265     return true;
7266   case ARM::LDRConstPool:
7267   case ARM::tLDRConstPool:
7268   case ARM::t2LDRConstPool: {
7269     // Pseudo instruction ldr rt, =immediate is converted to a
7270     // MOV rt, immediate if immediate is known and representable
7271     // otherwise we create a constant pool entry that we load from.
7272     MCInst TmpInst;
7273     if (Inst.getOpcode() == ARM::LDRConstPool)
7274       TmpInst.setOpcode(ARM::LDRi12);
7275     else if (Inst.getOpcode() == ARM::tLDRConstPool)
7276       TmpInst.setOpcode(ARM::tLDRpci);
7277     else if (Inst.getOpcode() == ARM::t2LDRConstPool)
7278       TmpInst.setOpcode(ARM::t2LDRpci);
7279     const ARMOperand &PoolOperand =
7280       (HasWideQualifier ?
7281        static_cast<ARMOperand &>(*Operands[4]) :
7282        static_cast<ARMOperand &>(*Operands[3]));
7283     const MCExpr *SubExprVal = PoolOperand.getConstantPoolImm();
7284     // If SubExprVal is a constant we may be able to use a MOV
7285     if (isa<MCConstantExpr>(SubExprVal) &&
7286         Inst.getOperand(0).getReg() != ARM::PC &&
7287         Inst.getOperand(0).getReg() != ARM::SP) {
7288       int64_t Value =
7289         (int64_t) (cast<MCConstantExpr>(SubExprVal))->getValue();
7290       bool UseMov  = true;
7291       bool MovHasS = true;
7292       if (Inst.getOpcode() == ARM::LDRConstPool) {
7293         // ARM Constant
7294         if (ARM_AM::getSOImmVal(Value) != -1) {
7295           Value = ARM_AM::getSOImmVal(Value);
7296           TmpInst.setOpcode(ARM::MOVi);
7297         }
7298         else if (ARM_AM::getSOImmVal(~Value) != -1) {
7299           Value = ARM_AM::getSOImmVal(~Value);
7300           TmpInst.setOpcode(ARM::MVNi);
7301         }
7302         else if (hasV6T2Ops() &&
7303                  Value >=0 && Value < 65536) {
7304           TmpInst.setOpcode(ARM::MOVi16);
7305           MovHasS = false;
7306         }
7307         else
7308           UseMov = false;
7309       }
7310       else {
7311         // Thumb/Thumb2 Constant
7312         if (hasThumb2() &&
7313             ARM_AM::getT2SOImmVal(Value) != -1)
7314           TmpInst.setOpcode(ARM::t2MOVi);
7315         else if (hasThumb2() &&
7316                  ARM_AM::getT2SOImmVal(~Value) != -1) {
7317           TmpInst.setOpcode(ARM::t2MVNi);
7318           Value = ~Value;
7319         }
7320         else if (hasV8MBaseline() &&
7321                  Value >=0 && Value < 65536) {
7322           TmpInst.setOpcode(ARM::t2MOVi16);
7323           MovHasS = false;
7324         }
7325         else
7326           UseMov = false;
7327       }
7328       if (UseMov) {
7329         TmpInst.addOperand(Inst.getOperand(0));           // Rt
7330         TmpInst.addOperand(MCOperand::createImm(Value));  // Immediate
7331         TmpInst.addOperand(Inst.getOperand(2));           // CondCode
7332         TmpInst.addOperand(Inst.getOperand(3));           // CondCode
7333         if (MovHasS)
7334           TmpInst.addOperand(MCOperand::createReg(0));    // S
7335         Inst = TmpInst;
7336         return true;
7337       }
7338     }
7339     // No opportunity to use MOV/MVN create constant pool
7340     const MCExpr *CPLoc =
7341       getTargetStreamer().addConstantPoolEntry(SubExprVal,
7342                                                PoolOperand.getStartLoc());
7343     TmpInst.addOperand(Inst.getOperand(0));           // Rt
7344     TmpInst.addOperand(MCOperand::createExpr(CPLoc)); // offset to constpool
7345     if (TmpInst.getOpcode() == ARM::LDRi12)
7346       TmpInst.addOperand(MCOperand::createImm(0));    // unused offset
7347     TmpInst.addOperand(Inst.getOperand(2));           // CondCode
7348     TmpInst.addOperand(Inst.getOperand(3));           // CondCode
7349     Inst = TmpInst;
7350     return true;
7351   }
7352   // Handle NEON VST complex aliases.
7353   case ARM::VST1LNdWB_register_Asm_8:
7354   case ARM::VST1LNdWB_register_Asm_16:
7355   case ARM::VST1LNdWB_register_Asm_32: {
7356     MCInst TmpInst;
7357     // Shuffle the operands around so the lane index operand is in the
7358     // right place.
7359     unsigned Spacing;
7360     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7361     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7362     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7363     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7364     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7365     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7366     TmpInst.addOperand(Inst.getOperand(1)); // lane
7367     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7368     TmpInst.addOperand(Inst.getOperand(6));
7369     Inst = TmpInst;
7370     return true;
7371   }
7372 
7373   case ARM::VST2LNdWB_register_Asm_8:
7374   case ARM::VST2LNdWB_register_Asm_16:
7375   case ARM::VST2LNdWB_register_Asm_32:
7376   case ARM::VST2LNqWB_register_Asm_16:
7377   case ARM::VST2LNqWB_register_Asm_32: {
7378     MCInst TmpInst;
7379     // Shuffle the operands around so the lane index operand is in the
7380     // right place.
7381     unsigned Spacing;
7382     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7383     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7384     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7385     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7386     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7387     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7388     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7389                                             Spacing));
7390     TmpInst.addOperand(Inst.getOperand(1)); // lane
7391     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7392     TmpInst.addOperand(Inst.getOperand(6));
7393     Inst = TmpInst;
7394     return true;
7395   }
7396 
7397   case ARM::VST3LNdWB_register_Asm_8:
7398   case ARM::VST3LNdWB_register_Asm_16:
7399   case ARM::VST3LNdWB_register_Asm_32:
7400   case ARM::VST3LNqWB_register_Asm_16:
7401   case ARM::VST3LNqWB_register_Asm_32: {
7402     MCInst TmpInst;
7403     // Shuffle the operands around so the lane index operand is in the
7404     // right place.
7405     unsigned Spacing;
7406     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7407     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7408     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7409     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7410     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7411     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7412     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7413                                             Spacing));
7414     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7415                                             Spacing * 2));
7416     TmpInst.addOperand(Inst.getOperand(1)); // lane
7417     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7418     TmpInst.addOperand(Inst.getOperand(6));
7419     Inst = TmpInst;
7420     return true;
7421   }
7422 
7423   case ARM::VST4LNdWB_register_Asm_8:
7424   case ARM::VST4LNdWB_register_Asm_16:
7425   case ARM::VST4LNdWB_register_Asm_32:
7426   case ARM::VST4LNqWB_register_Asm_16:
7427   case ARM::VST4LNqWB_register_Asm_32: {
7428     MCInst TmpInst;
7429     // Shuffle the operands around so the lane index operand is in the
7430     // right place.
7431     unsigned Spacing;
7432     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7433     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7434     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7435     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7436     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7437     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7438     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7439                                             Spacing));
7440     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7441                                             Spacing * 2));
7442     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7443                                             Spacing * 3));
7444     TmpInst.addOperand(Inst.getOperand(1)); // lane
7445     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7446     TmpInst.addOperand(Inst.getOperand(6));
7447     Inst = TmpInst;
7448     return true;
7449   }
7450 
7451   case ARM::VST1LNdWB_fixed_Asm_8:
7452   case ARM::VST1LNdWB_fixed_Asm_16:
7453   case ARM::VST1LNdWB_fixed_Asm_32: {
7454     MCInst TmpInst;
7455     // Shuffle the operands around so the lane index operand is in the
7456     // right place.
7457     unsigned Spacing;
7458     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7459     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7460     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7461     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7462     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7463     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7464     TmpInst.addOperand(Inst.getOperand(1)); // lane
7465     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7466     TmpInst.addOperand(Inst.getOperand(5));
7467     Inst = TmpInst;
7468     return true;
7469   }
7470 
7471   case ARM::VST2LNdWB_fixed_Asm_8:
7472   case ARM::VST2LNdWB_fixed_Asm_16:
7473   case ARM::VST2LNdWB_fixed_Asm_32:
7474   case ARM::VST2LNqWB_fixed_Asm_16:
7475   case ARM::VST2LNqWB_fixed_Asm_32: {
7476     MCInst TmpInst;
7477     // Shuffle the operands around so the lane index operand is in the
7478     // right place.
7479     unsigned Spacing;
7480     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7481     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7482     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7483     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7484     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7485     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7486     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7487                                             Spacing));
7488     TmpInst.addOperand(Inst.getOperand(1)); // lane
7489     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7490     TmpInst.addOperand(Inst.getOperand(5));
7491     Inst = TmpInst;
7492     return true;
7493   }
7494 
7495   case ARM::VST3LNdWB_fixed_Asm_8:
7496   case ARM::VST3LNdWB_fixed_Asm_16:
7497   case ARM::VST3LNdWB_fixed_Asm_32:
7498   case ARM::VST3LNqWB_fixed_Asm_16:
7499   case ARM::VST3LNqWB_fixed_Asm_32: {
7500     MCInst TmpInst;
7501     // Shuffle the operands around so the lane index operand is in the
7502     // right place.
7503     unsigned Spacing;
7504     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7505     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7506     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7507     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7508     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7509     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7510     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7511                                             Spacing));
7512     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7513                                             Spacing * 2));
7514     TmpInst.addOperand(Inst.getOperand(1)); // lane
7515     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7516     TmpInst.addOperand(Inst.getOperand(5));
7517     Inst = TmpInst;
7518     return true;
7519   }
7520 
7521   case ARM::VST4LNdWB_fixed_Asm_8:
7522   case ARM::VST4LNdWB_fixed_Asm_16:
7523   case ARM::VST4LNdWB_fixed_Asm_32:
7524   case ARM::VST4LNqWB_fixed_Asm_16:
7525   case ARM::VST4LNqWB_fixed_Asm_32: {
7526     MCInst TmpInst;
7527     // Shuffle the operands around so the lane index operand is in the
7528     // right place.
7529     unsigned Spacing;
7530     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7531     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7532     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7533     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7534     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7535     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7536     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7537                                             Spacing));
7538     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7539                                             Spacing * 2));
7540     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7541                                             Spacing * 3));
7542     TmpInst.addOperand(Inst.getOperand(1)); // lane
7543     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7544     TmpInst.addOperand(Inst.getOperand(5));
7545     Inst = TmpInst;
7546     return true;
7547   }
7548 
7549   case ARM::VST1LNdAsm_8:
7550   case ARM::VST1LNdAsm_16:
7551   case ARM::VST1LNdAsm_32: {
7552     MCInst TmpInst;
7553     // Shuffle the operands around so the lane index operand is in the
7554     // right place.
7555     unsigned Spacing;
7556     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7557     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7558     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7559     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7560     TmpInst.addOperand(Inst.getOperand(1)); // lane
7561     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7562     TmpInst.addOperand(Inst.getOperand(5));
7563     Inst = TmpInst;
7564     return true;
7565   }
7566 
7567   case ARM::VST2LNdAsm_8:
7568   case ARM::VST2LNdAsm_16:
7569   case ARM::VST2LNdAsm_32:
7570   case ARM::VST2LNqAsm_16:
7571   case ARM::VST2LNqAsm_32: {
7572     MCInst TmpInst;
7573     // Shuffle the operands around so the lane index operand is in the
7574     // right place.
7575     unsigned Spacing;
7576     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7577     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7578     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7579     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7580     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7581                                             Spacing));
7582     TmpInst.addOperand(Inst.getOperand(1)); // lane
7583     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7584     TmpInst.addOperand(Inst.getOperand(5));
7585     Inst = TmpInst;
7586     return true;
7587   }
7588 
7589   case ARM::VST3LNdAsm_8:
7590   case ARM::VST3LNdAsm_16:
7591   case ARM::VST3LNdAsm_32:
7592   case ARM::VST3LNqAsm_16:
7593   case ARM::VST3LNqAsm_32: {
7594     MCInst TmpInst;
7595     // Shuffle the operands around so the lane index operand is in the
7596     // right place.
7597     unsigned Spacing;
7598     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7599     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7600     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7601     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7602     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7603                                             Spacing));
7604     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7605                                             Spacing * 2));
7606     TmpInst.addOperand(Inst.getOperand(1)); // lane
7607     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7608     TmpInst.addOperand(Inst.getOperand(5));
7609     Inst = TmpInst;
7610     return true;
7611   }
7612 
7613   case ARM::VST4LNdAsm_8:
7614   case ARM::VST4LNdAsm_16:
7615   case ARM::VST4LNdAsm_32:
7616   case ARM::VST4LNqAsm_16:
7617   case ARM::VST4LNqAsm_32: {
7618     MCInst TmpInst;
7619     // Shuffle the operands around so the lane index operand is in the
7620     // right place.
7621     unsigned Spacing;
7622     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7623     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7624     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7625     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7626     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7627                                             Spacing));
7628     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7629                                             Spacing * 2));
7630     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7631                                             Spacing * 3));
7632     TmpInst.addOperand(Inst.getOperand(1)); // lane
7633     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7634     TmpInst.addOperand(Inst.getOperand(5));
7635     Inst = TmpInst;
7636     return true;
7637   }
7638 
7639   // Handle NEON VLD complex aliases.
7640   case ARM::VLD1LNdWB_register_Asm_8:
7641   case ARM::VLD1LNdWB_register_Asm_16:
7642   case ARM::VLD1LNdWB_register_Asm_32: {
7643     MCInst TmpInst;
7644     // Shuffle the operands around so the lane index operand is in the
7645     // right place.
7646     unsigned Spacing;
7647     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7648     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7649     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7650     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7651     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7652     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7653     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7654     TmpInst.addOperand(Inst.getOperand(1)); // lane
7655     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7656     TmpInst.addOperand(Inst.getOperand(6));
7657     Inst = TmpInst;
7658     return true;
7659   }
7660 
7661   case ARM::VLD2LNdWB_register_Asm_8:
7662   case ARM::VLD2LNdWB_register_Asm_16:
7663   case ARM::VLD2LNdWB_register_Asm_32:
7664   case ARM::VLD2LNqWB_register_Asm_16:
7665   case ARM::VLD2LNqWB_register_Asm_32: {
7666     MCInst TmpInst;
7667     // Shuffle the operands around so the lane index operand is in the
7668     // right place.
7669     unsigned Spacing;
7670     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7671     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7672     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7673                                             Spacing));
7674     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7675     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7676     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7677     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7678     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7679     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7680                                             Spacing));
7681     TmpInst.addOperand(Inst.getOperand(1)); // lane
7682     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7683     TmpInst.addOperand(Inst.getOperand(6));
7684     Inst = TmpInst;
7685     return true;
7686   }
7687 
7688   case ARM::VLD3LNdWB_register_Asm_8:
7689   case ARM::VLD3LNdWB_register_Asm_16:
7690   case ARM::VLD3LNdWB_register_Asm_32:
7691   case ARM::VLD3LNqWB_register_Asm_16:
7692   case ARM::VLD3LNqWB_register_Asm_32: {
7693     MCInst TmpInst;
7694     // Shuffle the operands around so the lane index operand is in the
7695     // right place.
7696     unsigned Spacing;
7697     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7698     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7699     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7700                                             Spacing));
7701     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7702                                             Spacing * 2));
7703     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7704     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7705     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7706     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7707     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7708     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7709                                             Spacing));
7710     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7711                                             Spacing * 2));
7712     TmpInst.addOperand(Inst.getOperand(1)); // lane
7713     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7714     TmpInst.addOperand(Inst.getOperand(6));
7715     Inst = TmpInst;
7716     return true;
7717   }
7718 
7719   case ARM::VLD4LNdWB_register_Asm_8:
7720   case ARM::VLD4LNdWB_register_Asm_16:
7721   case ARM::VLD4LNdWB_register_Asm_32:
7722   case ARM::VLD4LNqWB_register_Asm_16:
7723   case ARM::VLD4LNqWB_register_Asm_32: {
7724     MCInst TmpInst;
7725     // Shuffle the operands around so the lane index operand is in the
7726     // right place.
7727     unsigned Spacing;
7728     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7729     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7730     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7731                                             Spacing));
7732     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7733                                             Spacing * 2));
7734     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7735                                             Spacing * 3));
7736     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7737     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7738     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7739     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7740     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7741     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7742                                             Spacing));
7743     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7744                                             Spacing * 2));
7745     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7746                                             Spacing * 3));
7747     TmpInst.addOperand(Inst.getOperand(1)); // lane
7748     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7749     TmpInst.addOperand(Inst.getOperand(6));
7750     Inst = TmpInst;
7751     return true;
7752   }
7753 
7754   case ARM::VLD1LNdWB_fixed_Asm_8:
7755   case ARM::VLD1LNdWB_fixed_Asm_16:
7756   case ARM::VLD1LNdWB_fixed_Asm_32: {
7757     MCInst TmpInst;
7758     // Shuffle the operands around so the lane index operand is in the
7759     // right place.
7760     unsigned Spacing;
7761     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7762     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7763     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7764     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7765     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7766     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7767     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7768     TmpInst.addOperand(Inst.getOperand(1)); // lane
7769     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7770     TmpInst.addOperand(Inst.getOperand(5));
7771     Inst = TmpInst;
7772     return true;
7773   }
7774 
7775   case ARM::VLD2LNdWB_fixed_Asm_8:
7776   case ARM::VLD2LNdWB_fixed_Asm_16:
7777   case ARM::VLD2LNdWB_fixed_Asm_32:
7778   case ARM::VLD2LNqWB_fixed_Asm_16:
7779   case ARM::VLD2LNqWB_fixed_Asm_32: {
7780     MCInst TmpInst;
7781     // Shuffle the operands around so the lane index operand is in the
7782     // right place.
7783     unsigned Spacing;
7784     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7785     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7786     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7787                                             Spacing));
7788     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7789     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7790     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7791     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7792     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7793     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7794                                             Spacing));
7795     TmpInst.addOperand(Inst.getOperand(1)); // lane
7796     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7797     TmpInst.addOperand(Inst.getOperand(5));
7798     Inst = TmpInst;
7799     return true;
7800   }
7801 
7802   case ARM::VLD3LNdWB_fixed_Asm_8:
7803   case ARM::VLD3LNdWB_fixed_Asm_16:
7804   case ARM::VLD3LNdWB_fixed_Asm_32:
7805   case ARM::VLD3LNqWB_fixed_Asm_16:
7806   case ARM::VLD3LNqWB_fixed_Asm_32: {
7807     MCInst TmpInst;
7808     // Shuffle the operands around so the lane index operand is in the
7809     // right place.
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(Inst.getOperand(2)); // Rn_wb
7818     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7819     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7820     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7821     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7822     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7823                                             Spacing));
7824     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7825                                             Spacing * 2));
7826     TmpInst.addOperand(Inst.getOperand(1)); // lane
7827     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7828     TmpInst.addOperand(Inst.getOperand(5));
7829     Inst = TmpInst;
7830     return true;
7831   }
7832 
7833   case ARM::VLD4LNdWB_fixed_Asm_8:
7834   case ARM::VLD4LNdWB_fixed_Asm_16:
7835   case ARM::VLD4LNdWB_fixed_Asm_32:
7836   case ARM::VLD4LNqWB_fixed_Asm_16:
7837   case ARM::VLD4LNqWB_fixed_Asm_32: {
7838     MCInst TmpInst;
7839     // Shuffle the operands around so the lane index operand is in the
7840     // right place.
7841     unsigned Spacing;
7842     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7843     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7844     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7845                                             Spacing));
7846     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7847                                             Spacing * 2));
7848     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7849                                             Spacing * 3));
7850     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7851     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7852     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7853     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7854     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7855     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7856                                             Spacing));
7857     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7858                                             Spacing * 2));
7859     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7860                                             Spacing * 3));
7861     TmpInst.addOperand(Inst.getOperand(1)); // lane
7862     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7863     TmpInst.addOperand(Inst.getOperand(5));
7864     Inst = TmpInst;
7865     return true;
7866   }
7867 
7868   case ARM::VLD1LNdAsm_8:
7869   case ARM::VLD1LNdAsm_16:
7870   case ARM::VLD1LNdAsm_32: {
7871     MCInst TmpInst;
7872     // Shuffle the operands around so the lane index operand is in the
7873     // right place.
7874     unsigned Spacing;
7875     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7876     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7877     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7878     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7879     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7880     TmpInst.addOperand(Inst.getOperand(1)); // lane
7881     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7882     TmpInst.addOperand(Inst.getOperand(5));
7883     Inst = TmpInst;
7884     return true;
7885   }
7886 
7887   case ARM::VLD2LNdAsm_8:
7888   case ARM::VLD2LNdAsm_16:
7889   case ARM::VLD2LNdAsm_32:
7890   case ARM::VLD2LNqAsm_16:
7891   case ARM::VLD2LNqAsm_32: {
7892     MCInst TmpInst;
7893     // Shuffle the operands around so the lane index operand is in the
7894     // right place.
7895     unsigned Spacing;
7896     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7897     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7898     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7899                                             Spacing));
7900     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7901     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7902     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7903     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7904                                             Spacing));
7905     TmpInst.addOperand(Inst.getOperand(1)); // lane
7906     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7907     TmpInst.addOperand(Inst.getOperand(5));
7908     Inst = TmpInst;
7909     return true;
7910   }
7911 
7912   case ARM::VLD3LNdAsm_8:
7913   case ARM::VLD3LNdAsm_16:
7914   case ARM::VLD3LNdAsm_32:
7915   case ARM::VLD3LNqAsm_16:
7916   case ARM::VLD3LNqAsm_32: {
7917     MCInst TmpInst;
7918     // Shuffle the operands around so the lane index operand is in the
7919     // right place.
7920     unsigned Spacing;
7921     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7922     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7923     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7924                                             Spacing));
7925     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7926                                             Spacing * 2));
7927     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7928     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7929     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7930     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7931                                             Spacing));
7932     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7933                                             Spacing * 2));
7934     TmpInst.addOperand(Inst.getOperand(1)); // lane
7935     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7936     TmpInst.addOperand(Inst.getOperand(5));
7937     Inst = TmpInst;
7938     return true;
7939   }
7940 
7941   case ARM::VLD4LNdAsm_8:
7942   case ARM::VLD4LNdAsm_16:
7943   case ARM::VLD4LNdAsm_32:
7944   case ARM::VLD4LNqAsm_16:
7945   case ARM::VLD4LNqAsm_32: {
7946     MCInst TmpInst;
7947     // Shuffle the operands around so the lane index operand is in the
7948     // right place.
7949     unsigned Spacing;
7950     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7951     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7952     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7953                                             Spacing));
7954     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7955                                             Spacing * 2));
7956     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7957                                             Spacing * 3));
7958     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7959     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7960     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7961     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7962                                             Spacing));
7963     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7964                                             Spacing * 2));
7965     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7966                                             Spacing * 3));
7967     TmpInst.addOperand(Inst.getOperand(1)); // lane
7968     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7969     TmpInst.addOperand(Inst.getOperand(5));
7970     Inst = TmpInst;
7971     return true;
7972   }
7973 
7974   // VLD3DUP single 3-element structure to all lanes instructions.
7975   case ARM::VLD3DUPdAsm_8:
7976   case ARM::VLD3DUPdAsm_16:
7977   case ARM::VLD3DUPdAsm_32:
7978   case ARM::VLD3DUPqAsm_8:
7979   case ARM::VLD3DUPqAsm_16:
7980   case ARM::VLD3DUPqAsm_32: {
7981     MCInst TmpInst;
7982     unsigned Spacing;
7983     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7984     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7985     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7986                                             Spacing));
7987     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7988                                             Spacing * 2));
7989     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7990     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7991     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7992     TmpInst.addOperand(Inst.getOperand(4));
7993     Inst = TmpInst;
7994     return true;
7995   }
7996 
7997   case ARM::VLD3DUPdWB_fixed_Asm_8:
7998   case ARM::VLD3DUPdWB_fixed_Asm_16:
7999   case ARM::VLD3DUPdWB_fixed_Asm_32:
8000   case ARM::VLD3DUPqWB_fixed_Asm_8:
8001   case ARM::VLD3DUPqWB_fixed_Asm_16:
8002   case ARM::VLD3DUPqWB_fixed_Asm_32: {
8003     MCInst TmpInst;
8004     unsigned Spacing;
8005     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8006     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8007     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8008                                             Spacing));
8009     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8010                                             Spacing * 2));
8011     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8012     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8013     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8014     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8015     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8016     TmpInst.addOperand(Inst.getOperand(4));
8017     Inst = TmpInst;
8018     return true;
8019   }
8020 
8021   case ARM::VLD3DUPdWB_register_Asm_8:
8022   case ARM::VLD3DUPdWB_register_Asm_16:
8023   case ARM::VLD3DUPdWB_register_Asm_32:
8024   case ARM::VLD3DUPqWB_register_Asm_8:
8025   case ARM::VLD3DUPqWB_register_Asm_16:
8026   case ARM::VLD3DUPqWB_register_Asm_32: {
8027     MCInst TmpInst;
8028     unsigned Spacing;
8029     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8030     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8031     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8032                                             Spacing));
8033     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8034                                             Spacing * 2));
8035     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8036     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8037     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8038     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8039     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8040     TmpInst.addOperand(Inst.getOperand(5));
8041     Inst = TmpInst;
8042     return true;
8043   }
8044 
8045   // VLD3 multiple 3-element structure instructions.
8046   case ARM::VLD3dAsm_8:
8047   case ARM::VLD3dAsm_16:
8048   case ARM::VLD3dAsm_32:
8049   case ARM::VLD3qAsm_8:
8050   case ARM::VLD3qAsm_16:
8051   case ARM::VLD3qAsm_32: {
8052     MCInst TmpInst;
8053     unsigned Spacing;
8054     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8055     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8056     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8057                                             Spacing));
8058     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8059                                             Spacing * 2));
8060     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8061     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8062     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8063     TmpInst.addOperand(Inst.getOperand(4));
8064     Inst = TmpInst;
8065     return true;
8066   }
8067 
8068   case ARM::VLD3dWB_fixed_Asm_8:
8069   case ARM::VLD3dWB_fixed_Asm_16:
8070   case ARM::VLD3dWB_fixed_Asm_32:
8071   case ARM::VLD3qWB_fixed_Asm_8:
8072   case ARM::VLD3qWB_fixed_Asm_16:
8073   case ARM::VLD3qWB_fixed_Asm_32: {
8074     MCInst TmpInst;
8075     unsigned Spacing;
8076     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8077     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8078     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8079                                             Spacing));
8080     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8081                                             Spacing * 2));
8082     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8083     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8084     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8085     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8086     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8087     TmpInst.addOperand(Inst.getOperand(4));
8088     Inst = TmpInst;
8089     return true;
8090   }
8091 
8092   case ARM::VLD3dWB_register_Asm_8:
8093   case ARM::VLD3dWB_register_Asm_16:
8094   case ARM::VLD3dWB_register_Asm_32:
8095   case ARM::VLD3qWB_register_Asm_8:
8096   case ARM::VLD3qWB_register_Asm_16:
8097   case ARM::VLD3qWB_register_Asm_32: {
8098     MCInst TmpInst;
8099     unsigned Spacing;
8100     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8101     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8102     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8103                                             Spacing));
8104     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8105                                             Spacing * 2));
8106     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8107     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8108     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8109     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8110     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8111     TmpInst.addOperand(Inst.getOperand(5));
8112     Inst = TmpInst;
8113     return true;
8114   }
8115 
8116   // VLD4DUP single 3-element structure to all lanes instructions.
8117   case ARM::VLD4DUPdAsm_8:
8118   case ARM::VLD4DUPdAsm_16:
8119   case ARM::VLD4DUPdAsm_32:
8120   case ARM::VLD4DUPqAsm_8:
8121   case ARM::VLD4DUPqAsm_16:
8122   case ARM::VLD4DUPqAsm_32: {
8123     MCInst TmpInst;
8124     unsigned Spacing;
8125     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8126     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8127     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8128                                             Spacing));
8129     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8130                                             Spacing * 2));
8131     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8132                                             Spacing * 3));
8133     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8134     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8135     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8136     TmpInst.addOperand(Inst.getOperand(4));
8137     Inst = TmpInst;
8138     return true;
8139   }
8140 
8141   case ARM::VLD4DUPdWB_fixed_Asm_8:
8142   case ARM::VLD4DUPdWB_fixed_Asm_16:
8143   case ARM::VLD4DUPdWB_fixed_Asm_32:
8144   case ARM::VLD4DUPqWB_fixed_Asm_8:
8145   case ARM::VLD4DUPqWB_fixed_Asm_16:
8146   case ARM::VLD4DUPqWB_fixed_Asm_32: {
8147     MCInst TmpInst;
8148     unsigned Spacing;
8149     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8150     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8151     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8152                                             Spacing));
8153     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8154                                             Spacing * 2));
8155     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8156                                             Spacing * 3));
8157     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8158     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8159     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8160     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8161     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8162     TmpInst.addOperand(Inst.getOperand(4));
8163     Inst = TmpInst;
8164     return true;
8165   }
8166 
8167   case ARM::VLD4DUPdWB_register_Asm_8:
8168   case ARM::VLD4DUPdWB_register_Asm_16:
8169   case ARM::VLD4DUPdWB_register_Asm_32:
8170   case ARM::VLD4DUPqWB_register_Asm_8:
8171   case ARM::VLD4DUPqWB_register_Asm_16:
8172   case ARM::VLD4DUPqWB_register_Asm_32: {
8173     MCInst TmpInst;
8174     unsigned Spacing;
8175     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8176     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8177     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8178                                             Spacing));
8179     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8180                                             Spacing * 2));
8181     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8182                                             Spacing * 3));
8183     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8184     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8185     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8186     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8187     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8188     TmpInst.addOperand(Inst.getOperand(5));
8189     Inst = TmpInst;
8190     return true;
8191   }
8192 
8193   // VLD4 multiple 4-element structure instructions.
8194   case ARM::VLD4dAsm_8:
8195   case ARM::VLD4dAsm_16:
8196   case ARM::VLD4dAsm_32:
8197   case ARM::VLD4qAsm_8:
8198   case ARM::VLD4qAsm_16:
8199   case ARM::VLD4qAsm_32: {
8200     MCInst TmpInst;
8201     unsigned Spacing;
8202     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8203     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8204     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8205                                             Spacing));
8206     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8207                                             Spacing * 2));
8208     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8209                                             Spacing * 3));
8210     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8211     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8212     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8213     TmpInst.addOperand(Inst.getOperand(4));
8214     Inst = TmpInst;
8215     return true;
8216   }
8217 
8218   case ARM::VLD4dWB_fixed_Asm_8:
8219   case ARM::VLD4dWB_fixed_Asm_16:
8220   case ARM::VLD4dWB_fixed_Asm_32:
8221   case ARM::VLD4qWB_fixed_Asm_8:
8222   case ARM::VLD4qWB_fixed_Asm_16:
8223   case ARM::VLD4qWB_fixed_Asm_32: {
8224     MCInst TmpInst;
8225     unsigned Spacing;
8226     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8227     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8228     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8229                                             Spacing));
8230     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8231                                             Spacing * 2));
8232     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8233                                             Spacing * 3));
8234     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8235     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8236     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8237     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8238     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8239     TmpInst.addOperand(Inst.getOperand(4));
8240     Inst = TmpInst;
8241     return true;
8242   }
8243 
8244   case ARM::VLD4dWB_register_Asm_8:
8245   case ARM::VLD4dWB_register_Asm_16:
8246   case ARM::VLD4dWB_register_Asm_32:
8247   case ARM::VLD4qWB_register_Asm_8:
8248   case ARM::VLD4qWB_register_Asm_16:
8249   case ARM::VLD4qWB_register_Asm_32: {
8250     MCInst TmpInst;
8251     unsigned Spacing;
8252     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8253     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8254     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8255                                             Spacing));
8256     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8257                                             Spacing * 2));
8258     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8259                                             Spacing * 3));
8260     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8261     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8262     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8263     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8264     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8265     TmpInst.addOperand(Inst.getOperand(5));
8266     Inst = TmpInst;
8267     return true;
8268   }
8269 
8270   // VST3 multiple 3-element structure instructions.
8271   case ARM::VST3dAsm_8:
8272   case ARM::VST3dAsm_16:
8273   case ARM::VST3dAsm_32:
8274   case ARM::VST3qAsm_8:
8275   case ARM::VST3qAsm_16:
8276   case ARM::VST3qAsm_32: {
8277     MCInst TmpInst;
8278     unsigned Spacing;
8279     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8280     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8281     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8282     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8283     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8284                                             Spacing));
8285     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8286                                             Spacing * 2));
8287     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8288     TmpInst.addOperand(Inst.getOperand(4));
8289     Inst = TmpInst;
8290     return true;
8291   }
8292 
8293   case ARM::VST3dWB_fixed_Asm_8:
8294   case ARM::VST3dWB_fixed_Asm_16:
8295   case ARM::VST3dWB_fixed_Asm_32:
8296   case ARM::VST3qWB_fixed_Asm_8:
8297   case ARM::VST3qWB_fixed_Asm_16:
8298   case ARM::VST3qWB_fixed_Asm_32: {
8299     MCInst TmpInst;
8300     unsigned Spacing;
8301     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8302     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8303     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8304     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8305     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8306     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8307     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8308                                             Spacing));
8309     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8310                                             Spacing * 2));
8311     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8312     TmpInst.addOperand(Inst.getOperand(4));
8313     Inst = TmpInst;
8314     return true;
8315   }
8316 
8317   case ARM::VST3dWB_register_Asm_8:
8318   case ARM::VST3dWB_register_Asm_16:
8319   case ARM::VST3dWB_register_Asm_32:
8320   case ARM::VST3qWB_register_Asm_8:
8321   case ARM::VST3qWB_register_Asm_16:
8322   case ARM::VST3qWB_register_Asm_32: {
8323     MCInst TmpInst;
8324     unsigned Spacing;
8325     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8326     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8327     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8328     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8329     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8330     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8331     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8332                                             Spacing));
8333     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8334                                             Spacing * 2));
8335     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8336     TmpInst.addOperand(Inst.getOperand(5));
8337     Inst = TmpInst;
8338     return true;
8339   }
8340 
8341   // VST4 multiple 3-element structure instructions.
8342   case ARM::VST4dAsm_8:
8343   case ARM::VST4dAsm_16:
8344   case ARM::VST4dAsm_32:
8345   case ARM::VST4qAsm_8:
8346   case ARM::VST4qAsm_16:
8347   case ARM::VST4qAsm_32: {
8348     MCInst TmpInst;
8349     unsigned Spacing;
8350     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8351     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8352     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8353     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8354     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8355                                             Spacing));
8356     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8357                                             Spacing * 2));
8358     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8359                                             Spacing * 3));
8360     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8361     TmpInst.addOperand(Inst.getOperand(4));
8362     Inst = TmpInst;
8363     return true;
8364   }
8365 
8366   case ARM::VST4dWB_fixed_Asm_8:
8367   case ARM::VST4dWB_fixed_Asm_16:
8368   case ARM::VST4dWB_fixed_Asm_32:
8369   case ARM::VST4qWB_fixed_Asm_8:
8370   case ARM::VST4qWB_fixed_Asm_16:
8371   case ARM::VST4qWB_fixed_Asm_32: {
8372     MCInst TmpInst;
8373     unsigned Spacing;
8374     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8375     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8376     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8377     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8378     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8379     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8380     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8381                                             Spacing));
8382     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8383                                             Spacing * 2));
8384     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8385                                             Spacing * 3));
8386     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8387     TmpInst.addOperand(Inst.getOperand(4));
8388     Inst = TmpInst;
8389     return true;
8390   }
8391 
8392   case ARM::VST4dWB_register_Asm_8:
8393   case ARM::VST4dWB_register_Asm_16:
8394   case ARM::VST4dWB_register_Asm_32:
8395   case ARM::VST4qWB_register_Asm_8:
8396   case ARM::VST4qWB_register_Asm_16:
8397   case ARM::VST4qWB_register_Asm_32: {
8398     MCInst TmpInst;
8399     unsigned Spacing;
8400     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8401     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8402     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8403     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8404     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8405     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8406     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8407                                             Spacing));
8408     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8409                                             Spacing * 2));
8410     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8411                                             Spacing * 3));
8412     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8413     TmpInst.addOperand(Inst.getOperand(5));
8414     Inst = TmpInst;
8415     return true;
8416   }
8417 
8418   // Handle encoding choice for the shift-immediate instructions.
8419   case ARM::t2LSLri:
8420   case ARM::t2LSRri:
8421   case ARM::t2ASRri:
8422     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8423         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8424         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8425         !HasWideQualifier) {
8426       unsigned NewOpc;
8427       switch (Inst.getOpcode()) {
8428       default: llvm_unreachable("unexpected opcode");
8429       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
8430       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
8431       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
8432       }
8433       // The Thumb1 operands aren't in the same order. Awesome, eh?
8434       MCInst TmpInst;
8435       TmpInst.setOpcode(NewOpc);
8436       TmpInst.addOperand(Inst.getOperand(0));
8437       TmpInst.addOperand(Inst.getOperand(5));
8438       TmpInst.addOperand(Inst.getOperand(1));
8439       TmpInst.addOperand(Inst.getOperand(2));
8440       TmpInst.addOperand(Inst.getOperand(3));
8441       TmpInst.addOperand(Inst.getOperand(4));
8442       Inst = TmpInst;
8443       return true;
8444     }
8445     return false;
8446 
8447   // Handle the Thumb2 mode MOV complex aliases.
8448   case ARM::t2MOVsr:
8449   case ARM::t2MOVSsr: {
8450     // Which instruction to expand to depends on the CCOut operand and
8451     // whether we're in an IT block if the register operands are low
8452     // registers.
8453     bool isNarrow = false;
8454     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8455         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8456         isARMLowRegister(Inst.getOperand(2).getReg()) &&
8457         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8458         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr) &&
8459         !HasWideQualifier)
8460       isNarrow = true;
8461     MCInst TmpInst;
8462     unsigned newOpc;
8463     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
8464     default: llvm_unreachable("unexpected opcode!");
8465     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
8466     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
8467     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
8468     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
8469     }
8470     TmpInst.setOpcode(newOpc);
8471     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8472     if (isNarrow)
8473       TmpInst.addOperand(MCOperand::createReg(
8474           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8475     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8476     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8477     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8478     TmpInst.addOperand(Inst.getOperand(5));
8479     if (!isNarrow)
8480       TmpInst.addOperand(MCOperand::createReg(
8481           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8482     Inst = TmpInst;
8483     return true;
8484   }
8485   case ARM::t2MOVsi:
8486   case ARM::t2MOVSsi: {
8487     // Which instruction to expand to depends on the CCOut operand and
8488     // whether we're in an IT block if the register operands are low
8489     // registers.
8490     bool isNarrow = false;
8491     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8492         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8493         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi) &&
8494         !HasWideQualifier)
8495       isNarrow = true;
8496     MCInst TmpInst;
8497     unsigned newOpc;
8498     unsigned Shift = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8499     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
8500     bool isMov = false;
8501     // MOV rd, rm, LSL #0 is actually a MOV instruction
8502     if (Shift == ARM_AM::lsl && Amount == 0) {
8503       isMov = true;
8504       // The 16-bit encoding of MOV rd, rm, LSL #N is explicitly encoding T2 of
8505       // MOV (register) in the ARMv8-A and ARMv8-M manuals, and immediate 0 is
8506       // unpredictable in an IT block so the 32-bit encoding T3 has to be used
8507       // instead.
8508       if (inITBlock()) {
8509         isNarrow = false;
8510       }
8511       newOpc = isNarrow ? ARM::tMOVSr : ARM::t2MOVr;
8512     } else {
8513       switch(Shift) {
8514       default: llvm_unreachable("unexpected opcode!");
8515       case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
8516       case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
8517       case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
8518       case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
8519       case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
8520       }
8521     }
8522     if (Amount == 32) Amount = 0;
8523     TmpInst.setOpcode(newOpc);
8524     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8525     if (isNarrow && !isMov)
8526       TmpInst.addOperand(MCOperand::createReg(
8527           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8528     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8529     if (newOpc != ARM::t2RRX && !isMov)
8530       TmpInst.addOperand(MCOperand::createImm(Amount));
8531     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8532     TmpInst.addOperand(Inst.getOperand(4));
8533     if (!isNarrow)
8534       TmpInst.addOperand(MCOperand::createReg(
8535           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8536     Inst = TmpInst;
8537     return true;
8538   }
8539   // Handle the ARM mode MOV complex aliases.
8540   case ARM::ASRr:
8541   case ARM::LSRr:
8542   case ARM::LSLr:
8543   case ARM::RORr: {
8544     ARM_AM::ShiftOpc ShiftTy;
8545     switch(Inst.getOpcode()) {
8546     default: llvm_unreachable("unexpected opcode!");
8547     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
8548     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
8549     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
8550     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
8551     }
8552     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
8553     MCInst TmpInst;
8554     TmpInst.setOpcode(ARM::MOVsr);
8555     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8556     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8557     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8558     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8559     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8560     TmpInst.addOperand(Inst.getOperand(4));
8561     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8562     Inst = TmpInst;
8563     return true;
8564   }
8565   case ARM::ASRi:
8566   case ARM::LSRi:
8567   case ARM::LSLi:
8568   case ARM::RORi: {
8569     ARM_AM::ShiftOpc ShiftTy;
8570     switch(Inst.getOpcode()) {
8571     default: llvm_unreachable("unexpected opcode!");
8572     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
8573     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
8574     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
8575     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
8576     }
8577     // A shift by zero is a plain MOVr, not a MOVsi.
8578     unsigned Amt = Inst.getOperand(2).getImm();
8579     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
8580     // A shift by 32 should be encoded as 0 when permitted
8581     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
8582       Amt = 0;
8583     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
8584     MCInst TmpInst;
8585     TmpInst.setOpcode(Opc);
8586     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8587     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8588     if (Opc == ARM::MOVsi)
8589       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8590     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8591     TmpInst.addOperand(Inst.getOperand(4));
8592     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8593     Inst = TmpInst;
8594     return true;
8595   }
8596   case ARM::RRXi: {
8597     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
8598     MCInst TmpInst;
8599     TmpInst.setOpcode(ARM::MOVsi);
8600     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8601     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8602     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8603     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8604     TmpInst.addOperand(Inst.getOperand(3));
8605     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
8606     Inst = TmpInst;
8607     return true;
8608   }
8609   case ARM::t2LDMIA_UPD: {
8610     // If this is a load of a single register, then we should use
8611     // a post-indexed LDR instruction instead, per the ARM ARM.
8612     if (Inst.getNumOperands() != 5)
8613       return false;
8614     MCInst TmpInst;
8615     TmpInst.setOpcode(ARM::t2LDR_POST);
8616     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8617     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8618     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8619     TmpInst.addOperand(MCOperand::createImm(4));
8620     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8621     TmpInst.addOperand(Inst.getOperand(3));
8622     Inst = TmpInst;
8623     return true;
8624   }
8625   case ARM::t2STMDB_UPD: {
8626     // If this is a store of a single register, then we should use
8627     // a pre-indexed STR instruction instead, per the ARM ARM.
8628     if (Inst.getNumOperands() != 5)
8629       return false;
8630     MCInst TmpInst;
8631     TmpInst.setOpcode(ARM::t2STR_PRE);
8632     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8633     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8634     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8635     TmpInst.addOperand(MCOperand::createImm(-4));
8636     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8637     TmpInst.addOperand(Inst.getOperand(3));
8638     Inst = TmpInst;
8639     return true;
8640   }
8641   case ARM::LDMIA_UPD:
8642     // If this is a load of a single register via a 'pop', then we should use
8643     // a post-indexed LDR instruction instead, per the ARM ARM.
8644     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
8645         Inst.getNumOperands() == 5) {
8646       MCInst TmpInst;
8647       TmpInst.setOpcode(ARM::LDR_POST_IMM);
8648       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8649       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8650       TmpInst.addOperand(Inst.getOperand(1)); // Rn
8651       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
8652       TmpInst.addOperand(MCOperand::createImm(4));
8653       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8654       TmpInst.addOperand(Inst.getOperand(3));
8655       Inst = TmpInst;
8656       return true;
8657     }
8658     break;
8659   case ARM::STMDB_UPD:
8660     // If this is a store of a single register via a 'push', then we should use
8661     // a pre-indexed STR instruction instead, per the ARM ARM.
8662     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
8663         Inst.getNumOperands() == 5) {
8664       MCInst TmpInst;
8665       TmpInst.setOpcode(ARM::STR_PRE_IMM);
8666       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8667       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8668       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
8669       TmpInst.addOperand(MCOperand::createImm(-4));
8670       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8671       TmpInst.addOperand(Inst.getOperand(3));
8672       Inst = TmpInst;
8673     }
8674     break;
8675   case ARM::t2ADDri12:
8676     // If the immediate fits for encoding T3 (t2ADDri) and the generic "add"
8677     // mnemonic was used (not "addw"), encoding T3 is preferred.
8678     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "add" ||
8679         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8680       break;
8681     Inst.setOpcode(ARM::t2ADDri);
8682     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8683     break;
8684   case ARM::t2SUBri12:
8685     // If the immediate fits for encoding T3 (t2SUBri) and the generic "sub"
8686     // mnemonic was used (not "subw"), encoding T3 is preferred.
8687     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "sub" ||
8688         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8689       break;
8690     Inst.setOpcode(ARM::t2SUBri);
8691     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8692     break;
8693   case ARM::tADDi8:
8694     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8695     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8696     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8697     // to encoding T1 if <Rd> is omitted."
8698     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8699       Inst.setOpcode(ARM::tADDi3);
8700       return true;
8701     }
8702     break;
8703   case ARM::tSUBi8:
8704     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8705     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8706     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8707     // to encoding T1 if <Rd> is omitted."
8708     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8709       Inst.setOpcode(ARM::tSUBi3);
8710       return true;
8711     }
8712     break;
8713   case ARM::t2ADDri:
8714   case ARM::t2SUBri: {
8715     // If the destination and first source operand are the same, and
8716     // the flags are compatible with the current IT status, use encoding T2
8717     // instead of T3. For compatibility with the system 'as'. Make sure the
8718     // wide encoding wasn't explicit.
8719     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
8720         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
8721         (Inst.getOperand(2).isImm() &&
8722          (unsigned)Inst.getOperand(2).getImm() > 255) ||
8723         Inst.getOperand(5).getReg() != (inITBlock() ? 0 : ARM::CPSR) ||
8724         HasWideQualifier)
8725       break;
8726     MCInst TmpInst;
8727     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
8728                       ARM::tADDi8 : ARM::tSUBi8);
8729     TmpInst.addOperand(Inst.getOperand(0));
8730     TmpInst.addOperand(Inst.getOperand(5));
8731     TmpInst.addOperand(Inst.getOperand(0));
8732     TmpInst.addOperand(Inst.getOperand(2));
8733     TmpInst.addOperand(Inst.getOperand(3));
8734     TmpInst.addOperand(Inst.getOperand(4));
8735     Inst = TmpInst;
8736     return true;
8737   }
8738   case ARM::t2ADDrr: {
8739     // If the destination and first source operand are the same, and
8740     // there's no setting of the flags, use encoding T2 instead of T3.
8741     // Note that this is only for ADD, not SUB. This mirrors the system
8742     // 'as' behaviour.  Also take advantage of ADD being commutative.
8743     // Make sure the wide encoding wasn't explicit.
8744     bool Swap = false;
8745     auto DestReg = Inst.getOperand(0).getReg();
8746     bool Transform = DestReg == Inst.getOperand(1).getReg();
8747     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
8748       Transform = true;
8749       Swap = true;
8750     }
8751     if (!Transform ||
8752         Inst.getOperand(5).getReg() != 0 ||
8753         HasWideQualifier)
8754       break;
8755     MCInst TmpInst;
8756     TmpInst.setOpcode(ARM::tADDhirr);
8757     TmpInst.addOperand(Inst.getOperand(0));
8758     TmpInst.addOperand(Inst.getOperand(0));
8759     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
8760     TmpInst.addOperand(Inst.getOperand(3));
8761     TmpInst.addOperand(Inst.getOperand(4));
8762     Inst = TmpInst;
8763     return true;
8764   }
8765   case ARM::tADDrSP:
8766     // If the non-SP source operand and the destination operand are not the
8767     // same, we need to use the 32-bit encoding if it's available.
8768     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
8769       Inst.setOpcode(ARM::t2ADDrr);
8770       Inst.addOperand(MCOperand::createReg(0)); // cc_out
8771       return true;
8772     }
8773     break;
8774   case ARM::tB:
8775     // A Thumb conditional branch outside of an IT block is a tBcc.
8776     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
8777       Inst.setOpcode(ARM::tBcc);
8778       return true;
8779     }
8780     break;
8781   case ARM::t2B:
8782     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
8783     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
8784       Inst.setOpcode(ARM::t2Bcc);
8785       return true;
8786     }
8787     break;
8788   case ARM::t2Bcc:
8789     // If the conditional is AL or we're in an IT block, we really want t2B.
8790     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
8791       Inst.setOpcode(ARM::t2B);
8792       return true;
8793     }
8794     break;
8795   case ARM::tBcc:
8796     // If the conditional is AL, we really want tB.
8797     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
8798       Inst.setOpcode(ARM::tB);
8799       return true;
8800     }
8801     break;
8802   case ARM::tLDMIA: {
8803     // If the register list contains any high registers, or if the writeback
8804     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
8805     // instead if we're in Thumb2. Otherwise, this should have generated
8806     // an error in validateInstruction().
8807     unsigned Rn = Inst.getOperand(0).getReg();
8808     bool hasWritebackToken =
8809         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8810          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
8811     bool listContainsBase;
8812     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
8813         (!listContainsBase && !hasWritebackToken) ||
8814         (listContainsBase && hasWritebackToken)) {
8815       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8816       assert(isThumbTwo());
8817       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
8818       // If we're switching to the updating version, we need to insert
8819       // the writeback tied operand.
8820       if (hasWritebackToken)
8821         Inst.insert(Inst.begin(),
8822                     MCOperand::createReg(Inst.getOperand(0).getReg()));
8823       return true;
8824     }
8825     break;
8826   }
8827   case ARM::tSTMIA_UPD: {
8828     // If the register list contains any high registers, we need to use
8829     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8830     // should have generated an error in validateInstruction().
8831     unsigned Rn = Inst.getOperand(0).getReg();
8832     bool listContainsBase;
8833     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
8834       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8835       assert(isThumbTwo());
8836       Inst.setOpcode(ARM::t2STMIA_UPD);
8837       return true;
8838     }
8839     break;
8840   }
8841   case ARM::tPOP: {
8842     bool listContainsBase;
8843     // If the register list contains any high registers, we need to use
8844     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8845     // should have generated an error in validateInstruction().
8846     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
8847       return false;
8848     assert(isThumbTwo());
8849     Inst.setOpcode(ARM::t2LDMIA_UPD);
8850     // Add the base register and writeback operands.
8851     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8852     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8853     return true;
8854   }
8855   case ARM::tPUSH: {
8856     bool listContainsBase;
8857     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
8858       return false;
8859     assert(isThumbTwo());
8860     Inst.setOpcode(ARM::t2STMDB_UPD);
8861     // Add the base register and writeback operands.
8862     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8863     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8864     return true;
8865   }
8866   case ARM::t2MOVi:
8867     // If we can use the 16-bit encoding and the user didn't explicitly
8868     // request the 32-bit variant, transform it here.
8869     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8870         (Inst.getOperand(1).isImm() &&
8871          (unsigned)Inst.getOperand(1).getImm() <= 255) &&
8872         Inst.getOperand(4).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8873         !HasWideQualifier) {
8874       // The operands aren't in the same order for tMOVi8...
8875       MCInst TmpInst;
8876       TmpInst.setOpcode(ARM::tMOVi8);
8877       TmpInst.addOperand(Inst.getOperand(0));
8878       TmpInst.addOperand(Inst.getOperand(4));
8879       TmpInst.addOperand(Inst.getOperand(1));
8880       TmpInst.addOperand(Inst.getOperand(2));
8881       TmpInst.addOperand(Inst.getOperand(3));
8882       Inst = TmpInst;
8883       return true;
8884     }
8885     break;
8886 
8887   case ARM::t2MOVr:
8888     // If we can use the 16-bit encoding and the user didn't explicitly
8889     // request the 32-bit variant, transform it here.
8890     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8891         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8892         Inst.getOperand(2).getImm() == ARMCC::AL &&
8893         Inst.getOperand(4).getReg() == ARM::CPSR &&
8894         !HasWideQualifier) {
8895       // The operands aren't the same for tMOV[S]r... (no cc_out)
8896       MCInst TmpInst;
8897       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
8898       TmpInst.addOperand(Inst.getOperand(0));
8899       TmpInst.addOperand(Inst.getOperand(1));
8900       TmpInst.addOperand(Inst.getOperand(2));
8901       TmpInst.addOperand(Inst.getOperand(3));
8902       Inst = TmpInst;
8903       return true;
8904     }
8905     break;
8906 
8907   case ARM::t2SXTH:
8908   case ARM::t2SXTB:
8909   case ARM::t2UXTH:
8910   case ARM::t2UXTB:
8911     // If we can use the 16-bit encoding and the user didn't explicitly
8912     // request the 32-bit variant, transform it here.
8913     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8914         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8915         Inst.getOperand(2).getImm() == 0 &&
8916         !HasWideQualifier) {
8917       unsigned NewOpc;
8918       switch (Inst.getOpcode()) {
8919       default: llvm_unreachable("Illegal opcode!");
8920       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
8921       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
8922       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
8923       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
8924       }
8925       // The operands aren't the same for thumb1 (no rotate operand).
8926       MCInst TmpInst;
8927       TmpInst.setOpcode(NewOpc);
8928       TmpInst.addOperand(Inst.getOperand(0));
8929       TmpInst.addOperand(Inst.getOperand(1));
8930       TmpInst.addOperand(Inst.getOperand(3));
8931       TmpInst.addOperand(Inst.getOperand(4));
8932       Inst = TmpInst;
8933       return true;
8934     }
8935     break;
8936 
8937   case ARM::MOVsi: {
8938     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8939     // rrx shifts and asr/lsr of #32 is encoded as 0
8940     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr)
8941       return false;
8942     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
8943       // Shifting by zero is accepted as a vanilla 'MOVr'
8944       MCInst TmpInst;
8945       TmpInst.setOpcode(ARM::MOVr);
8946       TmpInst.addOperand(Inst.getOperand(0));
8947       TmpInst.addOperand(Inst.getOperand(1));
8948       TmpInst.addOperand(Inst.getOperand(3));
8949       TmpInst.addOperand(Inst.getOperand(4));
8950       TmpInst.addOperand(Inst.getOperand(5));
8951       Inst = TmpInst;
8952       return true;
8953     }
8954     return false;
8955   }
8956   case ARM::ANDrsi:
8957   case ARM::ORRrsi:
8958   case ARM::EORrsi:
8959   case ARM::BICrsi:
8960   case ARM::SUBrsi:
8961   case ARM::ADDrsi: {
8962     unsigned newOpc;
8963     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
8964     if (SOpc == ARM_AM::rrx) return false;
8965     switch (Inst.getOpcode()) {
8966     default: llvm_unreachable("unexpected opcode!");
8967     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
8968     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
8969     case ARM::EORrsi: newOpc = ARM::EORrr; break;
8970     case ARM::BICrsi: newOpc = ARM::BICrr; break;
8971     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
8972     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
8973     }
8974     // If the shift is by zero, use the non-shifted instruction definition.
8975     // The exception is for right shifts, where 0 == 32
8976     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
8977         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
8978       MCInst TmpInst;
8979       TmpInst.setOpcode(newOpc);
8980       TmpInst.addOperand(Inst.getOperand(0));
8981       TmpInst.addOperand(Inst.getOperand(1));
8982       TmpInst.addOperand(Inst.getOperand(2));
8983       TmpInst.addOperand(Inst.getOperand(4));
8984       TmpInst.addOperand(Inst.getOperand(5));
8985       TmpInst.addOperand(Inst.getOperand(6));
8986       Inst = TmpInst;
8987       return true;
8988     }
8989     return false;
8990   }
8991   case ARM::ITasm:
8992   case ARM::t2IT: {
8993     MCOperand &MO = Inst.getOperand(1);
8994     unsigned Mask = MO.getImm();
8995     ARMCC::CondCodes Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
8996 
8997     // Set up the IT block state according to the IT instruction we just
8998     // matched.
8999     assert(!inITBlock() && "nested IT blocks?!");
9000     startExplicitITBlock(Cond, Mask);
9001     MO.setImm(getITMaskEncoding());
9002     break;
9003   }
9004   case ARM::t2LSLrr:
9005   case ARM::t2LSRrr:
9006   case ARM::t2ASRrr:
9007   case ARM::t2SBCrr:
9008   case ARM::t2RORrr:
9009   case ARM::t2BICrr:
9010     // Assemblers should use the narrow encodings of these instructions when permissible.
9011     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
9012          isARMLowRegister(Inst.getOperand(2).getReg())) &&
9013         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
9014         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
9015         !HasWideQualifier) {
9016       unsigned NewOpc;
9017       switch (Inst.getOpcode()) {
9018         default: llvm_unreachable("unexpected opcode");
9019         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
9020         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
9021         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
9022         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
9023         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
9024         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
9025       }
9026       MCInst TmpInst;
9027       TmpInst.setOpcode(NewOpc);
9028       TmpInst.addOperand(Inst.getOperand(0));
9029       TmpInst.addOperand(Inst.getOperand(5));
9030       TmpInst.addOperand(Inst.getOperand(1));
9031       TmpInst.addOperand(Inst.getOperand(2));
9032       TmpInst.addOperand(Inst.getOperand(3));
9033       TmpInst.addOperand(Inst.getOperand(4));
9034       Inst = TmpInst;
9035       return true;
9036     }
9037     return false;
9038 
9039   case ARM::t2ANDrr:
9040   case ARM::t2EORrr:
9041   case ARM::t2ADCrr:
9042   case ARM::t2ORRrr:
9043     // Assemblers should use the narrow encodings of these instructions when permissible.
9044     // These instructions are special in that they are commutable, so shorter encodings
9045     // are available more often.
9046     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
9047          isARMLowRegister(Inst.getOperand(2).getReg())) &&
9048         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
9049          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
9050         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
9051         !HasWideQualifier) {
9052       unsigned NewOpc;
9053       switch (Inst.getOpcode()) {
9054         default: llvm_unreachable("unexpected opcode");
9055         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
9056         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
9057         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
9058         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
9059       }
9060       MCInst TmpInst;
9061       TmpInst.setOpcode(NewOpc);
9062       TmpInst.addOperand(Inst.getOperand(0));
9063       TmpInst.addOperand(Inst.getOperand(5));
9064       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
9065         TmpInst.addOperand(Inst.getOperand(1));
9066         TmpInst.addOperand(Inst.getOperand(2));
9067       } else {
9068         TmpInst.addOperand(Inst.getOperand(2));
9069         TmpInst.addOperand(Inst.getOperand(1));
9070       }
9071       TmpInst.addOperand(Inst.getOperand(3));
9072       TmpInst.addOperand(Inst.getOperand(4));
9073       Inst = TmpInst;
9074       return true;
9075     }
9076     return false;
9077   }
9078   return false;
9079 }
9080 
checkTargetMatchPredicate(MCInst & Inst)9081 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
9082   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
9083   // suffix depending on whether they're in an IT block or not.
9084   unsigned Opc = Inst.getOpcode();
9085   const MCInstrDesc &MCID = MII.get(Opc);
9086   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
9087     assert(MCID.hasOptionalDef() &&
9088            "optionally flag setting instruction missing optional def operand");
9089     assert(MCID.NumOperands == Inst.getNumOperands() &&
9090            "operand count mismatch!");
9091     // Find the optional-def operand (cc_out).
9092     unsigned OpNo;
9093     for (OpNo = 0;
9094          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
9095          ++OpNo)
9096       ;
9097     // If we're parsing Thumb1, reject it completely.
9098     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
9099       return Match_RequiresFlagSetting;
9100     // If we're parsing Thumb2, which form is legal depends on whether we're
9101     // in an IT block.
9102     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
9103         !inITBlock())
9104       return Match_RequiresITBlock;
9105     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
9106         inITBlock())
9107       return Match_RequiresNotITBlock;
9108     // LSL with zero immediate is not allowed in an IT block
9109     if (Opc == ARM::tLSLri && Inst.getOperand(3).getImm() == 0 && inITBlock())
9110       return Match_RequiresNotITBlock;
9111   } else if (isThumbOne()) {
9112     // Some high-register supporting Thumb1 encodings only allow both registers
9113     // to be from r0-r7 when in Thumb2.
9114     if (Opc == ARM::tADDhirr && !hasV6MOps() &&
9115         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9116         isARMLowRegister(Inst.getOperand(2).getReg()))
9117       return Match_RequiresThumb2;
9118     // Others only require ARMv6 or later.
9119     else if (Opc == ARM::tMOVr && !hasV6Ops() &&
9120              isARMLowRegister(Inst.getOperand(0).getReg()) &&
9121              isARMLowRegister(Inst.getOperand(1).getReg()))
9122       return Match_RequiresV6;
9123   }
9124 
9125   // Before ARMv8 the rules for when SP is allowed in t2MOVr are more complex
9126   // than the loop below can handle, so it uses the GPRnopc register class and
9127   // we do SP handling here.
9128   if (Opc == ARM::t2MOVr && !hasV8Ops())
9129   {
9130     // SP as both source and destination is not allowed
9131     if (Inst.getOperand(0).getReg() == ARM::SP &&
9132         Inst.getOperand(1).getReg() == ARM::SP)
9133       return Match_RequiresV8;
9134     // When flags-setting SP as either source or destination is not allowed
9135     if (Inst.getOperand(4).getReg() == ARM::CPSR &&
9136         (Inst.getOperand(0).getReg() == ARM::SP ||
9137          Inst.getOperand(1).getReg() == ARM::SP))
9138       return Match_RequiresV8;
9139   }
9140 
9141   // Use of SP for VMRS/VMSR is only allowed in ARM mode with the exception of
9142   // ARMv8-A.
9143   if ((Inst.getOpcode() == ARM::VMRS || Inst.getOpcode() == ARM::VMSR) &&
9144       Inst.getOperand(0).getReg() == ARM::SP && (isThumb() && !hasV8Ops()))
9145     return Match_InvalidOperand;
9146 
9147   for (unsigned I = 0; I < MCID.NumOperands; ++I)
9148     if (MCID.OpInfo[I].RegClass == ARM::rGPRRegClassID) {
9149       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
9150       if ((Inst.getOperand(I).getReg() == ARM::SP) && !hasV8Ops())
9151         return Match_RequiresV8;
9152       else if (Inst.getOperand(I).getReg() == ARM::PC)
9153         return Match_InvalidOperand;
9154     }
9155 
9156   return Match_Success;
9157 }
9158 
9159 namespace llvm {
9160 
IsCPSRDead(const MCInst * Instr)9161 template <> inline bool IsCPSRDead<MCInst>(const MCInst *Instr) {
9162   return true; // In an assembly source, no need to second-guess
9163 }
9164 
9165 } // end namespace llvm
9166 
9167 // Returns true if Inst is unpredictable if it is in and IT block, but is not
9168 // the last instruction in the block.
isITBlockTerminator(MCInst & Inst) const9169 bool ARMAsmParser::isITBlockTerminator(MCInst &Inst) const {
9170   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
9171 
9172   // All branch & call instructions terminate IT blocks with the exception of
9173   // SVC.
9174   if (MCID.isTerminator() || (MCID.isCall() && Inst.getOpcode() != ARM::tSVC) ||
9175       MCID.isReturn() || MCID.isBranch() || MCID.isIndirectBranch())
9176     return true;
9177 
9178   // Any arithmetic instruction which writes to the PC also terminates the IT
9179   // block.
9180   if (MCID.hasDefOfPhysReg(Inst, ARM::PC, *MRI))
9181     return true;
9182 
9183   return false;
9184 }
9185 
MatchInstruction(OperandVector & Operands,MCInst & Inst,SmallVectorImpl<NearMissInfo> & NearMisses,bool MatchingInlineAsm,bool & EmitInITBlock,MCStreamer & Out)9186 unsigned ARMAsmParser::MatchInstruction(OperandVector &Operands, MCInst &Inst,
9187                                           SmallVectorImpl<NearMissInfo> &NearMisses,
9188                                           bool MatchingInlineAsm,
9189                                           bool &EmitInITBlock,
9190                                           MCStreamer &Out) {
9191   // If we can't use an implicit IT block here, just match as normal.
9192   if (inExplicitITBlock() || !isThumbTwo() || !useImplicitITThumb())
9193     return MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
9194 
9195   // Try to match the instruction in an extension of the current IT block (if
9196   // there is one).
9197   if (inImplicitITBlock()) {
9198     extendImplicitITBlock(ITState.Cond);
9199     if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
9200             Match_Success) {
9201       // The match succeded, but we still have to check that the instruction is
9202       // valid in this implicit IT block.
9203       const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
9204       if (MCID.isPredicable()) {
9205         ARMCC::CondCodes InstCond =
9206             (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
9207                 .getImm();
9208         ARMCC::CondCodes ITCond = currentITCond();
9209         if (InstCond == ITCond) {
9210           EmitInITBlock = true;
9211           return Match_Success;
9212         } else if (InstCond == ARMCC::getOppositeCondition(ITCond)) {
9213           invertCurrentITCondition();
9214           EmitInITBlock = true;
9215           return Match_Success;
9216         }
9217       }
9218     }
9219     rewindImplicitITPosition();
9220   }
9221 
9222   // Finish the current IT block, and try to match outside any IT block.
9223   flushPendingInstructions(Out);
9224   unsigned PlainMatchResult =
9225       MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
9226   if (PlainMatchResult == Match_Success) {
9227     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
9228     if (MCID.isPredicable()) {
9229       ARMCC::CondCodes InstCond =
9230           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
9231               .getImm();
9232       // Some forms of the branch instruction have their own condition code
9233       // fields, so can be conditionally executed without an IT block.
9234       if (Inst.getOpcode() == ARM::tBcc || Inst.getOpcode() == ARM::t2Bcc) {
9235         EmitInITBlock = false;
9236         return Match_Success;
9237       }
9238       if (InstCond == ARMCC::AL) {
9239         EmitInITBlock = false;
9240         return Match_Success;
9241       }
9242     } else {
9243       EmitInITBlock = false;
9244       return Match_Success;
9245     }
9246   }
9247 
9248   // Try to match in a new IT block. The matcher doesn't check the actual
9249   // condition, so we create an IT block with a dummy condition, and fix it up
9250   // once we know the actual condition.
9251   startImplicitITBlock();
9252   if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
9253       Match_Success) {
9254     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
9255     if (MCID.isPredicable()) {
9256       ITState.Cond =
9257           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
9258               .getImm();
9259       EmitInITBlock = true;
9260       return Match_Success;
9261     }
9262   }
9263   discardImplicitITBlock();
9264 
9265   // If none of these succeed, return the error we got when trying to match
9266   // outside any IT blocks.
9267   EmitInITBlock = false;
9268   return PlainMatchResult;
9269 }
9270 
9271 static std::string ARMMnemonicSpellCheck(StringRef S, uint64_t FBS,
9272                                          unsigned VariantID = 0);
9273 
9274 static const char *getSubtargetFeatureName(uint64_t Val);
MatchAndEmitInstruction(SMLoc IDLoc,unsigned & Opcode,OperandVector & Operands,MCStreamer & Out,uint64_t & ErrorInfo,bool MatchingInlineAsm)9275 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
9276                                            OperandVector &Operands,
9277                                            MCStreamer &Out, uint64_t &ErrorInfo,
9278                                            bool MatchingInlineAsm) {
9279   MCInst Inst;
9280   unsigned MatchResult;
9281   bool PendConditionalInstruction = false;
9282 
9283   SmallVector<NearMissInfo, 4> NearMisses;
9284   MatchResult = MatchInstruction(Operands, Inst, NearMisses, MatchingInlineAsm,
9285                                  PendConditionalInstruction, Out);
9286 
9287   switch (MatchResult) {
9288   case Match_Success:
9289     LLVM_DEBUG(dbgs() << "Parsed as: ";
9290                Inst.dump_pretty(dbgs(), MII.getName(Inst.getOpcode()));
9291                dbgs() << "\n");
9292 
9293     // Context sensitive operand constraints aren't handled by the matcher,
9294     // so check them here.
9295     if (validateInstruction(Inst, Operands)) {
9296       // Still progress the IT block, otherwise one wrong condition causes
9297       // nasty cascading errors.
9298       forwardITPosition();
9299       return true;
9300     }
9301 
9302     { // processInstruction() updates inITBlock state, we need to save it away
9303       bool wasInITBlock = inITBlock();
9304 
9305       // Some instructions need post-processing to, for example, tweak which
9306       // encoding is selected. Loop on it while changes happen so the
9307       // individual transformations can chain off each other. E.g.,
9308       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
9309       while (processInstruction(Inst, Operands, Out))
9310         LLVM_DEBUG(dbgs() << "Changed to: ";
9311                    Inst.dump_pretty(dbgs(), MII.getName(Inst.getOpcode()));
9312                    dbgs() << "\n");
9313 
9314       // Only after the instruction is fully processed, we can validate it
9315       if (wasInITBlock && hasV8Ops() && isThumb() &&
9316           !isV8EligibleForIT(&Inst)) {
9317         Warning(IDLoc, "deprecated instruction in IT block");
9318       }
9319     }
9320 
9321     // Only move forward at the very end so that everything in validate
9322     // and process gets a consistent answer about whether we're in an IT
9323     // block.
9324     forwardITPosition();
9325 
9326     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
9327     // doesn't actually encode.
9328     if (Inst.getOpcode() == ARM::ITasm)
9329       return false;
9330 
9331     Inst.setLoc(IDLoc);
9332     if (PendConditionalInstruction) {
9333       PendingConditionalInsts.push_back(Inst);
9334       if (isITBlockFull() || isITBlockTerminator(Inst))
9335         flushPendingInstructions(Out);
9336     } else {
9337       Out.EmitInstruction(Inst, getSTI());
9338     }
9339     return false;
9340   case Match_NearMisses:
9341     ReportNearMisses(NearMisses, IDLoc, Operands);
9342     return true;
9343   case Match_MnemonicFail: {
9344     uint64_t FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
9345     std::string Suggestion = ARMMnemonicSpellCheck(
9346       ((ARMOperand &)*Operands[0]).getToken(), FBS);
9347     return Error(IDLoc, "invalid instruction" + Suggestion,
9348                  ((ARMOperand &)*Operands[0]).getLocRange());
9349   }
9350   }
9351 
9352   llvm_unreachable("Implement any new match types added!");
9353 }
9354 
9355 /// parseDirective parses the arm specific directives
ParseDirective(AsmToken DirectiveID)9356 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
9357   const MCObjectFileInfo::Environment Format =
9358     getContext().getObjectFileInfo()->getObjectFileType();
9359   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9360   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
9361 
9362   StringRef IDVal = DirectiveID.getIdentifier();
9363   if (IDVal == ".word")
9364     parseLiteralValues(4, DirectiveID.getLoc());
9365   else if (IDVal == ".short" || IDVal == ".hword")
9366     parseLiteralValues(2, DirectiveID.getLoc());
9367   else if (IDVal == ".thumb")
9368     parseDirectiveThumb(DirectiveID.getLoc());
9369   else if (IDVal == ".arm")
9370     parseDirectiveARM(DirectiveID.getLoc());
9371   else if (IDVal == ".thumb_func")
9372     parseDirectiveThumbFunc(DirectiveID.getLoc());
9373   else if (IDVal == ".code")
9374     parseDirectiveCode(DirectiveID.getLoc());
9375   else if (IDVal == ".syntax")
9376     parseDirectiveSyntax(DirectiveID.getLoc());
9377   else if (IDVal == ".unreq")
9378     parseDirectiveUnreq(DirectiveID.getLoc());
9379   else if (IDVal == ".fnend")
9380     parseDirectiveFnEnd(DirectiveID.getLoc());
9381   else if (IDVal == ".cantunwind")
9382     parseDirectiveCantUnwind(DirectiveID.getLoc());
9383   else if (IDVal == ".personality")
9384     parseDirectivePersonality(DirectiveID.getLoc());
9385   else if (IDVal == ".handlerdata")
9386     parseDirectiveHandlerData(DirectiveID.getLoc());
9387   else if (IDVal == ".setfp")
9388     parseDirectiveSetFP(DirectiveID.getLoc());
9389   else if (IDVal == ".pad")
9390     parseDirectivePad(DirectiveID.getLoc());
9391   else if (IDVal == ".save")
9392     parseDirectiveRegSave(DirectiveID.getLoc(), false);
9393   else if (IDVal == ".vsave")
9394     parseDirectiveRegSave(DirectiveID.getLoc(), true);
9395   else if (IDVal == ".ltorg" || IDVal == ".pool")
9396     parseDirectiveLtorg(DirectiveID.getLoc());
9397   else if (IDVal == ".even")
9398     parseDirectiveEven(DirectiveID.getLoc());
9399   else if (IDVal == ".personalityindex")
9400     parseDirectivePersonalityIndex(DirectiveID.getLoc());
9401   else if (IDVal == ".unwind_raw")
9402     parseDirectiveUnwindRaw(DirectiveID.getLoc());
9403   else if (IDVal == ".movsp")
9404     parseDirectiveMovSP(DirectiveID.getLoc());
9405   else if (IDVal == ".arch_extension")
9406     parseDirectiveArchExtension(DirectiveID.getLoc());
9407   else if (IDVal == ".align")
9408     return parseDirectiveAlign(DirectiveID.getLoc()); // Use Generic on failure.
9409   else if (IDVal == ".thumb_set")
9410     parseDirectiveThumbSet(DirectiveID.getLoc());
9411   else if (IDVal == ".inst")
9412     parseDirectiveInst(DirectiveID.getLoc());
9413   else if (IDVal == ".inst.n")
9414     parseDirectiveInst(DirectiveID.getLoc(), 'n');
9415   else if (IDVal == ".inst.w")
9416     parseDirectiveInst(DirectiveID.getLoc(), 'w');
9417   else if (!IsMachO && !IsCOFF) {
9418     if (IDVal == ".arch")
9419       parseDirectiveArch(DirectiveID.getLoc());
9420     else if (IDVal == ".cpu")
9421       parseDirectiveCPU(DirectiveID.getLoc());
9422     else if (IDVal == ".eabi_attribute")
9423       parseDirectiveEabiAttr(DirectiveID.getLoc());
9424     else if (IDVal == ".fpu")
9425       parseDirectiveFPU(DirectiveID.getLoc());
9426     else if (IDVal == ".fnstart")
9427       parseDirectiveFnStart(DirectiveID.getLoc());
9428     else if (IDVal == ".object_arch")
9429       parseDirectiveObjectArch(DirectiveID.getLoc());
9430     else if (IDVal == ".tlsdescseq")
9431       parseDirectiveTLSDescSeq(DirectiveID.getLoc());
9432     else
9433       return true;
9434   } else
9435     return true;
9436   return false;
9437 }
9438 
9439 /// parseLiteralValues
9440 ///  ::= .hword expression [, expression]*
9441 ///  ::= .short expression [, expression]*
9442 ///  ::= .word expression [, expression]*
parseLiteralValues(unsigned Size,SMLoc L)9443 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
9444   auto parseOne = [&]() -> bool {
9445     const MCExpr *Value;
9446     if (getParser().parseExpression(Value))
9447       return true;
9448     getParser().getStreamer().EmitValue(Value, Size, L);
9449     return false;
9450   };
9451   return (parseMany(parseOne));
9452 }
9453 
9454 /// parseDirectiveThumb
9455 ///  ::= .thumb
parseDirectiveThumb(SMLoc L)9456 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
9457   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9458       check(!hasThumb(), L, "target does not support Thumb mode"))
9459     return true;
9460 
9461   if (!isThumb())
9462     SwitchMode();
9463 
9464   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9465   return false;
9466 }
9467 
9468 /// parseDirectiveARM
9469 ///  ::= .arm
parseDirectiveARM(SMLoc L)9470 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
9471   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9472       check(!hasARM(), L, "target does not support ARM mode"))
9473     return true;
9474 
9475   if (isThumb())
9476     SwitchMode();
9477   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9478   return false;
9479 }
9480 
doBeforeLabelEmit(MCSymbol * Symbol)9481 void ARMAsmParser::doBeforeLabelEmit(MCSymbol *Symbol) {
9482   // We need to flush the current implicit IT block on a label, because it is
9483   // not legal to branch into an IT block.
9484   flushPendingInstructions(getStreamer());
9485 }
9486 
onLabelParsed(MCSymbol * Symbol)9487 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
9488   if (NextSymbolIsThumb) {
9489     getParser().getStreamer().EmitThumbFunc(Symbol);
9490     NextSymbolIsThumb = false;
9491   }
9492 }
9493 
9494 /// parseDirectiveThumbFunc
9495 ///  ::= .thumbfunc symbol_name
parseDirectiveThumbFunc(SMLoc L)9496 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
9497   MCAsmParser &Parser = getParser();
9498   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
9499   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9500 
9501   // Darwin asm has (optionally) function name after .thumb_func direction
9502   // ELF doesn't
9503 
9504   if (IsMachO) {
9505     if (Parser.getTok().is(AsmToken::Identifier) ||
9506         Parser.getTok().is(AsmToken::String)) {
9507       MCSymbol *Func = getParser().getContext().getOrCreateSymbol(
9508           Parser.getTok().getIdentifier());
9509       getParser().getStreamer().EmitThumbFunc(Func);
9510       Parser.Lex();
9511       if (parseToken(AsmToken::EndOfStatement,
9512                      "unexpected token in '.thumb_func' directive"))
9513         return true;
9514       return false;
9515     }
9516   }
9517 
9518   if (parseToken(AsmToken::EndOfStatement,
9519                  "unexpected token in '.thumb_func' directive"))
9520     return true;
9521 
9522   NextSymbolIsThumb = true;
9523   return false;
9524 }
9525 
9526 /// parseDirectiveSyntax
9527 ///  ::= .syntax unified | divided
parseDirectiveSyntax(SMLoc L)9528 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
9529   MCAsmParser &Parser = getParser();
9530   const AsmToken &Tok = Parser.getTok();
9531   if (Tok.isNot(AsmToken::Identifier)) {
9532     Error(L, "unexpected token in .syntax directive");
9533     return false;
9534   }
9535 
9536   StringRef Mode = Tok.getString();
9537   Parser.Lex();
9538   if (check(Mode == "divided" || Mode == "DIVIDED", L,
9539             "'.syntax divided' arm assembly not supported") ||
9540       check(Mode != "unified" && Mode != "UNIFIED", L,
9541             "unrecognized syntax mode in .syntax directive") ||
9542       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9543     return true;
9544 
9545   // TODO tell the MC streamer the mode
9546   // getParser().getStreamer().Emit???();
9547   return false;
9548 }
9549 
9550 /// parseDirectiveCode
9551 ///  ::= .code 16 | 32
parseDirectiveCode(SMLoc L)9552 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
9553   MCAsmParser &Parser = getParser();
9554   const AsmToken &Tok = Parser.getTok();
9555   if (Tok.isNot(AsmToken::Integer))
9556     return Error(L, "unexpected token in .code directive");
9557   int64_t Val = Parser.getTok().getIntVal();
9558   if (Val != 16 && Val != 32) {
9559     Error(L, "invalid operand to .code directive");
9560     return false;
9561   }
9562   Parser.Lex();
9563 
9564   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9565     return true;
9566 
9567   if (Val == 16) {
9568     if (!hasThumb())
9569       return Error(L, "target does not support Thumb mode");
9570 
9571     if (!isThumb())
9572       SwitchMode();
9573     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9574   } else {
9575     if (!hasARM())
9576       return Error(L, "target does not support ARM mode");
9577 
9578     if (isThumb())
9579       SwitchMode();
9580     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9581   }
9582 
9583   return false;
9584 }
9585 
9586 /// parseDirectiveReq
9587 ///  ::= name .req registername
parseDirectiveReq(StringRef Name,SMLoc L)9588 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
9589   MCAsmParser &Parser = getParser();
9590   Parser.Lex(); // Eat the '.req' token.
9591   unsigned Reg;
9592   SMLoc SRegLoc, ERegLoc;
9593   if (check(ParseRegister(Reg, SRegLoc, ERegLoc), SRegLoc,
9594             "register name expected") ||
9595       parseToken(AsmToken::EndOfStatement,
9596                  "unexpected input in .req directive."))
9597     return true;
9598 
9599   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg)
9600     return Error(SRegLoc,
9601                  "redefinition of '" + Name + "' does not match original.");
9602 
9603   return false;
9604 }
9605 
9606 /// parseDirectiveUneq
9607 ///  ::= .unreq registername
parseDirectiveUnreq(SMLoc L)9608 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
9609   MCAsmParser &Parser = getParser();
9610   if (Parser.getTok().isNot(AsmToken::Identifier))
9611     return Error(L, "unexpected input in .unreq directive.");
9612   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
9613   Parser.Lex(); // Eat the identifier.
9614   if (parseToken(AsmToken::EndOfStatement,
9615                  "unexpected input in '.unreq' directive"))
9616     return true;
9617   return false;
9618 }
9619 
9620 // After changing arch/CPU, try to put the ARM/Thumb mode back to what it was
9621 // before, if supported by the new target, or emit mapping symbols for the mode
9622 // switch.
FixModeAfterArchChange(bool WasThumb,SMLoc Loc)9623 void ARMAsmParser::FixModeAfterArchChange(bool WasThumb, SMLoc Loc) {
9624   if (WasThumb != isThumb()) {
9625     if (WasThumb && hasThumb()) {
9626       // Stay in Thumb mode
9627       SwitchMode();
9628     } else if (!WasThumb && hasARM()) {
9629       // Stay in ARM mode
9630       SwitchMode();
9631     } else {
9632       // Mode switch forced, because the new arch doesn't support the old mode.
9633       getParser().getStreamer().EmitAssemblerFlag(isThumb() ? MCAF_Code16
9634                                                             : MCAF_Code32);
9635       // Warn about the implcit mode switch. GAS does not switch modes here,
9636       // but instead stays in the old mode, reporting an error on any following
9637       // instructions as the mode does not exist on the target.
9638       Warning(Loc, Twine("new target does not support ") +
9639                        (WasThumb ? "thumb" : "arm") + " mode, switching to " +
9640                        (!WasThumb ? "thumb" : "arm") + " mode");
9641     }
9642   }
9643 }
9644 
9645 /// parseDirectiveArch
9646 ///  ::= .arch token
parseDirectiveArch(SMLoc L)9647 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
9648   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
9649   ARM::ArchKind ID = ARM::parseArch(Arch);
9650 
9651   if (ID == ARM::ArchKind::INVALID)
9652     return Error(L, "Unknown arch name");
9653 
9654   bool WasThumb = isThumb();
9655   Triple T;
9656   MCSubtargetInfo &STI = copySTI();
9657   STI.setDefaultFeatures("", ("+" + ARM::getArchName(ID)).str());
9658   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9659   FixModeAfterArchChange(WasThumb, L);
9660 
9661   getTargetStreamer().emitArch(ID);
9662   return false;
9663 }
9664 
9665 /// parseDirectiveEabiAttr
9666 ///  ::= .eabi_attribute int, int [, "str"]
9667 ///  ::= .eabi_attribute Tag_name, int [, "str"]
parseDirectiveEabiAttr(SMLoc L)9668 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
9669   MCAsmParser &Parser = getParser();
9670   int64_t Tag;
9671   SMLoc TagLoc;
9672   TagLoc = Parser.getTok().getLoc();
9673   if (Parser.getTok().is(AsmToken::Identifier)) {
9674     StringRef Name = Parser.getTok().getIdentifier();
9675     Tag = ARMBuildAttrs::AttrTypeFromString(Name);
9676     if (Tag == -1) {
9677       Error(TagLoc, "attribute name not recognised: " + Name);
9678       return false;
9679     }
9680     Parser.Lex();
9681   } else {
9682     const MCExpr *AttrExpr;
9683 
9684     TagLoc = Parser.getTok().getLoc();
9685     if (Parser.parseExpression(AttrExpr))
9686       return true;
9687 
9688     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
9689     if (check(!CE, TagLoc, "expected numeric constant"))
9690       return true;
9691 
9692     Tag = CE->getValue();
9693   }
9694 
9695   if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9696     return true;
9697 
9698   StringRef StringValue = "";
9699   bool IsStringValue = false;
9700 
9701   int64_t IntegerValue = 0;
9702   bool IsIntegerValue = false;
9703 
9704   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
9705     IsStringValue = true;
9706   else if (Tag == ARMBuildAttrs::compatibility) {
9707     IsStringValue = true;
9708     IsIntegerValue = true;
9709   } else if (Tag < 32 || Tag % 2 == 0)
9710     IsIntegerValue = true;
9711   else if (Tag % 2 == 1)
9712     IsStringValue = true;
9713   else
9714     llvm_unreachable("invalid tag type");
9715 
9716   if (IsIntegerValue) {
9717     const MCExpr *ValueExpr;
9718     SMLoc ValueExprLoc = Parser.getTok().getLoc();
9719     if (Parser.parseExpression(ValueExpr))
9720       return true;
9721 
9722     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
9723     if (!CE)
9724       return Error(ValueExprLoc, "expected numeric constant");
9725     IntegerValue = CE->getValue();
9726   }
9727 
9728   if (Tag == ARMBuildAttrs::compatibility) {
9729     if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9730       return true;
9731   }
9732 
9733   if (IsStringValue) {
9734     if (Parser.getTok().isNot(AsmToken::String))
9735       return Error(Parser.getTok().getLoc(), "bad string constant");
9736 
9737     StringValue = Parser.getTok().getStringContents();
9738     Parser.Lex();
9739   }
9740 
9741   if (Parser.parseToken(AsmToken::EndOfStatement,
9742                         "unexpected token in '.eabi_attribute' directive"))
9743     return true;
9744 
9745   if (IsIntegerValue && IsStringValue) {
9746     assert(Tag == ARMBuildAttrs::compatibility);
9747     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
9748   } else if (IsIntegerValue)
9749     getTargetStreamer().emitAttribute(Tag, IntegerValue);
9750   else if (IsStringValue)
9751     getTargetStreamer().emitTextAttribute(Tag, StringValue);
9752   return false;
9753 }
9754 
9755 /// parseDirectiveCPU
9756 ///  ::= .cpu str
parseDirectiveCPU(SMLoc L)9757 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
9758   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
9759   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
9760 
9761   // FIXME: This is using table-gen data, but should be moved to
9762   // ARMTargetParser once that is table-gen'd.
9763   if (!getSTI().isCPUStringValid(CPU))
9764     return Error(L, "Unknown CPU name");
9765 
9766   bool WasThumb = isThumb();
9767   MCSubtargetInfo &STI = copySTI();
9768   STI.setDefaultFeatures(CPU, "");
9769   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9770   FixModeAfterArchChange(WasThumb, L);
9771 
9772   return false;
9773 }
9774 
9775 /// parseDirectiveFPU
9776 ///  ::= .fpu str
parseDirectiveFPU(SMLoc L)9777 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
9778   SMLoc FPUNameLoc = getTok().getLoc();
9779   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
9780 
9781   unsigned ID = ARM::parseFPU(FPU);
9782   std::vector<StringRef> Features;
9783   if (!ARM::getFPUFeatures(ID, Features))
9784     return Error(FPUNameLoc, "Unknown FPU name");
9785 
9786   MCSubtargetInfo &STI = copySTI();
9787   for (auto Feature : Features)
9788     STI.ApplyFeatureFlag(Feature);
9789   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9790 
9791   getTargetStreamer().emitFPU(ID);
9792   return false;
9793 }
9794 
9795 /// parseDirectiveFnStart
9796 ///  ::= .fnstart
parseDirectiveFnStart(SMLoc L)9797 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
9798   if (parseToken(AsmToken::EndOfStatement,
9799                  "unexpected token in '.fnstart' directive"))
9800     return true;
9801 
9802   if (UC.hasFnStart()) {
9803     Error(L, ".fnstart starts before the end of previous one");
9804     UC.emitFnStartLocNotes();
9805     return true;
9806   }
9807 
9808   // Reset the unwind directives parser state
9809   UC.reset();
9810 
9811   getTargetStreamer().emitFnStart();
9812 
9813   UC.recordFnStart(L);
9814   return false;
9815 }
9816 
9817 /// parseDirectiveFnEnd
9818 ///  ::= .fnend
parseDirectiveFnEnd(SMLoc L)9819 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
9820   if (parseToken(AsmToken::EndOfStatement,
9821                  "unexpected token in '.fnend' directive"))
9822     return true;
9823   // Check the ordering of unwind directives
9824   if (!UC.hasFnStart())
9825     return Error(L, ".fnstart must precede .fnend directive");
9826 
9827   // Reset the unwind directives parser state
9828   getTargetStreamer().emitFnEnd();
9829 
9830   UC.reset();
9831   return false;
9832 }
9833 
9834 /// parseDirectiveCantUnwind
9835 ///  ::= .cantunwind
parseDirectiveCantUnwind(SMLoc L)9836 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
9837   if (parseToken(AsmToken::EndOfStatement,
9838                  "unexpected token in '.cantunwind' directive"))
9839     return true;
9840 
9841   UC.recordCantUnwind(L);
9842   // Check the ordering of unwind directives
9843   if (check(!UC.hasFnStart(), L, ".fnstart must precede .cantunwind directive"))
9844     return true;
9845 
9846   if (UC.hasHandlerData()) {
9847     Error(L, ".cantunwind can't be used with .handlerdata directive");
9848     UC.emitHandlerDataLocNotes();
9849     return true;
9850   }
9851   if (UC.hasPersonality()) {
9852     Error(L, ".cantunwind can't be used with .personality directive");
9853     UC.emitPersonalityLocNotes();
9854     return true;
9855   }
9856 
9857   getTargetStreamer().emitCantUnwind();
9858   return false;
9859 }
9860 
9861 /// parseDirectivePersonality
9862 ///  ::= .personality name
parseDirectivePersonality(SMLoc L)9863 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
9864   MCAsmParser &Parser = getParser();
9865   bool HasExistingPersonality = UC.hasPersonality();
9866 
9867   // Parse the name of the personality routine
9868   if (Parser.getTok().isNot(AsmToken::Identifier))
9869     return Error(L, "unexpected input in .personality directive.");
9870   StringRef Name(Parser.getTok().getIdentifier());
9871   Parser.Lex();
9872 
9873   if (parseToken(AsmToken::EndOfStatement,
9874                  "unexpected token in '.personality' directive"))
9875     return true;
9876 
9877   UC.recordPersonality(L);
9878 
9879   // Check the ordering of unwind directives
9880   if (!UC.hasFnStart())
9881     return Error(L, ".fnstart must precede .personality directive");
9882   if (UC.cantUnwind()) {
9883     Error(L, ".personality can't be used with .cantunwind directive");
9884     UC.emitCantUnwindLocNotes();
9885     return true;
9886   }
9887   if (UC.hasHandlerData()) {
9888     Error(L, ".personality must precede .handlerdata directive");
9889     UC.emitHandlerDataLocNotes();
9890     return true;
9891   }
9892   if (HasExistingPersonality) {
9893     Error(L, "multiple personality directives");
9894     UC.emitPersonalityLocNotes();
9895     return true;
9896   }
9897 
9898   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
9899   getTargetStreamer().emitPersonality(PR);
9900   return false;
9901 }
9902 
9903 /// parseDirectiveHandlerData
9904 ///  ::= .handlerdata
parseDirectiveHandlerData(SMLoc L)9905 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
9906   if (parseToken(AsmToken::EndOfStatement,
9907                  "unexpected token in '.handlerdata' directive"))
9908     return true;
9909 
9910   UC.recordHandlerData(L);
9911   // Check the ordering of unwind directives
9912   if (!UC.hasFnStart())
9913     return Error(L, ".fnstart must precede .personality directive");
9914   if (UC.cantUnwind()) {
9915     Error(L, ".handlerdata can't be used with .cantunwind directive");
9916     UC.emitCantUnwindLocNotes();
9917     return true;
9918   }
9919 
9920   getTargetStreamer().emitHandlerData();
9921   return false;
9922 }
9923 
9924 /// parseDirectiveSetFP
9925 ///  ::= .setfp fpreg, spreg [, offset]
parseDirectiveSetFP(SMLoc L)9926 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
9927   MCAsmParser &Parser = getParser();
9928   // Check the ordering of unwind directives
9929   if (check(!UC.hasFnStart(), L, ".fnstart must precede .setfp directive") ||
9930       check(UC.hasHandlerData(), L,
9931             ".setfp must precede .handlerdata directive"))
9932     return true;
9933 
9934   // Parse fpreg
9935   SMLoc FPRegLoc = Parser.getTok().getLoc();
9936   int FPReg = tryParseRegister();
9937 
9938   if (check(FPReg == -1, FPRegLoc, "frame pointer register expected") ||
9939       Parser.parseToken(AsmToken::Comma, "comma expected"))
9940     return true;
9941 
9942   // Parse spreg
9943   SMLoc SPRegLoc = Parser.getTok().getLoc();
9944   int SPReg = tryParseRegister();
9945   if (check(SPReg == -1, SPRegLoc, "stack pointer register expected") ||
9946       check(SPReg != ARM::SP && SPReg != UC.getFPReg(), SPRegLoc,
9947             "register should be either $sp or the latest fp register"))
9948     return true;
9949 
9950   // Update the frame pointer register
9951   UC.saveFPReg(FPReg);
9952 
9953   // Parse offset
9954   int64_t Offset = 0;
9955   if (Parser.parseOptionalToken(AsmToken::Comma)) {
9956     if (Parser.getTok().isNot(AsmToken::Hash) &&
9957         Parser.getTok().isNot(AsmToken::Dollar))
9958       return Error(Parser.getTok().getLoc(), "'#' expected");
9959     Parser.Lex(); // skip hash token.
9960 
9961     const MCExpr *OffsetExpr;
9962     SMLoc ExLoc = Parser.getTok().getLoc();
9963     SMLoc EndLoc;
9964     if (getParser().parseExpression(OffsetExpr, EndLoc))
9965       return Error(ExLoc, "malformed setfp offset");
9966     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9967     if (check(!CE, ExLoc, "setfp offset must be an immediate"))
9968       return true;
9969     Offset = CE->getValue();
9970   }
9971 
9972   if (Parser.parseToken(AsmToken::EndOfStatement))
9973     return true;
9974 
9975   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
9976                                 static_cast<unsigned>(SPReg), Offset);
9977   return false;
9978 }
9979 
9980 /// parseDirective
9981 ///  ::= .pad offset
parseDirectivePad(SMLoc L)9982 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
9983   MCAsmParser &Parser = getParser();
9984   // Check the ordering of unwind directives
9985   if (!UC.hasFnStart())
9986     return Error(L, ".fnstart must precede .pad directive");
9987   if (UC.hasHandlerData())
9988     return Error(L, ".pad must precede .handlerdata directive");
9989 
9990   // Parse the offset
9991   if (Parser.getTok().isNot(AsmToken::Hash) &&
9992       Parser.getTok().isNot(AsmToken::Dollar))
9993     return Error(Parser.getTok().getLoc(), "'#' expected");
9994   Parser.Lex(); // skip hash token.
9995 
9996   const MCExpr *OffsetExpr;
9997   SMLoc ExLoc = Parser.getTok().getLoc();
9998   SMLoc EndLoc;
9999   if (getParser().parseExpression(OffsetExpr, EndLoc))
10000     return Error(ExLoc, "malformed pad offset");
10001   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10002   if (!CE)
10003     return Error(ExLoc, "pad offset must be an immediate");
10004 
10005   if (parseToken(AsmToken::EndOfStatement,
10006                  "unexpected token in '.pad' directive"))
10007     return true;
10008 
10009   getTargetStreamer().emitPad(CE->getValue());
10010   return false;
10011 }
10012 
10013 /// parseDirectiveRegSave
10014 ///  ::= .save  { registers }
10015 ///  ::= .vsave { registers }
parseDirectiveRegSave(SMLoc L,bool IsVector)10016 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
10017   // Check the ordering of unwind directives
10018   if (!UC.hasFnStart())
10019     return Error(L, ".fnstart must precede .save or .vsave directives");
10020   if (UC.hasHandlerData())
10021     return Error(L, ".save or .vsave must precede .handlerdata directive");
10022 
10023   // RAII object to make sure parsed operands are deleted.
10024   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
10025 
10026   // Parse the register list
10027   if (parseRegisterList(Operands) ||
10028       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
10029     return true;
10030   ARMOperand &Op = (ARMOperand &)*Operands[0];
10031   if (!IsVector && !Op.isRegList())
10032     return Error(L, ".save expects GPR registers");
10033   if (IsVector && !Op.isDPRRegList())
10034     return Error(L, ".vsave expects DPR registers");
10035 
10036   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
10037   return false;
10038 }
10039 
10040 /// parseDirectiveInst
10041 ///  ::= .inst opcode [, ...]
10042 ///  ::= .inst.n opcode [, ...]
10043 ///  ::= .inst.w opcode [, ...]
parseDirectiveInst(SMLoc Loc,char Suffix)10044 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
10045   int Width = 4;
10046 
10047   if (isThumb()) {
10048     switch (Suffix) {
10049     case 'n':
10050       Width = 2;
10051       break;
10052     case 'w':
10053       break;
10054     default:
10055       Width = 0;
10056       break;
10057     }
10058   } else {
10059     if (Suffix)
10060       return Error(Loc, "width suffixes are invalid in ARM mode");
10061   }
10062 
10063   auto parseOne = [&]() -> bool {
10064     const MCExpr *Expr;
10065     if (getParser().parseExpression(Expr))
10066       return true;
10067     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
10068     if (!Value) {
10069       return Error(Loc, "expected constant expression");
10070     }
10071 
10072     char CurSuffix = Suffix;
10073     switch (Width) {
10074     case 2:
10075       if (Value->getValue() > 0xffff)
10076         return Error(Loc, "inst.n operand is too big, use inst.w instead");
10077       break;
10078     case 4:
10079       if (Value->getValue() > 0xffffffff)
10080         return Error(Loc, StringRef(Suffix ? "inst.w" : "inst") +
10081                               " operand is too big");
10082       break;
10083     case 0:
10084       // Thumb mode, no width indicated. Guess from the opcode, if possible.
10085       if (Value->getValue() < 0xe800)
10086         CurSuffix = 'n';
10087       else if (Value->getValue() >= 0xe8000000)
10088         CurSuffix = 'w';
10089       else
10090         return Error(Loc, "cannot determine Thumb instruction size, "
10091                           "use inst.n/inst.w instead");
10092       break;
10093     default:
10094       llvm_unreachable("only supported widths are 2 and 4");
10095     }
10096 
10097     getTargetStreamer().emitInst(Value->getValue(), CurSuffix);
10098     return false;
10099   };
10100 
10101   if (parseOptionalToken(AsmToken::EndOfStatement))
10102     return Error(Loc, "expected expression following directive");
10103   if (parseMany(parseOne))
10104     return true;
10105   return false;
10106 }
10107 
10108 /// parseDirectiveLtorg
10109 ///  ::= .ltorg | .pool
parseDirectiveLtorg(SMLoc L)10110 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
10111   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
10112     return true;
10113   getTargetStreamer().emitCurrentConstantPool();
10114   return false;
10115 }
10116 
parseDirectiveEven(SMLoc L)10117 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
10118   const MCSection *Section = getStreamer().getCurrentSectionOnly();
10119 
10120   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
10121     return true;
10122 
10123   if (!Section) {
10124     getStreamer().InitSections(false);
10125     Section = getStreamer().getCurrentSectionOnly();
10126   }
10127 
10128   assert(Section && "must have section to emit alignment");
10129   if (Section->UseCodeAlign())
10130     getStreamer().EmitCodeAlignment(2);
10131   else
10132     getStreamer().EmitValueToAlignment(2);
10133 
10134   return false;
10135 }
10136 
10137 /// parseDirectivePersonalityIndex
10138 ///   ::= .personalityindex index
parseDirectivePersonalityIndex(SMLoc L)10139 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
10140   MCAsmParser &Parser = getParser();
10141   bool HasExistingPersonality = UC.hasPersonality();
10142 
10143   const MCExpr *IndexExpression;
10144   SMLoc IndexLoc = Parser.getTok().getLoc();
10145   if (Parser.parseExpression(IndexExpression) ||
10146       parseToken(AsmToken::EndOfStatement,
10147                  "unexpected token in '.personalityindex' directive")) {
10148     return true;
10149   }
10150 
10151   UC.recordPersonalityIndex(L);
10152 
10153   if (!UC.hasFnStart()) {
10154     return Error(L, ".fnstart must precede .personalityindex directive");
10155   }
10156   if (UC.cantUnwind()) {
10157     Error(L, ".personalityindex cannot be used with .cantunwind");
10158     UC.emitCantUnwindLocNotes();
10159     return true;
10160   }
10161   if (UC.hasHandlerData()) {
10162     Error(L, ".personalityindex must precede .handlerdata directive");
10163     UC.emitHandlerDataLocNotes();
10164     return true;
10165   }
10166   if (HasExistingPersonality) {
10167     Error(L, "multiple personality directives");
10168     UC.emitPersonalityLocNotes();
10169     return true;
10170   }
10171 
10172   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
10173   if (!CE)
10174     return Error(IndexLoc, "index must be a constant number");
10175   if (CE->getValue() < 0 || CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX)
10176     return Error(IndexLoc,
10177                  "personality routine index should be in range [0-3]");
10178 
10179   getTargetStreamer().emitPersonalityIndex(CE->getValue());
10180   return false;
10181 }
10182 
10183 /// parseDirectiveUnwindRaw
10184 ///   ::= .unwind_raw offset, opcode [, opcode...]
parseDirectiveUnwindRaw(SMLoc L)10185 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
10186   MCAsmParser &Parser = getParser();
10187   int64_t StackOffset;
10188   const MCExpr *OffsetExpr;
10189   SMLoc OffsetLoc = getLexer().getLoc();
10190 
10191   if (!UC.hasFnStart())
10192     return Error(L, ".fnstart must precede .unwind_raw directives");
10193   if (getParser().parseExpression(OffsetExpr))
10194     return Error(OffsetLoc, "expected expression");
10195 
10196   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10197   if (!CE)
10198     return Error(OffsetLoc, "offset must be a constant");
10199 
10200   StackOffset = CE->getValue();
10201 
10202   if (Parser.parseToken(AsmToken::Comma, "expected comma"))
10203     return true;
10204 
10205   SmallVector<uint8_t, 16> Opcodes;
10206 
10207   auto parseOne = [&]() -> bool {
10208     const MCExpr *OE;
10209     SMLoc OpcodeLoc = getLexer().getLoc();
10210     if (check(getLexer().is(AsmToken::EndOfStatement) ||
10211                   Parser.parseExpression(OE),
10212               OpcodeLoc, "expected opcode expression"))
10213       return true;
10214     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
10215     if (!OC)
10216       return Error(OpcodeLoc, "opcode value must be a constant");
10217     const int64_t Opcode = OC->getValue();
10218     if (Opcode & ~0xff)
10219       return Error(OpcodeLoc, "invalid opcode");
10220     Opcodes.push_back(uint8_t(Opcode));
10221     return false;
10222   };
10223 
10224   // Must have at least 1 element
10225   SMLoc OpcodeLoc = getLexer().getLoc();
10226   if (parseOptionalToken(AsmToken::EndOfStatement))
10227     return Error(OpcodeLoc, "expected opcode expression");
10228   if (parseMany(parseOne))
10229     return true;
10230 
10231   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
10232   return false;
10233 }
10234 
10235 /// parseDirectiveTLSDescSeq
10236 ///   ::= .tlsdescseq tls-variable
parseDirectiveTLSDescSeq(SMLoc L)10237 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
10238   MCAsmParser &Parser = getParser();
10239 
10240   if (getLexer().isNot(AsmToken::Identifier))
10241     return TokError("expected variable after '.tlsdescseq' directive");
10242 
10243   const MCSymbolRefExpr *SRE =
10244     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
10245                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
10246   Lex();
10247 
10248   if (parseToken(AsmToken::EndOfStatement,
10249                  "unexpected token in '.tlsdescseq' directive"))
10250     return true;
10251 
10252   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
10253   return false;
10254 }
10255 
10256 /// parseDirectiveMovSP
10257 ///  ::= .movsp reg [, #offset]
parseDirectiveMovSP(SMLoc L)10258 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
10259   MCAsmParser &Parser = getParser();
10260   if (!UC.hasFnStart())
10261     return Error(L, ".fnstart must precede .movsp directives");
10262   if (UC.getFPReg() != ARM::SP)
10263     return Error(L, "unexpected .movsp directive");
10264 
10265   SMLoc SPRegLoc = Parser.getTok().getLoc();
10266   int SPReg = tryParseRegister();
10267   if (SPReg == -1)
10268     return Error(SPRegLoc, "register expected");
10269   if (SPReg == ARM::SP || SPReg == ARM::PC)
10270     return Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
10271 
10272   int64_t Offset = 0;
10273   if (Parser.parseOptionalToken(AsmToken::Comma)) {
10274     if (Parser.parseToken(AsmToken::Hash, "expected #constant"))
10275       return true;
10276 
10277     const MCExpr *OffsetExpr;
10278     SMLoc OffsetLoc = Parser.getTok().getLoc();
10279 
10280     if (Parser.parseExpression(OffsetExpr))
10281       return Error(OffsetLoc, "malformed offset expression");
10282 
10283     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10284     if (!CE)
10285       return Error(OffsetLoc, "offset must be an immediate constant");
10286 
10287     Offset = CE->getValue();
10288   }
10289 
10290   if (parseToken(AsmToken::EndOfStatement,
10291                  "unexpected token in '.movsp' directive"))
10292     return true;
10293 
10294   getTargetStreamer().emitMovSP(SPReg, Offset);
10295   UC.saveFPReg(SPReg);
10296 
10297   return false;
10298 }
10299 
10300 /// parseDirectiveObjectArch
10301 ///   ::= .object_arch name
parseDirectiveObjectArch(SMLoc L)10302 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
10303   MCAsmParser &Parser = getParser();
10304   if (getLexer().isNot(AsmToken::Identifier))
10305     return Error(getLexer().getLoc(), "unexpected token");
10306 
10307   StringRef Arch = Parser.getTok().getString();
10308   SMLoc ArchLoc = Parser.getTok().getLoc();
10309   Lex();
10310 
10311   ARM::ArchKind ID = ARM::parseArch(Arch);
10312 
10313   if (ID == ARM::ArchKind::INVALID)
10314     return Error(ArchLoc, "unknown architecture '" + Arch + "'");
10315   if (parseToken(AsmToken::EndOfStatement))
10316     return true;
10317 
10318   getTargetStreamer().emitObjectArch(ID);
10319   return false;
10320 }
10321 
10322 /// parseDirectiveAlign
10323 ///   ::= .align
parseDirectiveAlign(SMLoc L)10324 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
10325   // NOTE: if this is not the end of the statement, fall back to the target
10326   // agnostic handling for this directive which will correctly handle this.
10327   if (parseOptionalToken(AsmToken::EndOfStatement)) {
10328     // '.align' is target specifically handled to mean 2**2 byte alignment.
10329     const MCSection *Section = getStreamer().getCurrentSectionOnly();
10330     assert(Section && "must have section to emit alignment");
10331     if (Section->UseCodeAlign())
10332       getStreamer().EmitCodeAlignment(4, 0);
10333     else
10334       getStreamer().EmitValueToAlignment(4, 0, 1, 0);
10335     return false;
10336   }
10337   return true;
10338 }
10339 
10340 /// parseDirectiveThumbSet
10341 ///  ::= .thumb_set name, value
parseDirectiveThumbSet(SMLoc L)10342 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
10343   MCAsmParser &Parser = getParser();
10344 
10345   StringRef Name;
10346   if (check(Parser.parseIdentifier(Name),
10347             "expected identifier after '.thumb_set'") ||
10348       parseToken(AsmToken::Comma, "expected comma after name '" + Name + "'"))
10349     return true;
10350 
10351   MCSymbol *Sym;
10352   const MCExpr *Value;
10353   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
10354                                                Parser, Sym, Value))
10355     return true;
10356 
10357   getTargetStreamer().emitThumbSet(Sym, Value);
10358   return false;
10359 }
10360 
10361 /// Force static initialization.
LLVMInitializeARMAsmParser()10362 extern "C" void LLVMInitializeARMAsmParser() {
10363   RegisterMCAsmParser<ARMAsmParser> X(getTheARMLETarget());
10364   RegisterMCAsmParser<ARMAsmParser> Y(getTheARMBETarget());
10365   RegisterMCAsmParser<ARMAsmParser> A(getTheThumbLETarget());
10366   RegisterMCAsmParser<ARMAsmParser> B(getTheThumbBETarget());
10367 }
10368 
10369 #define GET_REGISTER_MATCHER
10370 #define GET_SUBTARGET_FEATURE_NAME
10371 #define GET_MATCHER_IMPLEMENTATION
10372 #define GET_MNEMONIC_SPELL_CHECKER
10373 #include "ARMGenAsmMatcher.inc"
10374 
10375 // Some diagnostics need to vary with subtarget features, so they are handled
10376 // here. For example, the DPR class has either 16 or 32 registers, depending
10377 // on the FPU available.
10378 const char *
getCustomOperandDiag(ARMMatchResultTy MatchError)10379 ARMAsmParser::getCustomOperandDiag(ARMMatchResultTy MatchError) {
10380   switch (MatchError) {
10381   // rGPR contains sp starting with ARMv8.
10382   case Match_rGPR:
10383     return hasV8Ops() ? "operand must be a register in range [r0, r14]"
10384                       : "operand must be a register in range [r0, r12] or r14";
10385   // DPR contains 16 registers for some FPUs, and 32 for others.
10386   case Match_DPR:
10387     return hasD16() ? "operand must be a register in range [d0, d15]"
10388                     : "operand must be a register in range [d0, d31]";
10389   case Match_DPR_RegList:
10390     return hasD16() ? "operand must be a list of registers in range [d0, d15]"
10391                     : "operand must be a list of registers in range [d0, d31]";
10392 
10393   // For all other diags, use the static string from tablegen.
10394   default:
10395     return getMatchKindDiag(MatchError);
10396   }
10397 }
10398 
10399 // Process the list of near-misses, throwing away ones we don't want to report
10400 // to the user, and converting the rest to a source location and string that
10401 // should be reported.
10402 void
FilterNearMisses(SmallVectorImpl<NearMissInfo> & NearMissesIn,SmallVectorImpl<NearMissMessage> & NearMissesOut,SMLoc IDLoc,OperandVector & Operands)10403 ARMAsmParser::FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
10404                                SmallVectorImpl<NearMissMessage> &NearMissesOut,
10405                                SMLoc IDLoc, OperandVector &Operands) {
10406   // TODO: If operand didn't match, sub in a dummy one and run target
10407   // predicate, so that we can avoid reporting near-misses that are invalid?
10408   // TODO: Many operand types dont have SuperClasses set, so we report
10409   // redundant ones.
10410   // TODO: Some operands are superclasses of registers (e.g.
10411   // MCK_RegShiftedImm), we don't have any way to represent that currently.
10412   // TODO: This is not all ARM-specific, can some of it be factored out?
10413 
10414   // Record some information about near-misses that we have already seen, so
10415   // that we can avoid reporting redundant ones. For example, if there are
10416   // variants of an instruction that take 8- and 16-bit immediates, we want
10417   // to only report the widest one.
10418   std::multimap<unsigned, unsigned> OperandMissesSeen;
10419   SmallSet<uint64_t, 4> FeatureMissesSeen;
10420   bool ReportedTooFewOperands = false;
10421 
10422   // Process the near-misses in reverse order, so that we see more general ones
10423   // first, and so can avoid emitting more specific ones.
10424   for (NearMissInfo &I : reverse(NearMissesIn)) {
10425     switch (I.getKind()) {
10426     case NearMissInfo::NearMissOperand: {
10427       SMLoc OperandLoc =
10428           ((ARMOperand &)*Operands[I.getOperandIndex()]).getStartLoc();
10429       const char *OperandDiag =
10430           getCustomOperandDiag((ARMMatchResultTy)I.getOperandError());
10431 
10432       // If we have already emitted a message for a superclass, don't also report
10433       // the sub-class. We consider all operand classes that we don't have a
10434       // specialised diagnostic for to be equal for the propose of this check,
10435       // so that we don't report the generic error multiple times on the same
10436       // operand.
10437       unsigned DupCheckMatchClass = OperandDiag ? I.getOperandClass() : ~0U;
10438       auto PrevReports = OperandMissesSeen.equal_range(I.getOperandIndex());
10439       if (std::any_of(PrevReports.first, PrevReports.second,
10440                       [DupCheckMatchClass](
10441                           const std::pair<unsigned, unsigned> Pair) {
10442             if (DupCheckMatchClass == ~0U || Pair.second == ~0U)
10443               return Pair.second == DupCheckMatchClass;
10444             else
10445               return isSubclass((MatchClassKind)DupCheckMatchClass,
10446                                 (MatchClassKind)Pair.second);
10447           }))
10448         break;
10449       OperandMissesSeen.insert(
10450           std::make_pair(I.getOperandIndex(), DupCheckMatchClass));
10451 
10452       NearMissMessage Message;
10453       Message.Loc = OperandLoc;
10454       if (OperandDiag) {
10455         Message.Message = OperandDiag;
10456       } else if (I.getOperandClass() == InvalidMatchClass) {
10457         Message.Message = "too many operands for instruction";
10458       } else {
10459         Message.Message = "invalid operand for instruction";
10460         LLVM_DEBUG(
10461             dbgs() << "Missing diagnostic string for operand class "
10462                    << getMatchClassName((MatchClassKind)I.getOperandClass())
10463                    << I.getOperandClass() << ", error " << I.getOperandError()
10464                    << ", opcode " << MII.getName(I.getOpcode()) << "\n");
10465       }
10466       NearMissesOut.emplace_back(Message);
10467       break;
10468     }
10469     case NearMissInfo::NearMissFeature: {
10470       uint64_t MissingFeatures = I.getFeatures();
10471       // Don't report the same set of features twice.
10472       if (FeatureMissesSeen.count(MissingFeatures))
10473         break;
10474       FeatureMissesSeen.insert(MissingFeatures);
10475 
10476       // Special case: don't report a feature set which includes arm-mode for
10477       // targets that don't have ARM mode.
10478       if ((MissingFeatures & Feature_IsARM) && !hasARM())
10479         break;
10480       // Don't report any near-misses that both require switching instruction
10481       // set, and adding other subtarget features.
10482       if (isThumb() && (MissingFeatures & Feature_IsARM) &&
10483           (MissingFeatures & ~Feature_IsARM))
10484         break;
10485       if (!isThumb() && (MissingFeatures & Feature_IsThumb) &&
10486           (MissingFeatures & ~Feature_IsThumb))
10487         break;
10488       if (!isThumb() && (MissingFeatures & Feature_IsThumb2) &&
10489           (MissingFeatures & ~(Feature_IsThumb2 | Feature_IsThumb)))
10490         break;
10491       if (isMClass() && (MissingFeatures & Feature_HasNEON))
10492         break;
10493 
10494       NearMissMessage Message;
10495       Message.Loc = IDLoc;
10496       raw_svector_ostream OS(Message.Message);
10497 
10498       OS << "instruction requires:";
10499       uint64_t Mask = 1;
10500       for (unsigned MaskPos = 0; MaskPos < (sizeof(MissingFeatures) * 8 - 1);
10501            ++MaskPos) {
10502         if (MissingFeatures & Mask) {
10503           OS << " " << getSubtargetFeatureName(MissingFeatures & Mask);
10504         }
10505         Mask <<= 1;
10506       }
10507       NearMissesOut.emplace_back(Message);
10508 
10509       break;
10510     }
10511     case NearMissInfo::NearMissPredicate: {
10512       NearMissMessage Message;
10513       Message.Loc = IDLoc;
10514       switch (I.getPredicateError()) {
10515       case Match_RequiresNotITBlock:
10516         Message.Message = "flag setting instruction only valid outside IT block";
10517         break;
10518       case Match_RequiresITBlock:
10519         Message.Message = "instruction only valid inside IT block";
10520         break;
10521       case Match_RequiresV6:
10522         Message.Message = "instruction variant requires ARMv6 or later";
10523         break;
10524       case Match_RequiresThumb2:
10525         Message.Message = "instruction variant requires Thumb2";
10526         break;
10527       case Match_RequiresV8:
10528         Message.Message = "instruction variant requires ARMv8 or later";
10529         break;
10530       case Match_RequiresFlagSetting:
10531         Message.Message = "no flag-preserving variant of this instruction available";
10532         break;
10533       case Match_InvalidOperand:
10534         Message.Message = "invalid operand for instruction";
10535         break;
10536       default:
10537         llvm_unreachable("Unhandled target predicate error");
10538         break;
10539       }
10540       NearMissesOut.emplace_back(Message);
10541       break;
10542     }
10543     case NearMissInfo::NearMissTooFewOperands: {
10544       if (!ReportedTooFewOperands) {
10545         SMLoc EndLoc = ((ARMOperand &)*Operands.back()).getEndLoc();
10546         NearMissesOut.emplace_back(NearMissMessage{
10547             EndLoc, StringRef("too few operands for instruction")});
10548         ReportedTooFewOperands = true;
10549       }
10550       break;
10551     }
10552     case NearMissInfo::NoNearMiss:
10553       // This should never leave the matcher.
10554       llvm_unreachable("not a near-miss");
10555       break;
10556     }
10557   }
10558 }
10559 
ReportNearMisses(SmallVectorImpl<NearMissInfo> & NearMisses,SMLoc IDLoc,OperandVector & Operands)10560 void ARMAsmParser::ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses,
10561                                     SMLoc IDLoc, OperandVector &Operands) {
10562   SmallVector<NearMissMessage, 4> Messages;
10563   FilterNearMisses(NearMisses, Messages, IDLoc, Operands);
10564 
10565   if (Messages.size() == 0) {
10566     // No near-misses were found, so the best we can do is "invalid
10567     // instruction".
10568     Error(IDLoc, "invalid instruction");
10569   } else if (Messages.size() == 1) {
10570     // One near miss was found, report it as the sole error.
10571     Error(Messages[0].Loc, Messages[0].Message);
10572   } else {
10573     // More than one near miss, so report a generic "invalid instruction"
10574     // error, followed by notes for each of the near-misses.
10575     Error(IDLoc, "invalid instruction, any one of the following would fix this:");
10576     for (auto &M : Messages) {
10577       Note(M.Loc, M.Message);
10578     }
10579   }
10580 }
10581 
10582 // FIXME: This structure should be moved inside ARMTargetParser
10583 // when we start to table-generate them, and we can use the ARM
10584 // flags below, that were generated by table-gen.
10585 static const struct {
10586   const unsigned Kind;
10587   const uint64_t ArchCheck;
10588   const FeatureBitset Features;
10589 } Extensions[] = {
10590   { ARM::AEK_CRC, Feature_HasV8, {ARM::FeatureCRC} },
10591   { ARM::AEK_CRYPTO,  Feature_HasV8,
10592     {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10593   { ARM::AEK_FP, Feature_HasV8, {ARM::FeatureFPARMv8} },
10594   { (ARM::AEK_HWDIVTHUMB | ARM::AEK_HWDIVARM), Feature_HasV7 | Feature_IsNotMClass,
10595     {ARM::FeatureHWDivThumb, ARM::FeatureHWDivARM} },
10596   { ARM::AEK_MP, Feature_HasV7 | Feature_IsNotMClass, {ARM::FeatureMP} },
10597   { ARM::AEK_SIMD, Feature_HasV8, {ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10598   { ARM::AEK_SEC, Feature_HasV6K, {ARM::FeatureTrustZone} },
10599   // FIXME: Only available in A-class, isel not predicated
10600   { ARM::AEK_VIRT, Feature_HasV7, {ARM::FeatureVirtualization} },
10601   { ARM::AEK_FP16, Feature_HasV8_2a, {ARM::FeatureFPARMv8, ARM::FeatureFullFP16} },
10602   { ARM::AEK_RAS, Feature_HasV8, {ARM::FeatureRAS} },
10603   // FIXME: Unsupported extensions.
10604   { ARM::AEK_OS, Feature_None, {} },
10605   { ARM::AEK_IWMMXT, Feature_None, {} },
10606   { ARM::AEK_IWMMXT2, Feature_None, {} },
10607   { ARM::AEK_MAVERICK, Feature_None, {} },
10608   { ARM::AEK_XSCALE, Feature_None, {} },
10609 };
10610 
10611 /// parseDirectiveArchExtension
10612 ///   ::= .arch_extension [no]feature
parseDirectiveArchExtension(SMLoc L)10613 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
10614   MCAsmParser &Parser = getParser();
10615 
10616   if (getLexer().isNot(AsmToken::Identifier))
10617     return Error(getLexer().getLoc(), "expected architecture extension name");
10618 
10619   StringRef Name = Parser.getTok().getString();
10620   SMLoc ExtLoc = Parser.getTok().getLoc();
10621   Lex();
10622 
10623   if (parseToken(AsmToken::EndOfStatement,
10624                  "unexpected token in '.arch_extension' directive"))
10625     return true;
10626 
10627   bool EnableFeature = true;
10628   if (Name.startswith_lower("no")) {
10629     EnableFeature = false;
10630     Name = Name.substr(2);
10631   }
10632   unsigned FeatureKind = ARM::parseArchExt(Name);
10633   if (FeatureKind == ARM::AEK_INVALID)
10634     return Error(ExtLoc, "unknown architectural extension: " + Name);
10635 
10636   for (const auto &Extension : Extensions) {
10637     if (Extension.Kind != FeatureKind)
10638       continue;
10639 
10640     if (Extension.Features.none())
10641       return Error(ExtLoc, "unsupported architectural extension: " + Name);
10642 
10643     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck)
10644       return Error(ExtLoc, "architectural extension '" + Name +
10645                                "' is not "
10646                                "allowed for the current base architecture");
10647 
10648     MCSubtargetInfo &STI = copySTI();
10649     FeatureBitset ToggleFeatures = EnableFeature
10650       ? (~STI.getFeatureBits() & Extension.Features)
10651       : ( STI.getFeatureBits() & Extension.Features);
10652 
10653     uint64_t Features =
10654         ComputeAvailableFeatures(STI.ToggleFeature(ToggleFeatures));
10655     setAvailableFeatures(Features);
10656     return false;
10657   }
10658 
10659   return Error(ExtLoc, "unknown architectural extension: " + Name);
10660 }
10661 
10662 // Define this matcher function after the auto-generated include so we
10663 // have the match class enum definitions.
validateTargetOperandClass(MCParsedAsmOperand & AsmOp,unsigned Kind)10664 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
10665                                                   unsigned Kind) {
10666   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
10667   // If the kind is a token for a literal immediate, check if our asm
10668   // operand matches. This is for InstAliases which have a fixed-value
10669   // immediate in the syntax.
10670   switch (Kind) {
10671   default: break;
10672   case MCK__35_0:
10673     if (Op.isImm())
10674       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
10675         if (CE->getValue() == 0)
10676           return Match_Success;
10677     break;
10678   case MCK_ModImm:
10679     if (Op.isImm()) {
10680       const MCExpr *SOExpr = Op.getImm();
10681       int64_t Value;
10682       if (!SOExpr->evaluateAsAbsolute(Value))
10683         return Match_Success;
10684       assert((Value >= std::numeric_limits<int32_t>::min() &&
10685               Value <= std::numeric_limits<uint32_t>::max()) &&
10686              "expression value must be representable in 32 bits");
10687     }
10688     break;
10689   case MCK_rGPR:
10690     if (hasV8Ops() && Op.isReg() && Op.getReg() == ARM::SP)
10691       return Match_Success;
10692     return Match_rGPR;
10693   case MCK_GPRPair:
10694     if (Op.isReg() &&
10695         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
10696       return Match_Success;
10697     break;
10698   }
10699   return Match_InvalidOperand;
10700 }
10701