xref: /netbsd-src/external/apache2/llvm/dist/llvm/lib/Target/ARM/AsmParser/ARMAsmParser.cpp (revision 82d56013d7b633d116a93943de88e08335357a7c)
1 //===- ARMAsmParser.cpp - Parse ARM assembly to MCInst instructions -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "ARMFeatures.h"
10 #include "ARMBaseInstrInfo.h"
11 #include "Utils/ARMBaseInfo.h"
12 #include "MCTargetDesc/ARMAddressingModes.h"
13 #include "MCTargetDesc/ARMBaseInfo.h"
14 #include "MCTargetDesc/ARMInstPrinter.h"
15 #include "MCTargetDesc/ARMMCExpr.h"
16 #include "MCTargetDesc/ARMMCTargetDesc.h"
17 #include "TargetInfo/ARMTargetInfo.h"
18 #include "llvm/ADT/APFloat.h"
19 #include "llvm/ADT/APInt.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/ADT/StringSet.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/MC/MCContext.h"
31 #include "llvm/MC/MCExpr.h"
32 #include "llvm/MC/MCInst.h"
33 #include "llvm/MC/MCInstrDesc.h"
34 #include "llvm/MC/MCInstrInfo.h"
35 #include "llvm/MC/MCParser/MCAsmLexer.h"
36 #include "llvm/MC/MCParser/MCAsmParser.h"
37 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
38 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
39 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
40 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
41 #include "llvm/MC/MCRegisterInfo.h"
42 #include "llvm/MC/MCSection.h"
43 #include "llvm/MC/MCStreamer.h"
44 #include "llvm/MC/MCSubtargetInfo.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/MC/SubtargetFeature.h"
47 #include "llvm/Support/ARMBuildAttributes.h"
48 #include "llvm/Support/ARMEHABI.h"
49 #include "llvm/Support/Casting.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/SMLoc.h"
55 #include "llvm/Support/TargetParser.h"
56 #include "llvm/Support/TargetRegistry.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include <algorithm>
59 #include <cassert>
60 #include <cstddef>
61 #include <cstdint>
62 #include <iterator>
63 #include <limits>
64 #include <memory>
65 #include <string>
66 #include <utility>
67 #include <vector>
68 
69 #define DEBUG_TYPE "asm-parser"
70 
71 using namespace llvm;
72 
73 namespace llvm {
74 extern const MCInstrDesc ARMInsts[];
75 } // end namespace llvm
76 
77 namespace {
78 
79 enum class ImplicitItModeTy { Always, Never, ARMOnly, ThumbOnly };
80 
81 static cl::opt<ImplicitItModeTy> ImplicitItMode(
82     "arm-implicit-it", cl::init(ImplicitItModeTy::ARMOnly),
83     cl::desc("Allow conditional instructions outdside of an IT block"),
84     cl::values(clEnumValN(ImplicitItModeTy::Always, "always",
85                           "Accept in both ISAs, emit implicit ITs in Thumb"),
86                clEnumValN(ImplicitItModeTy::Never, "never",
87                           "Warn in ARM, reject in Thumb"),
88                clEnumValN(ImplicitItModeTy::ARMOnly, "arm",
89                           "Accept in ARM, reject in Thumb"),
90                clEnumValN(ImplicitItModeTy::ThumbOnly, "thumb",
91                           "Warn in ARM, emit implicit ITs in Thumb")));
92 
93 static cl::opt<bool> AddBuildAttributes("arm-add-build-attributes",
94                                         cl::init(false));
95 
96 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
97 
extractITMaskBit(unsigned Mask,unsigned Position)98 static inline unsigned extractITMaskBit(unsigned Mask, unsigned Position) {
99   // Position==0 means we're not in an IT block at all. Position==1
100   // means we want the first state bit, which is always 0 (Then).
101   // Position==2 means we want the second state bit, stored at bit 3
102   // of Mask, and so on downwards. So (5 - Position) will shift the
103   // right bit down to bit 0, including the always-0 bit at bit 4 for
104   // the mandatory initial Then.
105   return (Mask >> (5 - Position) & 1);
106 }
107 
108 class UnwindContext {
109   using Locs = SmallVector<SMLoc, 4>;
110 
111   MCAsmParser &Parser;
112   Locs FnStartLocs;
113   Locs CantUnwindLocs;
114   Locs PersonalityLocs;
115   Locs PersonalityIndexLocs;
116   Locs HandlerDataLocs;
117   int FPReg;
118 
119 public:
UnwindContext(MCAsmParser & P)120   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
121 
hasFnStart() const122   bool hasFnStart() const { return !FnStartLocs.empty(); }
cantUnwind() const123   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
hasHandlerData() const124   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
125 
hasPersonality() const126   bool hasPersonality() const {
127     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
128   }
129 
recordFnStart(SMLoc L)130   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
recordCantUnwind(SMLoc L)131   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
recordPersonality(SMLoc L)132   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
recordHandlerData(SMLoc L)133   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
recordPersonalityIndex(SMLoc L)134   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
135 
saveFPReg(int Reg)136   void saveFPReg(int Reg) { FPReg = Reg; }
getFPReg() const137   int getFPReg() const { return FPReg; }
138 
emitFnStartLocNotes() const139   void emitFnStartLocNotes() const {
140     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
141          FI != FE; ++FI)
142       Parser.Note(*FI, ".fnstart was specified here");
143   }
144 
emitCantUnwindLocNotes() const145   void emitCantUnwindLocNotes() const {
146     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
147                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
148       Parser.Note(*UI, ".cantunwind was specified here");
149   }
150 
emitHandlerDataLocNotes() const151   void emitHandlerDataLocNotes() const {
152     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
153                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
154       Parser.Note(*HI, ".handlerdata was specified here");
155   }
156 
emitPersonalityLocNotes() const157   void emitPersonalityLocNotes() const {
158     for (Locs::const_iterator PI = PersonalityLocs.begin(),
159                               PE = PersonalityLocs.end(),
160                               PII = PersonalityIndexLocs.begin(),
161                               PIE = PersonalityIndexLocs.end();
162          PI != PE || PII != PIE;) {
163       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
164         Parser.Note(*PI++, ".personality was specified here");
165       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
166         Parser.Note(*PII++, ".personalityindex was specified here");
167       else
168         llvm_unreachable(".personality and .personalityindex cannot be "
169                          "at the same location");
170     }
171   }
172 
reset()173   void reset() {
174     FnStartLocs = Locs();
175     CantUnwindLocs = Locs();
176     PersonalityLocs = Locs();
177     HandlerDataLocs = Locs();
178     PersonalityIndexLocs = Locs();
179     FPReg = ARM::SP;
180   }
181 };
182 
183 // Various sets of ARM instruction mnemonics which are used by the asm parser
184 class ARMMnemonicSets {
185   StringSet<> CDE;
186   StringSet<> CDEWithVPTSuffix;
187 public:
188   ARMMnemonicSets(const MCSubtargetInfo &STI);
189 
190   /// Returns true iff a given mnemonic is a CDE instruction
isCDEInstr(StringRef Mnemonic)191   bool isCDEInstr(StringRef Mnemonic) {
192     // Quick check before searching the set
193     if (!Mnemonic.startswith("cx") && !Mnemonic.startswith("vcx"))
194       return false;
195     return CDE.count(Mnemonic);
196   }
197 
198   /// Returns true iff a given mnemonic is a VPT-predicable CDE instruction
199   /// (possibly with a predication suffix "e" or "t")
isVPTPredicableCDEInstr(StringRef Mnemonic)200   bool isVPTPredicableCDEInstr(StringRef Mnemonic) {
201     if (!Mnemonic.startswith("vcx"))
202       return false;
203     return CDEWithVPTSuffix.count(Mnemonic);
204   }
205 
206   /// Returns true iff a given mnemonic is an IT-predicable CDE instruction
207   /// (possibly with a condition suffix)
isITPredicableCDEInstr(StringRef Mnemonic)208   bool isITPredicableCDEInstr(StringRef Mnemonic) {
209     if (!Mnemonic.startswith("cx"))
210       return false;
211     return Mnemonic.startswith("cx1a") || Mnemonic.startswith("cx1da") ||
212            Mnemonic.startswith("cx2a") || Mnemonic.startswith("cx2da") ||
213            Mnemonic.startswith("cx3a") || Mnemonic.startswith("cx3da");
214   }
215 
216   /// Return true iff a given mnemonic is an integer CDE instruction with
217   /// dual-register destination
isCDEDualRegInstr(StringRef Mnemonic)218   bool isCDEDualRegInstr(StringRef Mnemonic) {
219     if (!Mnemonic.startswith("cx"))
220       return false;
221     return Mnemonic == "cx1d" || Mnemonic == "cx1da" ||
222            Mnemonic == "cx2d" || Mnemonic == "cx2da" ||
223            Mnemonic == "cx3d" || Mnemonic == "cx3da";
224   }
225 };
226 
ARMMnemonicSets(const MCSubtargetInfo & STI)227 ARMMnemonicSets::ARMMnemonicSets(const MCSubtargetInfo &STI) {
228   for (StringRef Mnemonic: { "cx1", "cx1a", "cx1d", "cx1da",
229                              "cx2", "cx2a", "cx2d", "cx2da",
230                              "cx3", "cx3a", "cx3d", "cx3da", })
231     CDE.insert(Mnemonic);
232   for (StringRef Mnemonic :
233        {"vcx1", "vcx1a", "vcx2", "vcx2a", "vcx3", "vcx3a"}) {
234     CDE.insert(Mnemonic);
235     CDEWithVPTSuffix.insert(Mnemonic);
236     CDEWithVPTSuffix.insert(std::string(Mnemonic) + "t");
237     CDEWithVPTSuffix.insert(std::string(Mnemonic) + "e");
238   }
239 }
240 
241 class ARMAsmParser : public MCTargetAsmParser {
242   const MCRegisterInfo *MRI;
243   UnwindContext UC;
244   ARMMnemonicSets MS;
245 
getTargetStreamer()246   ARMTargetStreamer &getTargetStreamer() {
247     assert(getParser().getStreamer().getTargetStreamer() &&
248            "do not have a target streamer");
249     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
250     return static_cast<ARMTargetStreamer &>(TS);
251   }
252 
253   // Map of register aliases registers via the .req directive.
254   StringMap<unsigned> RegisterReqs;
255 
256   bool NextSymbolIsThumb;
257 
useImplicitITThumb() const258   bool useImplicitITThumb() const {
259     return ImplicitItMode == ImplicitItModeTy::Always ||
260            ImplicitItMode == ImplicitItModeTy::ThumbOnly;
261   }
262 
useImplicitITARM() const263   bool useImplicitITARM() const {
264     return ImplicitItMode == ImplicitItModeTy::Always ||
265            ImplicitItMode == ImplicitItModeTy::ARMOnly;
266   }
267 
268   struct {
269     ARMCC::CondCodes Cond;    // Condition for IT block.
270     unsigned Mask:4;          // Condition mask for instructions.
271                               // Starting at first 1 (from lsb).
272                               //   '1'  condition as indicated in IT.
273                               //   '0'  inverse of condition (else).
274                               // Count of instructions in IT block is
275                               // 4 - trailingzeroes(mask)
276                               // Note that this does not have the same encoding
277                               // as in the IT instruction, which also depends
278                               // on the low bit of the condition code.
279 
280     unsigned CurPosition;     // Current position in parsing of IT
281                               // block. In range [0,4], with 0 being the IT
282                               // instruction itself. Initialized according to
283                               // count of instructions in block.  ~0U if no
284                               // active IT block.
285 
286     bool IsExplicit;          // true  - The IT instruction was present in the
287                               //         input, we should not modify it.
288                               // false - The IT instruction was added
289                               //         implicitly, we can extend it if that
290                               //         would be legal.
291   } ITState;
292 
293   SmallVector<MCInst, 4> PendingConditionalInsts;
294 
flushPendingInstructions(MCStreamer & Out)295   void flushPendingInstructions(MCStreamer &Out) override {
296     if (!inImplicitITBlock()) {
297       assert(PendingConditionalInsts.size() == 0);
298       return;
299     }
300 
301     // Emit the IT instruction
302     MCInst ITInst;
303     ITInst.setOpcode(ARM::t2IT);
304     ITInst.addOperand(MCOperand::createImm(ITState.Cond));
305     ITInst.addOperand(MCOperand::createImm(ITState.Mask));
306     Out.emitInstruction(ITInst, getSTI());
307 
308     // Emit the conditonal instructions
309     assert(PendingConditionalInsts.size() <= 4);
310     for (const MCInst &Inst : PendingConditionalInsts) {
311       Out.emitInstruction(Inst, getSTI());
312     }
313     PendingConditionalInsts.clear();
314 
315     // Clear the IT state
316     ITState.Mask = 0;
317     ITState.CurPosition = ~0U;
318   }
319 
inITBlock()320   bool inITBlock() { return ITState.CurPosition != ~0U; }
inExplicitITBlock()321   bool inExplicitITBlock() { return inITBlock() && ITState.IsExplicit; }
inImplicitITBlock()322   bool inImplicitITBlock() { return inITBlock() && !ITState.IsExplicit; }
323 
lastInITBlock()324   bool lastInITBlock() {
325     return ITState.CurPosition == 4 - countTrailingZeros(ITState.Mask);
326   }
327 
forwardITPosition()328   void forwardITPosition() {
329     if (!inITBlock()) return;
330     // Move to the next instruction in the IT block, if there is one. If not,
331     // mark the block as done, except for implicit IT blocks, which we leave
332     // open until we find an instruction that can't be added to it.
333     unsigned TZ = countTrailingZeros(ITState.Mask);
334     if (++ITState.CurPosition == 5 - TZ && ITState.IsExplicit)
335       ITState.CurPosition = ~0U; // Done with the IT block after this.
336   }
337 
338   // Rewind the state of the current IT block, removing the last slot from it.
rewindImplicitITPosition()339   void rewindImplicitITPosition() {
340     assert(inImplicitITBlock());
341     assert(ITState.CurPosition > 1);
342     ITState.CurPosition--;
343     unsigned TZ = countTrailingZeros(ITState.Mask);
344     unsigned NewMask = 0;
345     NewMask |= ITState.Mask & (0xC << TZ);
346     NewMask |= 0x2 << TZ;
347     ITState.Mask = NewMask;
348   }
349 
350   // Rewind the state of the current IT block, removing the last slot from it.
351   // If we were at the first slot, this closes the IT block.
discardImplicitITBlock()352   void discardImplicitITBlock() {
353     assert(inImplicitITBlock());
354     assert(ITState.CurPosition == 1);
355     ITState.CurPosition = ~0U;
356   }
357 
358   // Return the low-subreg of a given Q register.
getDRegFromQReg(unsigned QReg) const359   unsigned getDRegFromQReg(unsigned QReg) const {
360     return MRI->getSubReg(QReg, ARM::dsub_0);
361   }
362 
363   // Get the condition code corresponding to the current IT block slot.
currentITCond()364   ARMCC::CondCodes currentITCond() {
365     unsigned MaskBit = extractITMaskBit(ITState.Mask, ITState.CurPosition);
366     return MaskBit ? ARMCC::getOppositeCondition(ITState.Cond) : ITState.Cond;
367   }
368 
369   // Invert the condition of the current IT block slot without changing any
370   // other slots in the same block.
invertCurrentITCondition()371   void invertCurrentITCondition() {
372     if (ITState.CurPosition == 1) {
373       ITState.Cond = ARMCC::getOppositeCondition(ITState.Cond);
374     } else {
375       ITState.Mask ^= 1 << (5 - ITState.CurPosition);
376     }
377   }
378 
379   // Returns true if the current IT block is full (all 4 slots used).
isITBlockFull()380   bool isITBlockFull() {
381     return inITBlock() && (ITState.Mask & 1);
382   }
383 
384   // Extend the current implicit IT block to have one more slot with the given
385   // condition code.
extendImplicitITBlock(ARMCC::CondCodes Cond)386   void extendImplicitITBlock(ARMCC::CondCodes Cond) {
387     assert(inImplicitITBlock());
388     assert(!isITBlockFull());
389     assert(Cond == ITState.Cond ||
390            Cond == ARMCC::getOppositeCondition(ITState.Cond));
391     unsigned TZ = countTrailingZeros(ITState.Mask);
392     unsigned NewMask = 0;
393     // Keep any existing condition bits.
394     NewMask |= ITState.Mask & (0xE << TZ);
395     // Insert the new condition bit.
396     NewMask |= (Cond != ITState.Cond) << TZ;
397     // Move the trailing 1 down one bit.
398     NewMask |= 1 << (TZ - 1);
399     ITState.Mask = NewMask;
400   }
401 
402   // Create a new implicit IT block with a dummy condition code.
startImplicitITBlock()403   void startImplicitITBlock() {
404     assert(!inITBlock());
405     ITState.Cond = ARMCC::AL;
406     ITState.Mask = 8;
407     ITState.CurPosition = 1;
408     ITState.IsExplicit = false;
409   }
410 
411   // Create a new explicit IT block with the given condition and mask.
412   // The mask should be in the format used in ARMOperand and
413   // MCOperand, with a 1 implying 'e', regardless of the low bit of
414   // the condition.
startExplicitITBlock(ARMCC::CondCodes Cond,unsigned Mask)415   void startExplicitITBlock(ARMCC::CondCodes Cond, unsigned Mask) {
416     assert(!inITBlock());
417     ITState.Cond = Cond;
418     ITState.Mask = Mask;
419     ITState.CurPosition = 0;
420     ITState.IsExplicit = true;
421   }
422 
423   struct {
424     unsigned Mask : 4;
425     unsigned CurPosition;
426   } VPTState;
inVPTBlock()427   bool inVPTBlock() { return VPTState.CurPosition != ~0U; }
forwardVPTPosition()428   void forwardVPTPosition() {
429     if (!inVPTBlock()) return;
430     unsigned TZ = countTrailingZeros(VPTState.Mask);
431     if (++VPTState.CurPosition == 5 - TZ)
432       VPTState.CurPosition = ~0U;
433   }
434 
Note(SMLoc L,const Twine & Msg,SMRange Range=None)435   void Note(SMLoc L, const Twine &Msg, SMRange Range = None) {
436     return getParser().Note(L, Msg, Range);
437   }
438 
Warning(SMLoc L,const Twine & Msg,SMRange Range=None)439   bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) {
440     return getParser().Warning(L, Msg, Range);
441   }
442 
Error(SMLoc L,const Twine & Msg,SMRange Range=None)443   bool Error(SMLoc L, const Twine &Msg, SMRange Range = None) {
444     return getParser().Error(L, Msg, Range);
445   }
446 
447   bool validatetLDMRegList(const MCInst &Inst, const OperandVector &Operands,
448                            unsigned ListNo, bool IsARPop = false);
449   bool validatetSTMRegList(const MCInst &Inst, const OperandVector &Operands,
450                            unsigned ListNo);
451 
452   int tryParseRegister();
453   bool tryParseRegisterWithWriteBack(OperandVector &);
454   int tryParseShiftRegister(OperandVector &);
455   bool parseRegisterList(OperandVector &, bool EnforceOrder = true);
456   bool parseMemory(OperandVector &);
457   bool parseOperand(OperandVector &, StringRef Mnemonic);
458   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
459   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
460                               unsigned &ShiftAmount);
461   bool parseLiteralValues(unsigned Size, SMLoc L);
462   bool parseDirectiveThumb(SMLoc L);
463   bool parseDirectiveARM(SMLoc L);
464   bool parseDirectiveThumbFunc(SMLoc L);
465   bool parseDirectiveCode(SMLoc L);
466   bool parseDirectiveSyntax(SMLoc L);
467   bool parseDirectiveReq(StringRef Name, SMLoc L);
468   bool parseDirectiveUnreq(SMLoc L);
469   bool parseDirectiveArch(SMLoc L);
470   bool parseDirectiveEabiAttr(SMLoc L);
471   bool parseDirectiveCPU(SMLoc L);
472   bool parseDirectiveFPU(SMLoc L);
473   bool parseDirectiveFnStart(SMLoc L);
474   bool parseDirectiveFnEnd(SMLoc L);
475   bool parseDirectiveCantUnwind(SMLoc L);
476   bool parseDirectivePersonality(SMLoc L);
477   bool parseDirectiveHandlerData(SMLoc L);
478   bool parseDirectiveSetFP(SMLoc L);
479   bool parseDirectivePad(SMLoc L);
480   bool parseDirectiveRegSave(SMLoc L, bool IsVector);
481   bool parseDirectiveInst(SMLoc L, char Suffix = '\0');
482   bool parseDirectiveLtorg(SMLoc L);
483   bool parseDirectiveEven(SMLoc L);
484   bool parseDirectivePersonalityIndex(SMLoc L);
485   bool parseDirectiveUnwindRaw(SMLoc L);
486   bool parseDirectiveTLSDescSeq(SMLoc L);
487   bool parseDirectiveMovSP(SMLoc L);
488   bool parseDirectiveObjectArch(SMLoc L);
489   bool parseDirectiveArchExtension(SMLoc L);
490   bool parseDirectiveAlign(SMLoc L);
491   bool parseDirectiveThumbSet(SMLoc L);
492 
493   bool isMnemonicVPTPredicable(StringRef Mnemonic, StringRef ExtraToken);
494   StringRef splitMnemonic(StringRef Mnemonic, StringRef ExtraToken,
495                           unsigned &PredicationCode,
496                           unsigned &VPTPredicationCode, bool &CarrySetting,
497                           unsigned &ProcessorIMod, StringRef &ITMask);
498   void getMnemonicAcceptInfo(StringRef Mnemonic, StringRef ExtraToken,
499                              StringRef FullInst, bool &CanAcceptCarrySet,
500                              bool &CanAcceptPredicationCode,
501                              bool &CanAcceptVPTPredicationCode);
502   bool enableArchExtFeature(StringRef Name, SMLoc &ExtLoc);
503 
504   void tryConvertingToTwoOperandForm(StringRef Mnemonic, bool CarrySetting,
505                                      OperandVector &Operands);
506   bool CDEConvertDualRegOperand(StringRef Mnemonic, OperandVector &Operands);
507 
isThumb() const508   bool isThumb() const {
509     // FIXME: Can tablegen auto-generate this?
510     return getSTI().getFeatureBits()[ARM::ModeThumb];
511   }
512 
isThumbOne() const513   bool isThumbOne() const {
514     return isThumb() && !getSTI().getFeatureBits()[ARM::FeatureThumb2];
515   }
516 
isThumbTwo() const517   bool isThumbTwo() const {
518     return isThumb() && getSTI().getFeatureBits()[ARM::FeatureThumb2];
519   }
520 
hasThumb() const521   bool hasThumb() const {
522     return getSTI().getFeatureBits()[ARM::HasV4TOps];
523   }
524 
hasThumb2() const525   bool hasThumb2() const {
526     return getSTI().getFeatureBits()[ARM::FeatureThumb2];
527   }
528 
hasV6Ops() const529   bool hasV6Ops() const {
530     return getSTI().getFeatureBits()[ARM::HasV6Ops];
531   }
532 
hasV6T2Ops() const533   bool hasV6T2Ops() const {
534     return getSTI().getFeatureBits()[ARM::HasV6T2Ops];
535   }
536 
hasV6MOps() const537   bool hasV6MOps() const {
538     return getSTI().getFeatureBits()[ARM::HasV6MOps];
539   }
540 
hasV7Ops() const541   bool hasV7Ops() const {
542     return getSTI().getFeatureBits()[ARM::HasV7Ops];
543   }
544 
hasV8Ops() const545   bool hasV8Ops() const {
546     return getSTI().getFeatureBits()[ARM::HasV8Ops];
547   }
548 
hasV8MBaseline() const549   bool hasV8MBaseline() const {
550     return getSTI().getFeatureBits()[ARM::HasV8MBaselineOps];
551   }
552 
hasV8MMainline() const553   bool hasV8MMainline() const {
554     return getSTI().getFeatureBits()[ARM::HasV8MMainlineOps];
555   }
hasV8_1MMainline() const556   bool hasV8_1MMainline() const {
557     return getSTI().getFeatureBits()[ARM::HasV8_1MMainlineOps];
558   }
hasMVE() const559   bool hasMVE() const {
560     return getSTI().getFeatureBits()[ARM::HasMVEIntegerOps];
561   }
hasMVEFloat() const562   bool hasMVEFloat() const {
563     return getSTI().getFeatureBits()[ARM::HasMVEFloatOps];
564   }
hasCDE() const565   bool hasCDE() const {
566     return getSTI().getFeatureBits()[ARM::HasCDEOps];
567   }
has8MSecExt() const568   bool has8MSecExt() const {
569     return getSTI().getFeatureBits()[ARM::Feature8MSecExt];
570   }
571 
hasARM() const572   bool hasARM() const {
573     return !getSTI().getFeatureBits()[ARM::FeatureNoARM];
574   }
575 
hasDSP() const576   bool hasDSP() const {
577     return getSTI().getFeatureBits()[ARM::FeatureDSP];
578   }
579 
hasD32() const580   bool hasD32() const {
581     return getSTI().getFeatureBits()[ARM::FeatureD32];
582   }
583 
hasV8_1aOps() const584   bool hasV8_1aOps() const {
585     return getSTI().getFeatureBits()[ARM::HasV8_1aOps];
586   }
587 
hasRAS() const588   bool hasRAS() const {
589     return getSTI().getFeatureBits()[ARM::FeatureRAS];
590   }
591 
SwitchMode()592   void SwitchMode() {
593     MCSubtargetInfo &STI = copySTI();
594     auto FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
595     setAvailableFeatures(FB);
596   }
597 
598   void FixModeAfterArchChange(bool WasThumb, SMLoc Loc);
599 
isMClass() const600   bool isMClass() const {
601     return getSTI().getFeatureBits()[ARM::FeatureMClass];
602   }
603 
604   /// @name Auto-generated Match Functions
605   /// {
606 
607 #define GET_ASSEMBLER_HEADER
608 #include "ARMGenAsmMatcher.inc"
609 
610   /// }
611 
612   OperandMatchResultTy parseITCondCode(OperandVector &);
613   OperandMatchResultTy parseCoprocNumOperand(OperandVector &);
614   OperandMatchResultTy parseCoprocRegOperand(OperandVector &);
615   OperandMatchResultTy parseCoprocOptionOperand(OperandVector &);
616   OperandMatchResultTy parseMemBarrierOptOperand(OperandVector &);
617   OperandMatchResultTy parseTraceSyncBarrierOptOperand(OperandVector &);
618   OperandMatchResultTy parseInstSyncBarrierOptOperand(OperandVector &);
619   OperandMatchResultTy parseProcIFlagsOperand(OperandVector &);
620   OperandMatchResultTy parseMSRMaskOperand(OperandVector &);
621   OperandMatchResultTy parseBankedRegOperand(OperandVector &);
622   OperandMatchResultTy parsePKHImm(OperandVector &O, StringRef Op, int Low,
623                                    int High);
parsePKHLSLImm(OperandVector & O)624   OperandMatchResultTy parsePKHLSLImm(OperandVector &O) {
625     return parsePKHImm(O, "lsl", 0, 31);
626   }
parsePKHASRImm(OperandVector & O)627   OperandMatchResultTy parsePKHASRImm(OperandVector &O) {
628     return parsePKHImm(O, "asr", 1, 32);
629   }
630   OperandMatchResultTy parseSetEndImm(OperandVector &);
631   OperandMatchResultTy parseShifterImm(OperandVector &);
632   OperandMatchResultTy parseRotImm(OperandVector &);
633   OperandMatchResultTy parseModImm(OperandVector &);
634   OperandMatchResultTy parseBitfield(OperandVector &);
635   OperandMatchResultTy parsePostIdxReg(OperandVector &);
636   OperandMatchResultTy parseAM3Offset(OperandVector &);
637   OperandMatchResultTy parseFPImm(OperandVector &);
638   OperandMatchResultTy parseVectorList(OperandVector &);
639   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index,
640                                        SMLoc &EndLoc);
641 
642   // Asm Match Converter Methods
643   void cvtThumbMultiply(MCInst &Inst, const OperandVector &);
644   void cvtThumbBranches(MCInst &Inst, const OperandVector &);
645   void cvtMVEVMOVQtoDReg(MCInst &Inst, const OperandVector &);
646 
647   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
648   bool processInstruction(MCInst &Inst, const OperandVector &Ops, MCStreamer &Out);
649   bool shouldOmitCCOutOperand(StringRef Mnemonic, OperandVector &Operands);
650   bool shouldOmitPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
651   bool shouldOmitVectorPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
652   bool isITBlockTerminator(MCInst &Inst) const;
653   void fixupGNULDRDAlias(StringRef Mnemonic, OperandVector &Operands);
654   bool validateLDRDSTRD(MCInst &Inst, const OperandVector &Operands,
655                         bool Load, bool ARMMode, bool Writeback);
656 
657 public:
658   enum ARMMatchResultTy {
659     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
660     Match_RequiresNotITBlock,
661     Match_RequiresV6,
662     Match_RequiresThumb2,
663     Match_RequiresV8,
664     Match_RequiresFlagSetting,
665 #define GET_OPERAND_DIAGNOSTIC_TYPES
666 #include "ARMGenAsmMatcher.inc"
667 
668   };
669 
ARMAsmParser(const MCSubtargetInfo & STI,MCAsmParser & Parser,const MCInstrInfo & MII,const MCTargetOptions & Options)670   ARMAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
671                const MCInstrInfo &MII, const MCTargetOptions &Options)
672     : MCTargetAsmParser(Options, STI, MII), UC(Parser), MS(STI) {
673     MCAsmParserExtension::Initialize(Parser);
674 
675     // Cache the MCRegisterInfo.
676     MRI = getContext().getRegisterInfo();
677 
678     // Initialize the set of available features.
679     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
680 
681     // Add build attributes based on the selected target.
682     if (AddBuildAttributes)
683       getTargetStreamer().emitTargetAttributes(STI);
684 
685     // Not in an ITBlock to start with.
686     ITState.CurPosition = ~0U;
687 
688     VPTState.CurPosition = ~0U;
689 
690     NextSymbolIsThumb = false;
691   }
692 
693   // Implementation of the MCTargetAsmParser interface:
694   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
695   OperandMatchResultTy tryParseRegister(unsigned &RegNo, SMLoc &StartLoc,
696                                         SMLoc &EndLoc) override;
697   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
698                         SMLoc NameLoc, OperandVector &Operands) override;
699   bool ParseDirective(AsmToken DirectiveID) override;
700 
701   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
702                                       unsigned Kind) override;
703   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
704 
705   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
706                                OperandVector &Operands, MCStreamer &Out,
707                                uint64_t &ErrorInfo,
708                                bool MatchingInlineAsm) override;
709   unsigned MatchInstruction(OperandVector &Operands, MCInst &Inst,
710                             SmallVectorImpl<NearMissInfo> &NearMisses,
711                             bool MatchingInlineAsm, bool &EmitInITBlock,
712                             MCStreamer &Out);
713 
714   struct NearMissMessage {
715     SMLoc Loc;
716     SmallString<128> Message;
717   };
718 
719   const char *getCustomOperandDiag(ARMMatchResultTy MatchError);
720 
721   void FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
722                         SmallVectorImpl<NearMissMessage> &NearMissesOut,
723                         SMLoc IDLoc, OperandVector &Operands);
724   void ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses, SMLoc IDLoc,
725                         OperandVector &Operands);
726 
727   void doBeforeLabelEmit(MCSymbol *Symbol) override;
728 
729   void onLabelParsed(MCSymbol *Symbol) override;
730 };
731 
732 /// ARMOperand - Instances of this class represent a parsed ARM machine
733 /// operand.
734 class ARMOperand : public MCParsedAsmOperand {
735   enum KindTy {
736     k_CondCode,
737     k_VPTPred,
738     k_CCOut,
739     k_ITCondMask,
740     k_CoprocNum,
741     k_CoprocReg,
742     k_CoprocOption,
743     k_Immediate,
744     k_MemBarrierOpt,
745     k_InstSyncBarrierOpt,
746     k_TraceSyncBarrierOpt,
747     k_Memory,
748     k_PostIndexRegister,
749     k_MSRMask,
750     k_BankedReg,
751     k_ProcIFlags,
752     k_VectorIndex,
753     k_Register,
754     k_RegisterList,
755     k_RegisterListWithAPSR,
756     k_DPRRegisterList,
757     k_SPRRegisterList,
758     k_FPSRegisterListWithVPR,
759     k_FPDRegisterListWithVPR,
760     k_VectorList,
761     k_VectorListAllLanes,
762     k_VectorListIndexed,
763     k_ShiftedRegister,
764     k_ShiftedImmediate,
765     k_ShifterImmediate,
766     k_RotateImmediate,
767     k_ModifiedImmediate,
768     k_ConstantPoolImmediate,
769     k_BitfieldDescriptor,
770     k_Token,
771   } Kind;
772 
773   SMLoc StartLoc, EndLoc, AlignmentLoc;
774   SmallVector<unsigned, 8> Registers;
775 
776   struct CCOp {
777     ARMCC::CondCodes Val;
778   };
779 
780   struct VCCOp {
781     ARMVCC::VPTCodes Val;
782   };
783 
784   struct CopOp {
785     unsigned Val;
786   };
787 
788   struct CoprocOptionOp {
789     unsigned Val;
790   };
791 
792   struct ITMaskOp {
793     unsigned Mask:4;
794   };
795 
796   struct MBOptOp {
797     ARM_MB::MemBOpt Val;
798   };
799 
800   struct ISBOptOp {
801     ARM_ISB::InstSyncBOpt Val;
802   };
803 
804   struct TSBOptOp {
805     ARM_TSB::TraceSyncBOpt Val;
806   };
807 
808   struct IFlagsOp {
809     ARM_PROC::IFlags Val;
810   };
811 
812   struct MMaskOp {
813     unsigned Val;
814   };
815 
816   struct BankedRegOp {
817     unsigned Val;
818   };
819 
820   struct TokOp {
821     const char *Data;
822     unsigned Length;
823   };
824 
825   struct RegOp {
826     unsigned RegNum;
827   };
828 
829   // A vector register list is a sequential list of 1 to 4 registers.
830   struct VectorListOp {
831     unsigned RegNum;
832     unsigned Count;
833     unsigned LaneIndex;
834     bool isDoubleSpaced;
835   };
836 
837   struct VectorIndexOp {
838     unsigned Val;
839   };
840 
841   struct ImmOp {
842     const MCExpr *Val;
843   };
844 
845   /// Combined record for all forms of ARM address expressions.
846   struct MemoryOp {
847     unsigned BaseRegNum;
848     // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
849     // was specified.
850     const MCExpr *OffsetImm;  // Offset immediate value
851     unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
852     ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
853     unsigned ShiftImm;        // shift for OffsetReg.
854     unsigned Alignment;       // 0 = no alignment specified
855     // n = alignment in bytes (2, 4, 8, 16, or 32)
856     unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
857   };
858 
859   struct PostIdxRegOp {
860     unsigned RegNum;
861     bool isAdd;
862     ARM_AM::ShiftOpc ShiftTy;
863     unsigned ShiftImm;
864   };
865 
866   struct ShifterImmOp {
867     bool isASR;
868     unsigned Imm;
869   };
870 
871   struct RegShiftedRegOp {
872     ARM_AM::ShiftOpc ShiftTy;
873     unsigned SrcReg;
874     unsigned ShiftReg;
875     unsigned ShiftImm;
876   };
877 
878   struct RegShiftedImmOp {
879     ARM_AM::ShiftOpc ShiftTy;
880     unsigned SrcReg;
881     unsigned ShiftImm;
882   };
883 
884   struct RotImmOp {
885     unsigned Imm;
886   };
887 
888   struct ModImmOp {
889     unsigned Bits;
890     unsigned Rot;
891   };
892 
893   struct BitfieldOp {
894     unsigned LSB;
895     unsigned Width;
896   };
897 
898   union {
899     struct CCOp CC;
900     struct VCCOp VCC;
901     struct CopOp Cop;
902     struct CoprocOptionOp CoprocOption;
903     struct MBOptOp MBOpt;
904     struct ISBOptOp ISBOpt;
905     struct TSBOptOp TSBOpt;
906     struct ITMaskOp ITMask;
907     struct IFlagsOp IFlags;
908     struct MMaskOp MMask;
909     struct BankedRegOp BankedReg;
910     struct TokOp Tok;
911     struct RegOp Reg;
912     struct VectorListOp VectorList;
913     struct VectorIndexOp VectorIndex;
914     struct ImmOp Imm;
915     struct MemoryOp Memory;
916     struct PostIdxRegOp PostIdxReg;
917     struct ShifterImmOp ShifterImm;
918     struct RegShiftedRegOp RegShiftedReg;
919     struct RegShiftedImmOp RegShiftedImm;
920     struct RotImmOp RotImm;
921     struct ModImmOp ModImm;
922     struct BitfieldOp Bitfield;
923   };
924 
925 public:
ARMOperand(KindTy K)926   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
927 
928   /// getStartLoc - Get the location of the first token of this operand.
getStartLoc() const929   SMLoc getStartLoc() const override { return StartLoc; }
930 
931   /// getEndLoc - Get the location of the last token of this operand.
getEndLoc() const932   SMLoc getEndLoc() const override { return EndLoc; }
933 
934   /// getLocRange - Get the range between the first and last token of this
935   /// operand.
getLocRange() const936   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
937 
938   /// getAlignmentLoc - Get the location of the Alignment token of this operand.
getAlignmentLoc() const939   SMLoc getAlignmentLoc() const {
940     assert(Kind == k_Memory && "Invalid access!");
941     return AlignmentLoc;
942   }
943 
getCondCode() const944   ARMCC::CondCodes getCondCode() const {
945     assert(Kind == k_CondCode && "Invalid access!");
946     return CC.Val;
947   }
948 
getVPTPred() const949   ARMVCC::VPTCodes getVPTPred() const {
950     assert(isVPTPred() && "Invalid access!");
951     return VCC.Val;
952   }
953 
getCoproc() const954   unsigned getCoproc() const {
955     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
956     return Cop.Val;
957   }
958 
getToken() const959   StringRef getToken() const {
960     assert(Kind == k_Token && "Invalid access!");
961     return StringRef(Tok.Data, Tok.Length);
962   }
963 
getReg() const964   unsigned getReg() const override {
965     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
966     return Reg.RegNum;
967   }
968 
getRegList() const969   const SmallVectorImpl<unsigned> &getRegList() const {
970     assert((Kind == k_RegisterList || Kind == k_RegisterListWithAPSR ||
971             Kind == k_DPRRegisterList || Kind == k_SPRRegisterList ||
972             Kind == k_FPSRegisterListWithVPR ||
973             Kind == k_FPDRegisterListWithVPR) &&
974            "Invalid access!");
975     return Registers;
976   }
977 
getImm() const978   const MCExpr *getImm() const {
979     assert(isImm() && "Invalid access!");
980     return Imm.Val;
981   }
982 
getConstantPoolImm() const983   const MCExpr *getConstantPoolImm() const {
984     assert(isConstantPoolImm() && "Invalid access!");
985     return Imm.Val;
986   }
987 
getVectorIndex() const988   unsigned getVectorIndex() const {
989     assert(Kind == k_VectorIndex && "Invalid access!");
990     return VectorIndex.Val;
991   }
992 
getMemBarrierOpt() const993   ARM_MB::MemBOpt getMemBarrierOpt() const {
994     assert(Kind == k_MemBarrierOpt && "Invalid access!");
995     return MBOpt.Val;
996   }
997 
getInstSyncBarrierOpt() const998   ARM_ISB::InstSyncBOpt getInstSyncBarrierOpt() const {
999     assert(Kind == k_InstSyncBarrierOpt && "Invalid access!");
1000     return ISBOpt.Val;
1001   }
1002 
getTraceSyncBarrierOpt() const1003   ARM_TSB::TraceSyncBOpt getTraceSyncBarrierOpt() const {
1004     assert(Kind == k_TraceSyncBarrierOpt && "Invalid access!");
1005     return TSBOpt.Val;
1006   }
1007 
getProcIFlags() const1008   ARM_PROC::IFlags getProcIFlags() const {
1009     assert(Kind == k_ProcIFlags && "Invalid access!");
1010     return IFlags.Val;
1011   }
1012 
getMSRMask() const1013   unsigned getMSRMask() const {
1014     assert(Kind == k_MSRMask && "Invalid access!");
1015     return MMask.Val;
1016   }
1017 
getBankedReg() const1018   unsigned getBankedReg() const {
1019     assert(Kind == k_BankedReg && "Invalid access!");
1020     return BankedReg.Val;
1021   }
1022 
isCoprocNum() const1023   bool isCoprocNum() const { return Kind == k_CoprocNum; }
isCoprocReg() const1024   bool isCoprocReg() const { return Kind == k_CoprocReg; }
isCoprocOption() const1025   bool isCoprocOption() const { return Kind == k_CoprocOption; }
isCondCode() const1026   bool isCondCode() const { return Kind == k_CondCode; }
isVPTPred() const1027   bool isVPTPred() const { return Kind == k_VPTPred; }
isCCOut() const1028   bool isCCOut() const { return Kind == k_CCOut; }
isITMask() const1029   bool isITMask() const { return Kind == k_ITCondMask; }
isITCondCode() const1030   bool isITCondCode() const { return Kind == k_CondCode; }
isImm() const1031   bool isImm() const override {
1032     return Kind == k_Immediate;
1033   }
1034 
isARMBranchTarget() const1035   bool isARMBranchTarget() const {
1036     if (!isImm()) return false;
1037 
1038     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
1039       return CE->getValue() % 4 == 0;
1040     return true;
1041   }
1042 
1043 
isThumbBranchTarget() const1044   bool isThumbBranchTarget() const {
1045     if (!isImm()) return false;
1046 
1047     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
1048       return CE->getValue() % 2 == 0;
1049     return true;
1050   }
1051 
1052   // checks whether this operand is an unsigned offset which fits is a field
1053   // of specified width and scaled by a specific number of bits
1054   template<unsigned width, unsigned scale>
isUnsignedOffset() const1055   bool isUnsignedOffset() const {
1056     if (!isImm()) return false;
1057     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
1058     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
1059       int64_t Val = CE->getValue();
1060       int64_t Align = 1LL << scale;
1061       int64_t Max = Align * ((1LL << width) - 1);
1062       return ((Val % Align) == 0) && (Val >= 0) && (Val <= Max);
1063     }
1064     return false;
1065   }
1066 
1067   // checks whether this operand is an signed offset which fits is a field
1068   // of specified width and scaled by a specific number of bits
1069   template<unsigned width, unsigned scale>
isSignedOffset() const1070   bool isSignedOffset() const {
1071     if (!isImm()) return false;
1072     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
1073     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
1074       int64_t Val = CE->getValue();
1075       int64_t Align = 1LL << scale;
1076       int64_t Max = Align * ((1LL << (width-1)) - 1);
1077       int64_t Min = -Align * (1LL << (width-1));
1078       return ((Val % Align) == 0) && (Val >= Min) && (Val <= Max);
1079     }
1080     return false;
1081   }
1082 
1083   // checks whether this operand is an offset suitable for the LE /
1084   // LETP instructions in Arm v8.1M
isLEOffset() const1085   bool isLEOffset() const {
1086     if (!isImm()) return false;
1087     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
1088     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
1089       int64_t Val = CE->getValue();
1090       return Val < 0 && Val >= -4094 && (Val & 1) == 0;
1091     }
1092     return false;
1093   }
1094 
1095   // checks whether this operand is a memory operand computed as an offset
1096   // applied to PC. the offset may have 8 bits of magnitude and is represented
1097   // with two bits of shift. textually it may be either [pc, #imm], #imm or
1098   // relocable expression...
isThumbMemPC() const1099   bool isThumbMemPC() const {
1100     int64_t Val = 0;
1101     if (isImm()) {
1102       if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
1103       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
1104       if (!CE) return false;
1105       Val = CE->getValue();
1106     }
1107     else if (isGPRMem()) {
1108       if(!Memory.OffsetImm || Memory.OffsetRegNum) return false;
1109       if(Memory.BaseRegNum != ARM::PC) return false;
1110       if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm))
1111         Val = CE->getValue();
1112       else
1113         return false;
1114     }
1115     else return false;
1116     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
1117   }
1118 
isFPImm() const1119   bool isFPImm() const {
1120     if (!isImm()) return false;
1121     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1122     if (!CE) return false;
1123     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
1124     return Val != -1;
1125   }
1126 
1127   template<int64_t N, int64_t M>
isImmediate() const1128   bool isImmediate() const {
1129     if (!isImm()) return false;
1130     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1131     if (!CE) return false;
1132     int64_t Value = CE->getValue();
1133     return Value >= N && Value <= M;
1134   }
1135 
1136   template<int64_t N, int64_t M>
isImmediateS4() const1137   bool isImmediateS4() const {
1138     if (!isImm()) return false;
1139     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1140     if (!CE) return false;
1141     int64_t Value = CE->getValue();
1142     return ((Value & 3) == 0) && Value >= N && Value <= M;
1143   }
1144   template<int64_t N, int64_t M>
isImmediateS2() const1145   bool isImmediateS2() const {
1146     if (!isImm()) return false;
1147     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1148     if (!CE) return false;
1149     int64_t Value = CE->getValue();
1150     return ((Value & 1) == 0) && Value >= N && Value <= M;
1151   }
isFBits16() const1152   bool isFBits16() const {
1153     return isImmediate<0, 17>();
1154   }
isFBits32() const1155   bool isFBits32() const {
1156     return isImmediate<1, 33>();
1157   }
isImm8s4() const1158   bool isImm8s4() const {
1159     return isImmediateS4<-1020, 1020>();
1160   }
isImm7s4() const1161   bool isImm7s4() const {
1162     return isImmediateS4<-508, 508>();
1163   }
isImm7Shift0() const1164   bool isImm7Shift0() const {
1165     return isImmediate<-127, 127>();
1166   }
isImm7Shift1() const1167   bool isImm7Shift1() const {
1168     return isImmediateS2<-255, 255>();
1169   }
isImm7Shift2() const1170   bool isImm7Shift2() const {
1171     return isImmediateS4<-511, 511>();
1172   }
isImm7() const1173   bool isImm7() const {
1174     return isImmediate<-127, 127>();
1175   }
isImm0_1020s4() const1176   bool isImm0_1020s4() const {
1177     return isImmediateS4<0, 1020>();
1178   }
isImm0_508s4() const1179   bool isImm0_508s4() const {
1180     return isImmediateS4<0, 508>();
1181   }
isImm0_508s4Neg() const1182   bool isImm0_508s4Neg() const {
1183     if (!isImm()) return false;
1184     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1185     if (!CE) return false;
1186     int64_t Value = -CE->getValue();
1187     // explicitly exclude zero. we want that to use the normal 0_508 version.
1188     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
1189   }
1190 
isImm0_4095Neg() const1191   bool isImm0_4095Neg() const {
1192     if (!isImm()) return false;
1193     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1194     if (!CE) return false;
1195     // isImm0_4095Neg is used with 32-bit immediates only.
1196     // 32-bit immediates are zero extended to 64-bit when parsed,
1197     // thus simple -CE->getValue() results in a big negative number,
1198     // not a small positive number as intended
1199     if ((CE->getValue() >> 32) > 0) return false;
1200     uint32_t Value = -static_cast<uint32_t>(CE->getValue());
1201     return Value > 0 && Value < 4096;
1202   }
1203 
isImm0_7() const1204   bool isImm0_7() const {
1205     return isImmediate<0, 7>();
1206   }
1207 
isImm1_16() const1208   bool isImm1_16() const {
1209     return isImmediate<1, 16>();
1210   }
1211 
isImm1_32() const1212   bool isImm1_32() const {
1213     return isImmediate<1, 32>();
1214   }
1215 
isImm8_255() const1216   bool isImm8_255() const {
1217     return isImmediate<8, 255>();
1218   }
1219 
isImm256_65535Expr() const1220   bool isImm256_65535Expr() const {
1221     if (!isImm()) return false;
1222     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1223     // If it's not a constant expression, it'll generate a fixup and be
1224     // handled later.
1225     if (!CE) return true;
1226     int64_t Value = CE->getValue();
1227     return Value >= 256 && Value < 65536;
1228   }
1229 
isImm0_65535Expr() const1230   bool isImm0_65535Expr() const {
1231     if (!isImm()) return false;
1232     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1233     // If it's not a constant expression, it'll generate a fixup and be
1234     // handled later.
1235     if (!CE) return true;
1236     int64_t Value = CE->getValue();
1237     return Value >= 0 && Value < 65536;
1238   }
1239 
isImm24bit() const1240   bool isImm24bit() const {
1241     return isImmediate<0, 0xffffff + 1>();
1242   }
1243 
isImmThumbSR() const1244   bool isImmThumbSR() const {
1245     return isImmediate<1, 33>();
1246   }
1247 
1248   template<int shift>
isExpImmValue(uint64_t Value) const1249   bool isExpImmValue(uint64_t Value) const {
1250     uint64_t mask = (1 << shift) - 1;
1251     if ((Value & mask) != 0 || (Value >> shift) > 0xff)
1252       return false;
1253     return true;
1254   }
1255 
1256   template<int shift>
isExpImm() const1257   bool isExpImm() const {
1258     if (!isImm()) return false;
1259     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1260     if (!CE) return false;
1261 
1262     return isExpImmValue<shift>(CE->getValue());
1263   }
1264 
1265   template<int shift, int size>
isInvertedExpImm() const1266   bool isInvertedExpImm() const {
1267     if (!isImm()) return false;
1268     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1269     if (!CE) return false;
1270 
1271     uint64_t OriginalValue = CE->getValue();
1272     uint64_t InvertedValue = OriginalValue ^ (((uint64_t)1 << size) - 1);
1273     return isExpImmValue<shift>(InvertedValue);
1274   }
1275 
isPKHLSLImm() const1276   bool isPKHLSLImm() const {
1277     return isImmediate<0, 32>();
1278   }
1279 
isPKHASRImm() const1280   bool isPKHASRImm() const {
1281     return isImmediate<0, 33>();
1282   }
1283 
isAdrLabel() const1284   bool isAdrLabel() const {
1285     // If we have an immediate that's not a constant, treat it as a label
1286     // reference needing a fixup.
1287     if (isImm() && !isa<MCConstantExpr>(getImm()))
1288       return true;
1289 
1290     // If it is a constant, it must fit into a modified immediate encoding.
1291     if (!isImm()) return false;
1292     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1293     if (!CE) return false;
1294     int64_t Value = CE->getValue();
1295     return (ARM_AM::getSOImmVal(Value) != -1 ||
1296             ARM_AM::getSOImmVal(-Value) != -1);
1297   }
1298 
isT2SOImm() const1299   bool isT2SOImm() const {
1300     // If we have an immediate that's not a constant, treat it as an expression
1301     // needing a fixup.
1302     if (isImm() && !isa<MCConstantExpr>(getImm())) {
1303       // We want to avoid matching :upper16: and :lower16: as we want these
1304       // expressions to match in isImm0_65535Expr()
1305       const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(getImm());
1306       return (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
1307                              ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16));
1308     }
1309     if (!isImm()) return false;
1310     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1311     if (!CE) return false;
1312     int64_t Value = CE->getValue();
1313     return ARM_AM::getT2SOImmVal(Value) != -1;
1314   }
1315 
isT2SOImmNot() const1316   bool isT2SOImmNot() const {
1317     if (!isImm()) return false;
1318     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1319     if (!CE) return false;
1320     int64_t Value = CE->getValue();
1321     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1322       ARM_AM::getT2SOImmVal(~Value) != -1;
1323   }
1324 
isT2SOImmNeg() const1325   bool isT2SOImmNeg() const {
1326     if (!isImm()) return false;
1327     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1328     if (!CE) return false;
1329     int64_t Value = CE->getValue();
1330     // Only use this when not representable as a plain so_imm.
1331     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1332       ARM_AM::getT2SOImmVal(-Value) != -1;
1333   }
1334 
isSetEndImm() const1335   bool isSetEndImm() const {
1336     if (!isImm()) return false;
1337     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1338     if (!CE) return false;
1339     int64_t Value = CE->getValue();
1340     return Value == 1 || Value == 0;
1341   }
1342 
isReg() const1343   bool isReg() const override { return Kind == k_Register; }
isRegList() const1344   bool isRegList() const { return Kind == k_RegisterList; }
isRegListWithAPSR() const1345   bool isRegListWithAPSR() const {
1346     return Kind == k_RegisterListWithAPSR || Kind == k_RegisterList;
1347   }
isDPRRegList() const1348   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
isSPRRegList() const1349   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
isFPSRegListWithVPR() const1350   bool isFPSRegListWithVPR() const { return Kind == k_FPSRegisterListWithVPR; }
isFPDRegListWithVPR() const1351   bool isFPDRegListWithVPR() const { return Kind == k_FPDRegisterListWithVPR; }
isToken() const1352   bool isToken() const override { return Kind == k_Token; }
isMemBarrierOpt() const1353   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
isInstSyncBarrierOpt() const1354   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
isTraceSyncBarrierOpt() const1355   bool isTraceSyncBarrierOpt() const { return Kind == k_TraceSyncBarrierOpt; }
isMem() const1356   bool isMem() const override {
1357       return isGPRMem() || isMVEMem();
1358   }
isMVEMem() const1359   bool isMVEMem() const {
1360     if (Kind != k_Memory)
1361       return false;
1362     if (Memory.BaseRegNum &&
1363         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.BaseRegNum) &&
1364         !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(Memory.BaseRegNum))
1365       return false;
1366     if (Memory.OffsetRegNum &&
1367         !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1368             Memory.OffsetRegNum))
1369       return false;
1370     return true;
1371   }
isGPRMem() const1372   bool isGPRMem() const {
1373     if (Kind != k_Memory)
1374       return false;
1375     if (Memory.BaseRegNum &&
1376         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.BaseRegNum))
1377       return false;
1378     if (Memory.OffsetRegNum &&
1379         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.OffsetRegNum))
1380       return false;
1381     return true;
1382   }
isShifterImm() const1383   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
isRegShiftedReg() const1384   bool isRegShiftedReg() const {
1385     return Kind == k_ShiftedRegister &&
1386            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1387                RegShiftedReg.SrcReg) &&
1388            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1389                RegShiftedReg.ShiftReg);
1390   }
isRegShiftedImm() const1391   bool isRegShiftedImm() const {
1392     return Kind == k_ShiftedImmediate &&
1393            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1394                RegShiftedImm.SrcReg);
1395   }
isRotImm() const1396   bool isRotImm() const { return Kind == k_RotateImmediate; }
1397 
1398   template<unsigned Min, unsigned Max>
isPowerTwoInRange() const1399   bool isPowerTwoInRange() const {
1400     if (!isImm()) return false;
1401     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1402     if (!CE) return false;
1403     int64_t Value = CE->getValue();
1404     return Value > 0 && countPopulation((uint64_t)Value) == 1 &&
1405            Value >= Min && Value <= Max;
1406   }
isModImm() const1407   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1408 
isModImmNot() const1409   bool isModImmNot() const {
1410     if (!isImm()) return false;
1411     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1412     if (!CE) return false;
1413     int64_t Value = CE->getValue();
1414     return ARM_AM::getSOImmVal(~Value) != -1;
1415   }
1416 
isModImmNeg() const1417   bool isModImmNeg() const {
1418     if (!isImm()) return false;
1419     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1420     if (!CE) return false;
1421     int64_t Value = CE->getValue();
1422     return ARM_AM::getSOImmVal(Value) == -1 &&
1423       ARM_AM::getSOImmVal(-Value) != -1;
1424   }
1425 
isThumbModImmNeg1_7() const1426   bool isThumbModImmNeg1_7() const {
1427     if (!isImm()) return false;
1428     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1429     if (!CE) return false;
1430     int32_t Value = -(int32_t)CE->getValue();
1431     return 0 < Value && Value < 8;
1432   }
1433 
isThumbModImmNeg8_255() const1434   bool isThumbModImmNeg8_255() const {
1435     if (!isImm()) return false;
1436     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1437     if (!CE) return false;
1438     int32_t Value = -(int32_t)CE->getValue();
1439     return 7 < Value && Value < 256;
1440   }
1441 
isConstantPoolImm() const1442   bool isConstantPoolImm() const { return Kind == k_ConstantPoolImmediate; }
isBitfield() const1443   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
isPostIdxRegShifted() const1444   bool isPostIdxRegShifted() const {
1445     return Kind == k_PostIndexRegister &&
1446            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(PostIdxReg.RegNum);
1447   }
isPostIdxReg() const1448   bool isPostIdxReg() const {
1449     return isPostIdxRegShifted() && PostIdxReg.ShiftTy == ARM_AM::no_shift;
1450   }
isMemNoOffset(bool alignOK=false,unsigned Alignment=0) const1451   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1452     if (!isGPRMem())
1453       return false;
1454     // No offset of any kind.
1455     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1456      (alignOK || Memory.Alignment == Alignment);
1457   }
isMemNoOffsetT2(bool alignOK=false,unsigned Alignment=0) const1458   bool isMemNoOffsetT2(bool alignOK = false, unsigned Alignment = 0) const {
1459     if (!isGPRMem())
1460       return false;
1461 
1462     if (!ARMMCRegisterClasses[ARM::GPRnopcRegClassID].contains(
1463             Memory.BaseRegNum))
1464       return false;
1465 
1466     // No offset of any kind.
1467     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1468      (alignOK || Memory.Alignment == Alignment);
1469   }
isMemNoOffsetT2NoSp(bool alignOK=false,unsigned Alignment=0) const1470   bool isMemNoOffsetT2NoSp(bool alignOK = false, unsigned Alignment = 0) const {
1471     if (!isGPRMem())
1472       return false;
1473 
1474     if (!ARMMCRegisterClasses[ARM::rGPRRegClassID].contains(
1475             Memory.BaseRegNum))
1476       return false;
1477 
1478     // No offset of any kind.
1479     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1480      (alignOK || Memory.Alignment == Alignment);
1481   }
isMemNoOffsetT(bool alignOK=false,unsigned Alignment=0) const1482   bool isMemNoOffsetT(bool alignOK = false, unsigned Alignment = 0) const {
1483     if (!isGPRMem())
1484       return false;
1485 
1486     if (!ARMMCRegisterClasses[ARM::tGPRRegClassID].contains(
1487             Memory.BaseRegNum))
1488       return false;
1489 
1490     // No offset of any kind.
1491     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1492      (alignOK || Memory.Alignment == Alignment);
1493   }
isMemPCRelImm12() const1494   bool isMemPCRelImm12() const {
1495     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1496       return false;
1497     // Base register must be PC.
1498     if (Memory.BaseRegNum != ARM::PC)
1499       return false;
1500     // Immediate offset in range [-4095, 4095].
1501     if (!Memory.OffsetImm) return true;
1502     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1503       int64_t Val = CE->getValue();
1504       return (Val > -4096 && Val < 4096) ||
1505              (Val == std::numeric_limits<int32_t>::min());
1506     }
1507     return false;
1508   }
1509 
isAlignedMemory() const1510   bool isAlignedMemory() const {
1511     return isMemNoOffset(true);
1512   }
1513 
isAlignedMemoryNone() const1514   bool isAlignedMemoryNone() const {
1515     return isMemNoOffset(false, 0);
1516   }
1517 
isDupAlignedMemoryNone() const1518   bool isDupAlignedMemoryNone() const {
1519     return isMemNoOffset(false, 0);
1520   }
1521 
isAlignedMemory16() const1522   bool isAlignedMemory16() const {
1523     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1524       return true;
1525     return isMemNoOffset(false, 0);
1526   }
1527 
isDupAlignedMemory16() const1528   bool isDupAlignedMemory16() const {
1529     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1530       return true;
1531     return isMemNoOffset(false, 0);
1532   }
1533 
isAlignedMemory32() const1534   bool isAlignedMemory32() const {
1535     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1536       return true;
1537     return isMemNoOffset(false, 0);
1538   }
1539 
isDupAlignedMemory32() const1540   bool isDupAlignedMemory32() const {
1541     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1542       return true;
1543     return isMemNoOffset(false, 0);
1544   }
1545 
isAlignedMemory64() const1546   bool isAlignedMemory64() const {
1547     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1548       return true;
1549     return isMemNoOffset(false, 0);
1550   }
1551 
isDupAlignedMemory64() const1552   bool isDupAlignedMemory64() const {
1553     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1554       return true;
1555     return isMemNoOffset(false, 0);
1556   }
1557 
isAlignedMemory64or128() const1558   bool isAlignedMemory64or128() const {
1559     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1560       return true;
1561     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1562       return true;
1563     return isMemNoOffset(false, 0);
1564   }
1565 
isDupAlignedMemory64or128() const1566   bool isDupAlignedMemory64or128() const {
1567     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1568       return true;
1569     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1570       return true;
1571     return isMemNoOffset(false, 0);
1572   }
1573 
isAlignedMemory64or128or256() const1574   bool isAlignedMemory64or128or256() const {
1575     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1576       return true;
1577     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1578       return true;
1579     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1580       return true;
1581     return isMemNoOffset(false, 0);
1582   }
1583 
isAddrMode2() const1584   bool isAddrMode2() const {
1585     if (!isGPRMem() || Memory.Alignment != 0) return false;
1586     // Check for register offset.
1587     if (Memory.OffsetRegNum) return true;
1588     // Immediate offset in range [-4095, 4095].
1589     if (!Memory.OffsetImm) return true;
1590     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1591       int64_t Val = CE->getValue();
1592       return Val > -4096 && Val < 4096;
1593     }
1594     return false;
1595   }
1596 
isAM2OffsetImm() const1597   bool isAM2OffsetImm() const {
1598     if (!isImm()) return false;
1599     // Immediate offset in range [-4095, 4095].
1600     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1601     if (!CE) return false;
1602     int64_t Val = CE->getValue();
1603     return (Val == std::numeric_limits<int32_t>::min()) ||
1604            (Val > -4096 && Val < 4096);
1605   }
1606 
isAddrMode3() const1607   bool isAddrMode3() const {
1608     // If we have an immediate that's not a constant, treat it as a label
1609     // reference needing a fixup. If it is a constant, it's something else
1610     // and we reject it.
1611     if (isImm() && !isa<MCConstantExpr>(getImm()))
1612       return true;
1613     if (!isGPRMem() || Memory.Alignment != 0) return false;
1614     // No shifts are legal for AM3.
1615     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1616     // Check for register offset.
1617     if (Memory.OffsetRegNum) return true;
1618     // Immediate offset in range [-255, 255].
1619     if (!Memory.OffsetImm) return true;
1620     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1621       int64_t Val = CE->getValue();
1622       // The #-0 offset is encoded as std::numeric_limits<int32_t>::min(), and
1623       // we have to check for this too.
1624       return (Val > -256 && Val < 256) ||
1625              Val == std::numeric_limits<int32_t>::min();
1626     }
1627     return false;
1628   }
1629 
isAM3Offset() const1630   bool isAM3Offset() const {
1631     if (isPostIdxReg())
1632       return true;
1633     if (!isImm())
1634       return false;
1635     // Immediate offset in range [-255, 255].
1636     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1637     if (!CE) return false;
1638     int64_t Val = CE->getValue();
1639     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1640     return (Val > -256 && Val < 256) ||
1641            Val == std::numeric_limits<int32_t>::min();
1642   }
1643 
isAddrMode5() const1644   bool isAddrMode5() const {
1645     // If we have an immediate that's not a constant, treat it as a label
1646     // reference needing a fixup. If it is a constant, it's something else
1647     // and we reject it.
1648     if (isImm() && !isa<MCConstantExpr>(getImm()))
1649       return true;
1650     if (!isGPRMem() || Memory.Alignment != 0) return false;
1651     // Check for register offset.
1652     if (Memory.OffsetRegNum) return false;
1653     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1654     if (!Memory.OffsetImm) return true;
1655     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1656       int64_t Val = CE->getValue();
1657       return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1658              Val == std::numeric_limits<int32_t>::min();
1659     }
1660     return false;
1661   }
1662 
isAddrMode5FP16() const1663   bool isAddrMode5FP16() const {
1664     // If we have an immediate that's not a constant, treat it as a label
1665     // reference needing a fixup. If it is a constant, it's something else
1666     // and we reject it.
1667     if (isImm() && !isa<MCConstantExpr>(getImm()))
1668       return true;
1669     if (!isGPRMem() || Memory.Alignment != 0) return false;
1670     // Check for register offset.
1671     if (Memory.OffsetRegNum) return false;
1672     // Immediate offset in range [-510, 510] and a multiple of 2.
1673     if (!Memory.OffsetImm) return true;
1674     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1675       int64_t Val = CE->getValue();
1676       return (Val >= -510 && Val <= 510 && ((Val & 1) == 0)) ||
1677              Val == std::numeric_limits<int32_t>::min();
1678     }
1679     return false;
1680   }
1681 
isMemTBB() const1682   bool isMemTBB() const {
1683     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1684         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1685       return false;
1686     return true;
1687   }
1688 
isMemTBH() const1689   bool isMemTBH() const {
1690     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1691         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1692         Memory.Alignment != 0 )
1693       return false;
1694     return true;
1695   }
1696 
isMemRegOffset() const1697   bool isMemRegOffset() const {
1698     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1699       return false;
1700     return true;
1701   }
1702 
isT2MemRegOffset() const1703   bool isT2MemRegOffset() const {
1704     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1705         Memory.Alignment != 0 || Memory.BaseRegNum == ARM::PC)
1706       return false;
1707     // Only lsl #{0, 1, 2, 3} allowed.
1708     if (Memory.ShiftType == ARM_AM::no_shift)
1709       return true;
1710     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1711       return false;
1712     return true;
1713   }
1714 
isMemThumbRR() const1715   bool isMemThumbRR() const {
1716     // Thumb reg+reg addressing is simple. Just two registers, a base and
1717     // an offset. No shifts, negations or any other complicating factors.
1718     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1719         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1720       return false;
1721     return isARMLowRegister(Memory.BaseRegNum) &&
1722       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1723   }
1724 
isMemThumbRIs4() const1725   bool isMemThumbRIs4() const {
1726     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1727         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1728       return false;
1729     // Immediate offset, multiple of 4 in range [0, 124].
1730     if (!Memory.OffsetImm) return true;
1731     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1732       int64_t Val = CE->getValue();
1733       return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1734     }
1735     return false;
1736   }
1737 
isMemThumbRIs2() const1738   bool isMemThumbRIs2() const {
1739     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1740         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1741       return false;
1742     // Immediate offset, multiple of 4 in range [0, 62].
1743     if (!Memory.OffsetImm) return true;
1744     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1745       int64_t Val = CE->getValue();
1746       return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1747     }
1748     return false;
1749   }
1750 
isMemThumbRIs1() const1751   bool isMemThumbRIs1() const {
1752     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1753         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1754       return false;
1755     // Immediate offset in range [0, 31].
1756     if (!Memory.OffsetImm) return true;
1757     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1758       int64_t Val = CE->getValue();
1759       return Val >= 0 && Val <= 31;
1760     }
1761     return false;
1762   }
1763 
isMemThumbSPI() const1764   bool isMemThumbSPI() const {
1765     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1766         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1767       return false;
1768     // Immediate offset, multiple of 4 in range [0, 1020].
1769     if (!Memory.OffsetImm) return true;
1770     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1771       int64_t Val = CE->getValue();
1772       return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1773     }
1774     return false;
1775   }
1776 
isMemImm8s4Offset() const1777   bool isMemImm8s4Offset() const {
1778     // If we have an immediate that's not a constant, treat it as a label
1779     // reference needing a fixup. If it is a constant, it's something else
1780     // and we reject it.
1781     if (isImm() && !isa<MCConstantExpr>(getImm()))
1782       return true;
1783     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1784       return false;
1785     // Immediate offset a multiple of 4 in range [-1020, 1020].
1786     if (!Memory.OffsetImm) return true;
1787     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1788       int64_t Val = CE->getValue();
1789       // Special case, #-0 is std::numeric_limits<int32_t>::min().
1790       return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) ||
1791              Val == std::numeric_limits<int32_t>::min();
1792     }
1793     return false;
1794   }
1795 
isMemImm7s4Offset() const1796   bool isMemImm7s4Offset() const {
1797     // If we have an immediate that's not a constant, treat it as a label
1798     // reference needing a fixup. If it is a constant, it's something else
1799     // and we reject it.
1800     if (isImm() && !isa<MCConstantExpr>(getImm()))
1801       return true;
1802     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0 ||
1803         !ARMMCRegisterClasses[ARM::GPRnopcRegClassID].contains(
1804             Memory.BaseRegNum))
1805       return false;
1806     // Immediate offset a multiple of 4 in range [-508, 508].
1807     if (!Memory.OffsetImm) return true;
1808     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1809       int64_t Val = CE->getValue();
1810       // Special case, #-0 is INT32_MIN.
1811       return (Val >= -508 && Val <= 508 && (Val & 3) == 0) || Val == INT32_MIN;
1812     }
1813     return false;
1814   }
1815 
isMemImm0_1020s4Offset() const1816   bool isMemImm0_1020s4Offset() const {
1817     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1818       return false;
1819     // Immediate offset a multiple of 4 in range [0, 1020].
1820     if (!Memory.OffsetImm) return true;
1821     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1822       int64_t Val = CE->getValue();
1823       return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1824     }
1825     return false;
1826   }
1827 
isMemImm8Offset() const1828   bool isMemImm8Offset() const {
1829     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1830       return false;
1831     // Base reg of PC isn't allowed for these encodings.
1832     if (Memory.BaseRegNum == ARM::PC) return false;
1833     // Immediate offset in range [-255, 255].
1834     if (!Memory.OffsetImm) return true;
1835     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1836       int64_t Val = CE->getValue();
1837       return (Val == std::numeric_limits<int32_t>::min()) ||
1838              (Val > -256 && Val < 256);
1839     }
1840     return false;
1841   }
1842 
1843   template<unsigned Bits, unsigned RegClassID>
isMemImm7ShiftedOffset() const1844   bool isMemImm7ShiftedOffset() const {
1845     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0 ||
1846         !ARMMCRegisterClasses[RegClassID].contains(Memory.BaseRegNum))
1847       return false;
1848 
1849     // Expect an immediate offset equal to an element of the range
1850     // [-127, 127], shifted left by Bits.
1851 
1852     if (!Memory.OffsetImm) return true;
1853     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1854       int64_t Val = CE->getValue();
1855 
1856       // INT32_MIN is a special-case value (indicating the encoding with
1857       // zero offset and the subtract bit set)
1858       if (Val == INT32_MIN)
1859         return true;
1860 
1861       unsigned Divisor = 1U << Bits;
1862 
1863       // Check that the low bits are zero
1864       if (Val % Divisor != 0)
1865         return false;
1866 
1867       // Check that the remaining offset is within range.
1868       Val /= Divisor;
1869       return (Val >= -127 && Val <= 127);
1870     }
1871     return false;
1872   }
1873 
isMemRegRQOffset() const1874   template <int shift> bool isMemRegRQOffset() const {
1875     if (!isMVEMem() || Memory.OffsetImm != 0 || Memory.Alignment != 0)
1876       return false;
1877 
1878     if (!ARMMCRegisterClasses[ARM::GPRnopcRegClassID].contains(
1879             Memory.BaseRegNum))
1880       return false;
1881     if (!ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1882             Memory.OffsetRegNum))
1883       return false;
1884 
1885     if (shift == 0 && Memory.ShiftType != ARM_AM::no_shift)
1886       return false;
1887 
1888     if (shift > 0 &&
1889         (Memory.ShiftType != ARM_AM::uxtw || Memory.ShiftImm != shift))
1890       return false;
1891 
1892     return true;
1893   }
1894 
isMemRegQOffset() const1895   template <int shift> bool isMemRegQOffset() const {
1896     if (!isMVEMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1897       return false;
1898 
1899     if (!ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1900             Memory.BaseRegNum))
1901       return false;
1902 
1903     if (!Memory.OffsetImm)
1904       return true;
1905     static_assert(shift < 56,
1906                   "Such that we dont shift by a value higher than 62");
1907     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1908       int64_t Val = CE->getValue();
1909 
1910       // The value must be a multiple of (1 << shift)
1911       if ((Val & ((1U << shift) - 1)) != 0)
1912         return false;
1913 
1914       // And be in the right range, depending on the amount that it is shifted
1915       // by.  Shift 0, is equal to 7 unsigned bits, the sign bit is set
1916       // separately.
1917       int64_t Range = (1U << (7 + shift)) - 1;
1918       return (Val == INT32_MIN) || (Val > -Range && Val < Range);
1919     }
1920     return false;
1921   }
1922 
isMemPosImm8Offset() const1923   bool isMemPosImm8Offset() const {
1924     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1925       return false;
1926     // Immediate offset in range [0, 255].
1927     if (!Memory.OffsetImm) return true;
1928     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1929       int64_t Val = CE->getValue();
1930       return Val >= 0 && Val < 256;
1931     }
1932     return false;
1933   }
1934 
isMemNegImm8Offset() const1935   bool isMemNegImm8Offset() const {
1936     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1937       return false;
1938     // Base reg of PC isn't allowed for these encodings.
1939     if (Memory.BaseRegNum == ARM::PC) return false;
1940     // Immediate offset in range [-255, -1].
1941     if (!Memory.OffsetImm) return false;
1942     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1943       int64_t Val = CE->getValue();
1944       return (Val == std::numeric_limits<int32_t>::min()) ||
1945              (Val > -256 && Val < 0);
1946     }
1947     return false;
1948   }
1949 
isMemUImm12Offset() const1950   bool isMemUImm12Offset() const {
1951     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1952       return false;
1953     // Immediate offset in range [0, 4095].
1954     if (!Memory.OffsetImm) return true;
1955     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1956       int64_t Val = CE->getValue();
1957       return (Val >= 0 && Val < 4096);
1958     }
1959     return false;
1960   }
1961 
isMemImm12Offset() const1962   bool isMemImm12Offset() const {
1963     // If we have an immediate that's not a constant, treat it as a label
1964     // reference needing a fixup. If it is a constant, it's something else
1965     // and we reject it.
1966 
1967     if (isImm() && !isa<MCConstantExpr>(getImm()))
1968       return true;
1969 
1970     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1971       return false;
1972     // Immediate offset in range [-4095, 4095].
1973     if (!Memory.OffsetImm) return true;
1974     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1975       int64_t Val = CE->getValue();
1976       return (Val > -4096 && Val < 4096) ||
1977              (Val == std::numeric_limits<int32_t>::min());
1978     }
1979     // If we have an immediate that's not a constant, treat it as a
1980     // symbolic expression needing a fixup.
1981     return true;
1982   }
1983 
isConstPoolAsmImm() const1984   bool isConstPoolAsmImm() const {
1985     // Delay processing of Constant Pool Immediate, this will turn into
1986     // a constant. Match no other operand
1987     return (isConstantPoolImm());
1988   }
1989 
isPostIdxImm8() const1990   bool isPostIdxImm8() const {
1991     if (!isImm()) return false;
1992     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1993     if (!CE) return false;
1994     int64_t Val = CE->getValue();
1995     return (Val > -256 && Val < 256) ||
1996            (Val == std::numeric_limits<int32_t>::min());
1997   }
1998 
isPostIdxImm8s4() const1999   bool isPostIdxImm8s4() const {
2000     if (!isImm()) return false;
2001     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2002     if (!CE) return false;
2003     int64_t Val = CE->getValue();
2004     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
2005            (Val == std::numeric_limits<int32_t>::min());
2006   }
2007 
isMSRMask() const2008   bool isMSRMask() const { return Kind == k_MSRMask; }
isBankedReg() const2009   bool isBankedReg() const { return Kind == k_BankedReg; }
isProcIFlags() const2010   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
2011 
2012   // NEON operands.
isSingleSpacedVectorList() const2013   bool isSingleSpacedVectorList() const {
2014     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
2015   }
2016 
isDoubleSpacedVectorList() const2017   bool isDoubleSpacedVectorList() const {
2018     return Kind == k_VectorList && VectorList.isDoubleSpaced;
2019   }
2020 
isVecListOneD() const2021   bool isVecListOneD() const {
2022     if (!isSingleSpacedVectorList()) return false;
2023     return VectorList.Count == 1;
2024   }
2025 
isVecListTwoMQ() const2026   bool isVecListTwoMQ() const {
2027     return isSingleSpacedVectorList() && VectorList.Count == 2 &&
2028            ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
2029                VectorList.RegNum);
2030   }
2031 
isVecListDPair() const2032   bool isVecListDPair() const {
2033     if (!isSingleSpacedVectorList()) return false;
2034     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
2035               .contains(VectorList.RegNum));
2036   }
2037 
isVecListThreeD() const2038   bool isVecListThreeD() const {
2039     if (!isSingleSpacedVectorList()) return false;
2040     return VectorList.Count == 3;
2041   }
2042 
isVecListFourD() const2043   bool isVecListFourD() const {
2044     if (!isSingleSpacedVectorList()) return false;
2045     return VectorList.Count == 4;
2046   }
2047 
isVecListDPairSpaced() const2048   bool isVecListDPairSpaced() const {
2049     if (Kind != k_VectorList) return false;
2050     if (isSingleSpacedVectorList()) return false;
2051     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
2052               .contains(VectorList.RegNum));
2053   }
2054 
isVecListThreeQ() const2055   bool isVecListThreeQ() const {
2056     if (!isDoubleSpacedVectorList()) return false;
2057     return VectorList.Count == 3;
2058   }
2059 
isVecListFourQ() const2060   bool isVecListFourQ() const {
2061     if (!isDoubleSpacedVectorList()) return false;
2062     return VectorList.Count == 4;
2063   }
2064 
isVecListFourMQ() const2065   bool isVecListFourMQ() const {
2066     return isSingleSpacedVectorList() && VectorList.Count == 4 &&
2067            ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
2068                VectorList.RegNum);
2069   }
2070 
isSingleSpacedVectorAllLanes() const2071   bool isSingleSpacedVectorAllLanes() const {
2072     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
2073   }
2074 
isDoubleSpacedVectorAllLanes() const2075   bool isDoubleSpacedVectorAllLanes() const {
2076     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
2077   }
2078 
isVecListOneDAllLanes() const2079   bool isVecListOneDAllLanes() const {
2080     if (!isSingleSpacedVectorAllLanes()) return false;
2081     return VectorList.Count == 1;
2082   }
2083 
isVecListDPairAllLanes() const2084   bool isVecListDPairAllLanes() const {
2085     if (!isSingleSpacedVectorAllLanes()) return false;
2086     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
2087               .contains(VectorList.RegNum));
2088   }
2089 
isVecListDPairSpacedAllLanes() const2090   bool isVecListDPairSpacedAllLanes() const {
2091     if (!isDoubleSpacedVectorAllLanes()) return false;
2092     return VectorList.Count == 2;
2093   }
2094 
isVecListThreeDAllLanes() const2095   bool isVecListThreeDAllLanes() const {
2096     if (!isSingleSpacedVectorAllLanes()) return false;
2097     return VectorList.Count == 3;
2098   }
2099 
isVecListThreeQAllLanes() const2100   bool isVecListThreeQAllLanes() const {
2101     if (!isDoubleSpacedVectorAllLanes()) return false;
2102     return VectorList.Count == 3;
2103   }
2104 
isVecListFourDAllLanes() const2105   bool isVecListFourDAllLanes() const {
2106     if (!isSingleSpacedVectorAllLanes()) return false;
2107     return VectorList.Count == 4;
2108   }
2109 
isVecListFourQAllLanes() const2110   bool isVecListFourQAllLanes() const {
2111     if (!isDoubleSpacedVectorAllLanes()) return false;
2112     return VectorList.Count == 4;
2113   }
2114 
isSingleSpacedVectorIndexed() const2115   bool isSingleSpacedVectorIndexed() const {
2116     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
2117   }
2118 
isDoubleSpacedVectorIndexed() const2119   bool isDoubleSpacedVectorIndexed() const {
2120     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
2121   }
2122 
isVecListOneDByteIndexed() const2123   bool isVecListOneDByteIndexed() const {
2124     if (!isSingleSpacedVectorIndexed()) return false;
2125     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
2126   }
2127 
isVecListOneDHWordIndexed() const2128   bool isVecListOneDHWordIndexed() const {
2129     if (!isSingleSpacedVectorIndexed()) return false;
2130     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
2131   }
2132 
isVecListOneDWordIndexed() const2133   bool isVecListOneDWordIndexed() const {
2134     if (!isSingleSpacedVectorIndexed()) return false;
2135     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
2136   }
2137 
isVecListTwoDByteIndexed() const2138   bool isVecListTwoDByteIndexed() const {
2139     if (!isSingleSpacedVectorIndexed()) return false;
2140     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
2141   }
2142 
isVecListTwoDHWordIndexed() const2143   bool isVecListTwoDHWordIndexed() const {
2144     if (!isSingleSpacedVectorIndexed()) return false;
2145     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
2146   }
2147 
isVecListTwoQWordIndexed() const2148   bool isVecListTwoQWordIndexed() const {
2149     if (!isDoubleSpacedVectorIndexed()) return false;
2150     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
2151   }
2152 
isVecListTwoQHWordIndexed() const2153   bool isVecListTwoQHWordIndexed() const {
2154     if (!isDoubleSpacedVectorIndexed()) return false;
2155     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
2156   }
2157 
isVecListTwoDWordIndexed() const2158   bool isVecListTwoDWordIndexed() const {
2159     if (!isSingleSpacedVectorIndexed()) return false;
2160     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
2161   }
2162 
isVecListThreeDByteIndexed() const2163   bool isVecListThreeDByteIndexed() const {
2164     if (!isSingleSpacedVectorIndexed()) return false;
2165     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
2166   }
2167 
isVecListThreeDHWordIndexed() const2168   bool isVecListThreeDHWordIndexed() const {
2169     if (!isSingleSpacedVectorIndexed()) return false;
2170     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
2171   }
2172 
isVecListThreeQWordIndexed() const2173   bool isVecListThreeQWordIndexed() const {
2174     if (!isDoubleSpacedVectorIndexed()) return false;
2175     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
2176   }
2177 
isVecListThreeQHWordIndexed() const2178   bool isVecListThreeQHWordIndexed() const {
2179     if (!isDoubleSpacedVectorIndexed()) return false;
2180     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
2181   }
2182 
isVecListThreeDWordIndexed() const2183   bool isVecListThreeDWordIndexed() const {
2184     if (!isSingleSpacedVectorIndexed()) return false;
2185     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
2186   }
2187 
isVecListFourDByteIndexed() const2188   bool isVecListFourDByteIndexed() const {
2189     if (!isSingleSpacedVectorIndexed()) return false;
2190     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
2191   }
2192 
isVecListFourDHWordIndexed() const2193   bool isVecListFourDHWordIndexed() const {
2194     if (!isSingleSpacedVectorIndexed()) return false;
2195     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
2196   }
2197 
isVecListFourQWordIndexed() const2198   bool isVecListFourQWordIndexed() const {
2199     if (!isDoubleSpacedVectorIndexed()) return false;
2200     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
2201   }
2202 
isVecListFourQHWordIndexed() const2203   bool isVecListFourQHWordIndexed() const {
2204     if (!isDoubleSpacedVectorIndexed()) return false;
2205     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
2206   }
2207 
isVecListFourDWordIndexed() const2208   bool isVecListFourDWordIndexed() const {
2209     if (!isSingleSpacedVectorIndexed()) return false;
2210     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
2211   }
2212 
isVectorIndex() const2213   bool isVectorIndex() const { return Kind == k_VectorIndex; }
2214 
2215   template <unsigned NumLanes>
isVectorIndexInRange() const2216   bool isVectorIndexInRange() const {
2217     if (Kind != k_VectorIndex) return false;
2218     return VectorIndex.Val < NumLanes;
2219   }
2220 
isVectorIndex8() const2221   bool isVectorIndex8()  const { return isVectorIndexInRange<8>(); }
isVectorIndex16() const2222   bool isVectorIndex16() const { return isVectorIndexInRange<4>(); }
isVectorIndex32() const2223   bool isVectorIndex32() const { return isVectorIndexInRange<2>(); }
isVectorIndex64() const2224   bool isVectorIndex64() const { return isVectorIndexInRange<1>(); }
2225 
2226   template<int PermittedValue, int OtherPermittedValue>
isMVEPairVectorIndex() const2227   bool isMVEPairVectorIndex() const {
2228     if (Kind != k_VectorIndex) return false;
2229     return VectorIndex.Val == PermittedValue ||
2230            VectorIndex.Val == OtherPermittedValue;
2231   }
2232 
isNEONi8splat() const2233   bool isNEONi8splat() const {
2234     if (!isImm()) return false;
2235     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2236     // Must be a constant.
2237     if (!CE) return false;
2238     int64_t Value = CE->getValue();
2239     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
2240     // value.
2241     return Value >= 0 && Value < 256;
2242   }
2243 
isNEONi16splat() const2244   bool isNEONi16splat() const {
2245     if (isNEONByteReplicate(2))
2246       return false; // Leave that for bytes replication and forbid by default.
2247     if (!isImm())
2248       return false;
2249     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2250     // Must be a constant.
2251     if (!CE) return false;
2252     unsigned Value = CE->getValue();
2253     return ARM_AM::isNEONi16splat(Value);
2254   }
2255 
isNEONi16splatNot() const2256   bool isNEONi16splatNot() const {
2257     if (!isImm())
2258       return false;
2259     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2260     // Must be a constant.
2261     if (!CE) return false;
2262     unsigned Value = CE->getValue();
2263     return ARM_AM::isNEONi16splat(~Value & 0xffff);
2264   }
2265 
isNEONi32splat() const2266   bool isNEONi32splat() const {
2267     if (isNEONByteReplicate(4))
2268       return false; // Leave that for bytes replication and forbid by default.
2269     if (!isImm())
2270       return false;
2271     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2272     // Must be a constant.
2273     if (!CE) return false;
2274     unsigned Value = CE->getValue();
2275     return ARM_AM::isNEONi32splat(Value);
2276   }
2277 
isNEONi32splatNot() const2278   bool isNEONi32splatNot() const {
2279     if (!isImm())
2280       return false;
2281     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2282     // Must be a constant.
2283     if (!CE) return false;
2284     unsigned Value = CE->getValue();
2285     return ARM_AM::isNEONi32splat(~Value);
2286   }
2287 
isValidNEONi32vmovImm(int64_t Value)2288   static bool isValidNEONi32vmovImm(int64_t Value) {
2289     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
2290     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
2291     return ((Value & 0xffffffffffffff00) == 0) ||
2292            ((Value & 0xffffffffffff00ff) == 0) ||
2293            ((Value & 0xffffffffff00ffff) == 0) ||
2294            ((Value & 0xffffffff00ffffff) == 0) ||
2295            ((Value & 0xffffffffffff00ff) == 0xff) ||
2296            ((Value & 0xffffffffff00ffff) == 0xffff);
2297   }
2298 
isNEONReplicate(unsigned Width,unsigned NumElems,bool Inv) const2299   bool isNEONReplicate(unsigned Width, unsigned NumElems, bool Inv) const {
2300     assert((Width == 8 || Width == 16 || Width == 32) &&
2301            "Invalid element width");
2302     assert(NumElems * Width <= 64 && "Invalid result width");
2303 
2304     if (!isImm())
2305       return false;
2306     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2307     // Must be a constant.
2308     if (!CE)
2309       return false;
2310     int64_t Value = CE->getValue();
2311     if (!Value)
2312       return false; // Don't bother with zero.
2313     if (Inv)
2314       Value = ~Value;
2315 
2316     uint64_t Mask = (1ull << Width) - 1;
2317     uint64_t Elem = Value & Mask;
2318     if (Width == 16 && (Elem & 0x00ff) != 0 && (Elem & 0xff00) != 0)
2319       return false;
2320     if (Width == 32 && !isValidNEONi32vmovImm(Elem))
2321       return false;
2322 
2323     for (unsigned i = 1; i < NumElems; ++i) {
2324       Value >>= Width;
2325       if ((Value & Mask) != Elem)
2326         return false;
2327     }
2328     return true;
2329   }
2330 
isNEONByteReplicate(unsigned NumBytes) const2331   bool isNEONByteReplicate(unsigned NumBytes) const {
2332     return isNEONReplicate(8, NumBytes, false);
2333   }
2334 
checkNeonReplicateArgs(unsigned FromW,unsigned ToW)2335   static void checkNeonReplicateArgs(unsigned FromW, unsigned ToW) {
2336     assert((FromW == 8 || FromW == 16 || FromW == 32) &&
2337            "Invalid source width");
2338     assert((ToW == 16 || ToW == 32 || ToW == 64) &&
2339            "Invalid destination width");
2340     assert(FromW < ToW && "ToW is not less than FromW");
2341   }
2342 
2343   template<unsigned FromW, unsigned ToW>
isNEONmovReplicate() const2344   bool isNEONmovReplicate() const {
2345     checkNeonReplicateArgs(FromW, ToW);
2346     if (ToW == 64 && isNEONi64splat())
2347       return false;
2348     return isNEONReplicate(FromW, ToW / FromW, false);
2349   }
2350 
2351   template<unsigned FromW, unsigned ToW>
isNEONinvReplicate() const2352   bool isNEONinvReplicate() const {
2353     checkNeonReplicateArgs(FromW, ToW);
2354     return isNEONReplicate(FromW, ToW / FromW, true);
2355   }
2356 
isNEONi32vmov() const2357   bool isNEONi32vmov() const {
2358     if (isNEONByteReplicate(4))
2359       return false; // Let it to be classified as byte-replicate case.
2360     if (!isImm())
2361       return false;
2362     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2363     // Must be a constant.
2364     if (!CE)
2365       return false;
2366     return isValidNEONi32vmovImm(CE->getValue());
2367   }
2368 
isNEONi32vmovNeg() const2369   bool isNEONi32vmovNeg() const {
2370     if (!isImm()) return false;
2371     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2372     // Must be a constant.
2373     if (!CE) return false;
2374     return isValidNEONi32vmovImm(~CE->getValue());
2375   }
2376 
isNEONi64splat() const2377   bool isNEONi64splat() const {
2378     if (!isImm()) return false;
2379     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2380     // Must be a constant.
2381     if (!CE) return false;
2382     uint64_t Value = CE->getValue();
2383     // i64 value with each byte being either 0 or 0xff.
2384     for (unsigned i = 0; i < 8; ++i, Value >>= 8)
2385       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
2386     return true;
2387   }
2388 
2389   template<int64_t Angle, int64_t Remainder>
isComplexRotation() const2390   bool isComplexRotation() const {
2391     if (!isImm()) return false;
2392 
2393     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2394     if (!CE) return false;
2395     uint64_t Value = CE->getValue();
2396 
2397     return (Value % Angle == Remainder && Value <= 270);
2398   }
2399 
isMVELongShift() const2400   bool isMVELongShift() const {
2401     if (!isImm()) return false;
2402     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2403     // Must be a constant.
2404     if (!CE) return false;
2405     uint64_t Value = CE->getValue();
2406     return Value >= 1 && Value <= 32;
2407   }
2408 
isMveSaturateOp() const2409   bool isMveSaturateOp() const {
2410     if (!isImm()) return false;
2411     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2412     if (!CE) return false;
2413     uint64_t Value = CE->getValue();
2414     return Value == 48 || Value == 64;
2415   }
2416 
isITCondCodeNoAL() const2417   bool isITCondCodeNoAL() const {
2418     if (!isITCondCode()) return false;
2419     ARMCC::CondCodes CC = getCondCode();
2420     return CC != ARMCC::AL;
2421   }
2422 
isITCondCodeRestrictedI() const2423   bool isITCondCodeRestrictedI() const {
2424     if (!isITCondCode())
2425       return false;
2426     ARMCC::CondCodes CC = getCondCode();
2427     return CC == ARMCC::EQ || CC == ARMCC::NE;
2428   }
2429 
isITCondCodeRestrictedS() const2430   bool isITCondCodeRestrictedS() const {
2431     if (!isITCondCode())
2432       return false;
2433     ARMCC::CondCodes CC = getCondCode();
2434     return CC == ARMCC::LT || CC == ARMCC::GT || CC == ARMCC::LE ||
2435            CC == ARMCC::GE;
2436   }
2437 
isITCondCodeRestrictedU() const2438   bool isITCondCodeRestrictedU() const {
2439     if (!isITCondCode())
2440       return false;
2441     ARMCC::CondCodes CC = getCondCode();
2442     return CC == ARMCC::HS || CC == ARMCC::HI;
2443   }
2444 
isITCondCodeRestrictedFP() const2445   bool isITCondCodeRestrictedFP() const {
2446     if (!isITCondCode())
2447       return false;
2448     ARMCC::CondCodes CC = getCondCode();
2449     return CC == ARMCC::EQ || CC == ARMCC::NE || CC == ARMCC::LT ||
2450            CC == ARMCC::GT || CC == ARMCC::LE || CC == ARMCC::GE;
2451   }
2452 
addExpr(MCInst & Inst,const MCExpr * Expr) const2453   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
2454     // Add as immediates when possible.  Null MCExpr = 0.
2455     if (!Expr)
2456       Inst.addOperand(MCOperand::createImm(0));
2457     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
2458       Inst.addOperand(MCOperand::createImm(CE->getValue()));
2459     else
2460       Inst.addOperand(MCOperand::createExpr(Expr));
2461   }
2462 
addARMBranchTargetOperands(MCInst & Inst,unsigned N) const2463   void addARMBranchTargetOperands(MCInst &Inst, unsigned N) const {
2464     assert(N == 1 && "Invalid number of operands!");
2465     addExpr(Inst, getImm());
2466   }
2467 
addThumbBranchTargetOperands(MCInst & Inst,unsigned N) const2468   void addThumbBranchTargetOperands(MCInst &Inst, unsigned N) const {
2469     assert(N == 1 && "Invalid number of operands!");
2470     addExpr(Inst, getImm());
2471   }
2472 
addCondCodeOperands(MCInst & Inst,unsigned N) const2473   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
2474     assert(N == 2 && "Invalid number of operands!");
2475     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
2476     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
2477     Inst.addOperand(MCOperand::createReg(RegNum));
2478   }
2479 
addVPTPredNOperands(MCInst & Inst,unsigned N) const2480   void addVPTPredNOperands(MCInst &Inst, unsigned N) const {
2481     assert(N == 2 && "Invalid number of operands!");
2482     Inst.addOperand(MCOperand::createImm(unsigned(getVPTPred())));
2483     unsigned RegNum = getVPTPred() == ARMVCC::None ? 0: ARM::P0;
2484     Inst.addOperand(MCOperand::createReg(RegNum));
2485   }
2486 
addVPTPredROperands(MCInst & Inst,unsigned N) const2487   void addVPTPredROperands(MCInst &Inst, unsigned N) const {
2488     assert(N == 3 && "Invalid number of operands!");
2489     addVPTPredNOperands(Inst, N-1);
2490     unsigned RegNum;
2491     if (getVPTPred() == ARMVCC::None) {
2492       RegNum = 0;
2493     } else {
2494       unsigned NextOpIndex = Inst.getNumOperands();
2495       const MCInstrDesc &MCID = ARMInsts[Inst.getOpcode()];
2496       int TiedOp = MCID.getOperandConstraint(NextOpIndex, MCOI::TIED_TO);
2497       assert(TiedOp >= 0 &&
2498              "Inactive register in vpred_r is not tied to an output!");
2499       RegNum = Inst.getOperand(TiedOp).getReg();
2500     }
2501     Inst.addOperand(MCOperand::createReg(RegNum));
2502   }
2503 
addCoprocNumOperands(MCInst & Inst,unsigned N) const2504   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
2505     assert(N == 1 && "Invalid number of operands!");
2506     Inst.addOperand(MCOperand::createImm(getCoproc()));
2507   }
2508 
addCoprocRegOperands(MCInst & Inst,unsigned N) const2509   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
2510     assert(N == 1 && "Invalid number of operands!");
2511     Inst.addOperand(MCOperand::createImm(getCoproc()));
2512   }
2513 
addCoprocOptionOperands(MCInst & Inst,unsigned N) const2514   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
2515     assert(N == 1 && "Invalid number of operands!");
2516     Inst.addOperand(MCOperand::createImm(CoprocOption.Val));
2517   }
2518 
addITMaskOperands(MCInst & Inst,unsigned N) const2519   void addITMaskOperands(MCInst &Inst, unsigned N) const {
2520     assert(N == 1 && "Invalid number of operands!");
2521     Inst.addOperand(MCOperand::createImm(ITMask.Mask));
2522   }
2523 
addITCondCodeOperands(MCInst & Inst,unsigned N) const2524   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
2525     assert(N == 1 && "Invalid number of operands!");
2526     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
2527   }
2528 
addITCondCodeInvOperands(MCInst & Inst,unsigned N) const2529   void addITCondCodeInvOperands(MCInst &Inst, unsigned N) const {
2530     assert(N == 1 && "Invalid number of operands!");
2531     Inst.addOperand(MCOperand::createImm(unsigned(ARMCC::getOppositeCondition(getCondCode()))));
2532   }
2533 
addCCOutOperands(MCInst & Inst,unsigned N) const2534   void addCCOutOperands(MCInst &Inst, unsigned N) const {
2535     assert(N == 1 && "Invalid number of operands!");
2536     Inst.addOperand(MCOperand::createReg(getReg()));
2537   }
2538 
addRegOperands(MCInst & Inst,unsigned N) const2539   void addRegOperands(MCInst &Inst, unsigned N) const {
2540     assert(N == 1 && "Invalid number of operands!");
2541     Inst.addOperand(MCOperand::createReg(getReg()));
2542   }
2543 
addRegShiftedRegOperands(MCInst & Inst,unsigned N) const2544   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
2545     assert(N == 3 && "Invalid number of operands!");
2546     assert(isRegShiftedReg() &&
2547            "addRegShiftedRegOperands() on non-RegShiftedReg!");
2548     Inst.addOperand(MCOperand::createReg(RegShiftedReg.SrcReg));
2549     Inst.addOperand(MCOperand::createReg(RegShiftedReg.ShiftReg));
2550     Inst.addOperand(MCOperand::createImm(
2551       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
2552   }
2553 
addRegShiftedImmOperands(MCInst & Inst,unsigned N) const2554   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
2555     assert(N == 2 && "Invalid number of operands!");
2556     assert(isRegShiftedImm() &&
2557            "addRegShiftedImmOperands() on non-RegShiftedImm!");
2558     Inst.addOperand(MCOperand::createReg(RegShiftedImm.SrcReg));
2559     // Shift of #32 is encoded as 0 where permitted
2560     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
2561     Inst.addOperand(MCOperand::createImm(
2562       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
2563   }
2564 
addShifterImmOperands(MCInst & Inst,unsigned N) const2565   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
2566     assert(N == 1 && "Invalid number of operands!");
2567     Inst.addOperand(MCOperand::createImm((ShifterImm.isASR << 5) |
2568                                          ShifterImm.Imm));
2569   }
2570 
addRegListOperands(MCInst & Inst,unsigned N) const2571   void addRegListOperands(MCInst &Inst, unsigned N) const {
2572     assert(N == 1 && "Invalid number of operands!");
2573     const SmallVectorImpl<unsigned> &RegList = getRegList();
2574     for (SmallVectorImpl<unsigned>::const_iterator
2575            I = RegList.begin(), E = RegList.end(); I != E; ++I)
2576       Inst.addOperand(MCOperand::createReg(*I));
2577   }
2578 
addRegListWithAPSROperands(MCInst & Inst,unsigned N) const2579   void addRegListWithAPSROperands(MCInst &Inst, unsigned N) const {
2580     assert(N == 1 && "Invalid number of operands!");
2581     const SmallVectorImpl<unsigned> &RegList = getRegList();
2582     for (SmallVectorImpl<unsigned>::const_iterator
2583            I = RegList.begin(), E = RegList.end(); I != E; ++I)
2584       Inst.addOperand(MCOperand::createReg(*I));
2585   }
2586 
addDPRRegListOperands(MCInst & Inst,unsigned N) const2587   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
2588     addRegListOperands(Inst, N);
2589   }
2590 
addSPRRegListOperands(MCInst & Inst,unsigned N) const2591   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
2592     addRegListOperands(Inst, N);
2593   }
2594 
addFPSRegListWithVPROperands(MCInst & Inst,unsigned N) const2595   void addFPSRegListWithVPROperands(MCInst &Inst, unsigned N) const {
2596     addRegListOperands(Inst, N);
2597   }
2598 
addFPDRegListWithVPROperands(MCInst & Inst,unsigned N) const2599   void addFPDRegListWithVPROperands(MCInst &Inst, unsigned N) const {
2600     addRegListOperands(Inst, N);
2601   }
2602 
addRotImmOperands(MCInst & Inst,unsigned N) const2603   void addRotImmOperands(MCInst &Inst, unsigned N) const {
2604     assert(N == 1 && "Invalid number of operands!");
2605     // Encoded as val>>3. The printer handles display as 8, 16, 24.
2606     Inst.addOperand(MCOperand::createImm(RotImm.Imm >> 3));
2607   }
2608 
addModImmOperands(MCInst & Inst,unsigned N) const2609   void addModImmOperands(MCInst &Inst, unsigned N) const {
2610     assert(N == 1 && "Invalid number of operands!");
2611 
2612     // Support for fixups (MCFixup)
2613     if (isImm())
2614       return addImmOperands(Inst, N);
2615 
2616     Inst.addOperand(MCOperand::createImm(ModImm.Bits | (ModImm.Rot << 7)));
2617   }
2618 
addModImmNotOperands(MCInst & Inst,unsigned N) const2619   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
2620     assert(N == 1 && "Invalid number of operands!");
2621     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2622     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
2623     Inst.addOperand(MCOperand::createImm(Enc));
2624   }
2625 
addModImmNegOperands(MCInst & Inst,unsigned N) const2626   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
2627     assert(N == 1 && "Invalid number of operands!");
2628     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2629     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
2630     Inst.addOperand(MCOperand::createImm(Enc));
2631   }
2632 
addThumbModImmNeg8_255Operands(MCInst & Inst,unsigned N) const2633   void addThumbModImmNeg8_255Operands(MCInst &Inst, unsigned N) const {
2634     assert(N == 1 && "Invalid number of operands!");
2635     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2636     uint32_t Val = -CE->getValue();
2637     Inst.addOperand(MCOperand::createImm(Val));
2638   }
2639 
addThumbModImmNeg1_7Operands(MCInst & Inst,unsigned N) const2640   void addThumbModImmNeg1_7Operands(MCInst &Inst, unsigned N) const {
2641     assert(N == 1 && "Invalid number of operands!");
2642     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2643     uint32_t Val = -CE->getValue();
2644     Inst.addOperand(MCOperand::createImm(Val));
2645   }
2646 
addBitfieldOperands(MCInst & Inst,unsigned N) const2647   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
2648     assert(N == 1 && "Invalid number of operands!");
2649     // Munge the lsb/width into a bitfield mask.
2650     unsigned lsb = Bitfield.LSB;
2651     unsigned width = Bitfield.Width;
2652     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
2653     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
2654                       (32 - (lsb + width)));
2655     Inst.addOperand(MCOperand::createImm(Mask));
2656   }
2657 
addImmOperands(MCInst & Inst,unsigned N) const2658   void addImmOperands(MCInst &Inst, unsigned N) const {
2659     assert(N == 1 && "Invalid number of operands!");
2660     addExpr(Inst, getImm());
2661   }
2662 
addFBits16Operands(MCInst & Inst,unsigned N) const2663   void addFBits16Operands(MCInst &Inst, unsigned N) const {
2664     assert(N == 1 && "Invalid number of operands!");
2665     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2666     Inst.addOperand(MCOperand::createImm(16 - CE->getValue()));
2667   }
2668 
addFBits32Operands(MCInst & Inst,unsigned N) const2669   void addFBits32Operands(MCInst &Inst, unsigned N) const {
2670     assert(N == 1 && "Invalid number of operands!");
2671     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2672     Inst.addOperand(MCOperand::createImm(32 - CE->getValue()));
2673   }
2674 
addFPImmOperands(MCInst & Inst,unsigned N) const2675   void addFPImmOperands(MCInst &Inst, unsigned N) const {
2676     assert(N == 1 && "Invalid number of operands!");
2677     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2678     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
2679     Inst.addOperand(MCOperand::createImm(Val));
2680   }
2681 
addImm8s4Operands(MCInst & Inst,unsigned N) const2682   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
2683     assert(N == 1 && "Invalid number of operands!");
2684     // FIXME: We really want to scale the value here, but the LDRD/STRD
2685     // instruction don't encode operands that way yet.
2686     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2687     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2688   }
2689 
addImm7s4Operands(MCInst & Inst,unsigned N) const2690   void addImm7s4Operands(MCInst &Inst, unsigned N) const {
2691     assert(N == 1 && "Invalid number of operands!");
2692     // FIXME: We really want to scale the value here, but the VSTR/VLDR_VSYSR
2693     // instruction don't encode operands that way yet.
2694     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2695     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2696   }
2697 
addImm7Shift0Operands(MCInst & Inst,unsigned N) const2698   void addImm7Shift0Operands(MCInst &Inst, unsigned N) const {
2699     assert(N == 1 && "Invalid number of operands!");
2700     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2701     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2702   }
2703 
addImm7Shift1Operands(MCInst & Inst,unsigned N) const2704   void addImm7Shift1Operands(MCInst &Inst, unsigned N) const {
2705     assert(N == 1 && "Invalid number of operands!");
2706     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2707     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2708   }
2709 
addImm7Shift2Operands(MCInst & Inst,unsigned N) const2710   void addImm7Shift2Operands(MCInst &Inst, unsigned N) const {
2711     assert(N == 1 && "Invalid number of operands!");
2712     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2713     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2714   }
2715 
addImm7Operands(MCInst & Inst,unsigned N) const2716   void addImm7Operands(MCInst &Inst, unsigned N) const {
2717     assert(N == 1 && "Invalid number of operands!");
2718     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2719     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2720   }
2721 
addImm0_1020s4Operands(MCInst & Inst,unsigned N) const2722   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
2723     assert(N == 1 && "Invalid number of operands!");
2724     // The immediate is scaled by four in the encoding and is stored
2725     // in the MCInst as such. Lop off the low two bits here.
2726     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2727     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2728   }
2729 
addImm0_508s4NegOperands(MCInst & Inst,unsigned N) const2730   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
2731     assert(N == 1 && "Invalid number of operands!");
2732     // The immediate is scaled by four in the encoding and is stored
2733     // in the MCInst as such. Lop off the low two bits here.
2734     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2735     Inst.addOperand(MCOperand::createImm(-(CE->getValue() / 4)));
2736   }
2737 
addImm0_508s4Operands(MCInst & Inst,unsigned N) const2738   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
2739     assert(N == 1 && "Invalid number of operands!");
2740     // The immediate is scaled by four in the encoding and is stored
2741     // in the MCInst as such. Lop off the low two bits here.
2742     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2743     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2744   }
2745 
addImm1_16Operands(MCInst & Inst,unsigned N) const2746   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
2747     assert(N == 1 && "Invalid number of operands!");
2748     // The constant encodes as the immediate-1, and we store in the instruction
2749     // the bits as encoded, so subtract off one here.
2750     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2751     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2752   }
2753 
addImm1_32Operands(MCInst & Inst,unsigned N) const2754   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
2755     assert(N == 1 && "Invalid number of operands!");
2756     // The constant encodes as the immediate-1, and we store in the instruction
2757     // the bits as encoded, so subtract off one here.
2758     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2759     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2760   }
2761 
addImmThumbSROperands(MCInst & Inst,unsigned N) const2762   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
2763     assert(N == 1 && "Invalid number of operands!");
2764     // The constant encodes as the immediate, except for 32, which encodes as
2765     // zero.
2766     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2767     unsigned Imm = CE->getValue();
2768     Inst.addOperand(MCOperand::createImm((Imm == 32 ? 0 : Imm)));
2769   }
2770 
addPKHASRImmOperands(MCInst & Inst,unsigned N) const2771   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
2772     assert(N == 1 && "Invalid number of operands!");
2773     // An ASR value of 32 encodes as 0, so that's how we want to add it to
2774     // the instruction as well.
2775     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2776     int Val = CE->getValue();
2777     Inst.addOperand(MCOperand::createImm(Val == 32 ? 0 : Val));
2778   }
2779 
addT2SOImmNotOperands(MCInst & Inst,unsigned N) const2780   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
2781     assert(N == 1 && "Invalid number of operands!");
2782     // The operand is actually a t2_so_imm, but we have its bitwise
2783     // negation in the assembly source, so twiddle it here.
2784     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2785     Inst.addOperand(MCOperand::createImm(~(uint32_t)CE->getValue()));
2786   }
2787 
addT2SOImmNegOperands(MCInst & Inst,unsigned N) const2788   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
2789     assert(N == 1 && "Invalid number of operands!");
2790     // The operand is actually a t2_so_imm, but we have its
2791     // negation in the assembly source, so twiddle it here.
2792     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2793     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2794   }
2795 
addImm0_4095NegOperands(MCInst & Inst,unsigned N) const2796   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
2797     assert(N == 1 && "Invalid number of operands!");
2798     // The operand is actually an imm0_4095, but we have its
2799     // negation in the assembly source, so twiddle it here.
2800     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2801     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2802   }
2803 
addUnsignedOffset_b8s2Operands(MCInst & Inst,unsigned N) const2804   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
2805     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
2806       Inst.addOperand(MCOperand::createImm(CE->getValue() >> 2));
2807       return;
2808     }
2809     const MCSymbolRefExpr *SR = cast<MCSymbolRefExpr>(Imm.Val);
2810     Inst.addOperand(MCOperand::createExpr(SR));
2811   }
2812 
addThumbMemPCOperands(MCInst & Inst,unsigned N) const2813   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
2814     assert(N == 1 && "Invalid number of operands!");
2815     if (isImm()) {
2816       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2817       if (CE) {
2818         Inst.addOperand(MCOperand::createImm(CE->getValue()));
2819         return;
2820       }
2821       const MCSymbolRefExpr *SR = cast<MCSymbolRefExpr>(Imm.Val);
2822       Inst.addOperand(MCOperand::createExpr(SR));
2823       return;
2824     }
2825 
2826     assert(isGPRMem()  && "Unknown value type!");
2827     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
2828     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm))
2829       Inst.addOperand(MCOperand::createImm(CE->getValue()));
2830     else
2831       Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
2832   }
2833 
addMemBarrierOptOperands(MCInst & Inst,unsigned N) const2834   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
2835     assert(N == 1 && "Invalid number of operands!");
2836     Inst.addOperand(MCOperand::createImm(unsigned(getMemBarrierOpt())));
2837   }
2838 
addInstSyncBarrierOptOperands(MCInst & Inst,unsigned N) const2839   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2840     assert(N == 1 && "Invalid number of operands!");
2841     Inst.addOperand(MCOperand::createImm(unsigned(getInstSyncBarrierOpt())));
2842   }
2843 
addTraceSyncBarrierOptOperands(MCInst & Inst,unsigned N) const2844   void addTraceSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2845     assert(N == 1 && "Invalid number of operands!");
2846     Inst.addOperand(MCOperand::createImm(unsigned(getTraceSyncBarrierOpt())));
2847   }
2848 
addMemNoOffsetOperands(MCInst & Inst,unsigned N) const2849   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
2850     assert(N == 1 && "Invalid number of operands!");
2851     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2852   }
2853 
addMemNoOffsetT2Operands(MCInst & Inst,unsigned N) const2854   void addMemNoOffsetT2Operands(MCInst &Inst, unsigned N) const {
2855     assert(N == 1 && "Invalid number of operands!");
2856     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2857   }
2858 
addMemNoOffsetT2NoSpOperands(MCInst & Inst,unsigned N) const2859   void addMemNoOffsetT2NoSpOperands(MCInst &Inst, unsigned N) const {
2860     assert(N == 1 && "Invalid number of operands!");
2861     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2862   }
2863 
addMemNoOffsetTOperands(MCInst & Inst,unsigned N) const2864   void addMemNoOffsetTOperands(MCInst &Inst, unsigned N) const {
2865     assert(N == 1 && "Invalid number of operands!");
2866     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2867   }
2868 
addMemPCRelImm12Operands(MCInst & Inst,unsigned N) const2869   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
2870     assert(N == 1 && "Invalid number of operands!");
2871     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm))
2872       Inst.addOperand(MCOperand::createImm(CE->getValue()));
2873     else
2874       Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
2875   }
2876 
addAdrLabelOperands(MCInst & Inst,unsigned N) const2877   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
2878     assert(N == 1 && "Invalid number of operands!");
2879     assert(isImm() && "Not an immediate!");
2880 
2881     // If we have an immediate that's not a constant, treat it as a label
2882     // reference needing a fixup.
2883     if (!isa<MCConstantExpr>(getImm())) {
2884       Inst.addOperand(MCOperand::createExpr(getImm()));
2885       return;
2886     }
2887 
2888     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2889     int Val = CE->getValue();
2890     Inst.addOperand(MCOperand::createImm(Val));
2891   }
2892 
addAlignedMemoryOperands(MCInst & Inst,unsigned N) const2893   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
2894     assert(N == 2 && "Invalid number of operands!");
2895     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2896     Inst.addOperand(MCOperand::createImm(Memory.Alignment));
2897   }
2898 
addDupAlignedMemoryNoneOperands(MCInst & Inst,unsigned N) const2899   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2900     addAlignedMemoryOperands(Inst, N);
2901   }
2902 
addAlignedMemoryNoneOperands(MCInst & Inst,unsigned N) const2903   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2904     addAlignedMemoryOperands(Inst, N);
2905   }
2906 
addAlignedMemory16Operands(MCInst & Inst,unsigned N) const2907   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2908     addAlignedMemoryOperands(Inst, N);
2909   }
2910 
addDupAlignedMemory16Operands(MCInst & Inst,unsigned N) const2911   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2912     addAlignedMemoryOperands(Inst, N);
2913   }
2914 
addAlignedMemory32Operands(MCInst & Inst,unsigned N) const2915   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2916     addAlignedMemoryOperands(Inst, N);
2917   }
2918 
addDupAlignedMemory32Operands(MCInst & Inst,unsigned N) const2919   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2920     addAlignedMemoryOperands(Inst, N);
2921   }
2922 
addAlignedMemory64Operands(MCInst & Inst,unsigned N) const2923   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2924     addAlignedMemoryOperands(Inst, N);
2925   }
2926 
addDupAlignedMemory64Operands(MCInst & Inst,unsigned N) const2927   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2928     addAlignedMemoryOperands(Inst, N);
2929   }
2930 
addAlignedMemory64or128Operands(MCInst & Inst,unsigned N) const2931   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2932     addAlignedMemoryOperands(Inst, N);
2933   }
2934 
addDupAlignedMemory64or128Operands(MCInst & Inst,unsigned N) const2935   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2936     addAlignedMemoryOperands(Inst, N);
2937   }
2938 
addAlignedMemory64or128or256Operands(MCInst & Inst,unsigned N) const2939   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2940     addAlignedMemoryOperands(Inst, N);
2941   }
2942 
addAddrMode2Operands(MCInst & Inst,unsigned N) const2943   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2944     assert(N == 3 && "Invalid number of operands!");
2945     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2946     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2947     if (!Memory.OffsetRegNum) {
2948       if (!Memory.OffsetImm)
2949         Inst.addOperand(MCOperand::createImm(0));
2950       else if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
2951         int32_t Val = CE->getValue();
2952         ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2953         // Special case for #-0
2954         if (Val == std::numeric_limits<int32_t>::min())
2955           Val = 0;
2956         if (Val < 0)
2957           Val = -Val;
2958         Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2959         Inst.addOperand(MCOperand::createImm(Val));
2960       } else
2961         Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
2962     } else {
2963       // For register offset, we encode the shift type and negation flag
2964       // here.
2965       int32_t Val =
2966           ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2967                             Memory.ShiftImm, Memory.ShiftType);
2968       Inst.addOperand(MCOperand::createImm(Val));
2969     }
2970   }
2971 
addAM2OffsetImmOperands(MCInst & Inst,unsigned N) const2972   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2973     assert(N == 2 && "Invalid number of operands!");
2974     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2975     assert(CE && "non-constant AM2OffsetImm operand!");
2976     int32_t Val = CE->getValue();
2977     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2978     // Special case for #-0
2979     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2980     if (Val < 0) Val = -Val;
2981     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2982     Inst.addOperand(MCOperand::createReg(0));
2983     Inst.addOperand(MCOperand::createImm(Val));
2984   }
2985 
addAddrMode3Operands(MCInst & Inst,unsigned N) const2986   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2987     assert(N == 3 && "Invalid number of operands!");
2988     // If we have an immediate that's not a constant, treat it as a label
2989     // reference needing a fixup. If it is a constant, it's something else
2990     // and we reject it.
2991     if (isImm()) {
2992       Inst.addOperand(MCOperand::createExpr(getImm()));
2993       Inst.addOperand(MCOperand::createReg(0));
2994       Inst.addOperand(MCOperand::createImm(0));
2995       return;
2996     }
2997 
2998     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2999     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3000     if (!Memory.OffsetRegNum) {
3001       if (!Memory.OffsetImm)
3002         Inst.addOperand(MCOperand::createImm(0));
3003       else if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
3004         int32_t Val = CE->getValue();
3005         ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
3006         // Special case for #-0
3007         if (Val == std::numeric_limits<int32_t>::min())
3008           Val = 0;
3009         if (Val < 0)
3010           Val = -Val;
3011         Val = ARM_AM::getAM3Opc(AddSub, Val);
3012         Inst.addOperand(MCOperand::createImm(Val));
3013       } else
3014         Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
3015     } else {
3016       // For register offset, we encode the shift type and negation flag
3017       // here.
3018       int32_t Val =
3019           ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
3020       Inst.addOperand(MCOperand::createImm(Val));
3021     }
3022   }
3023 
addAM3OffsetOperands(MCInst & Inst,unsigned N) const3024   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
3025     assert(N == 2 && "Invalid number of operands!");
3026     if (Kind == k_PostIndexRegister) {
3027       int32_t Val =
3028         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
3029       Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
3030       Inst.addOperand(MCOperand::createImm(Val));
3031       return;
3032     }
3033 
3034     // Constant offset.
3035     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
3036     int32_t Val = CE->getValue();
3037     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
3038     // Special case for #-0
3039     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
3040     if (Val < 0) Val = -Val;
3041     Val = ARM_AM::getAM3Opc(AddSub, Val);
3042     Inst.addOperand(MCOperand::createReg(0));
3043     Inst.addOperand(MCOperand::createImm(Val));
3044   }
3045 
addAddrMode5Operands(MCInst & Inst,unsigned N) const3046   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
3047     assert(N == 2 && "Invalid number of operands!");
3048     // If we have an immediate that's not a constant, treat it as a label
3049     // reference needing a fixup. If it is a constant, it's something else
3050     // and we reject it.
3051     if (isImm()) {
3052       Inst.addOperand(MCOperand::createExpr(getImm()));
3053       Inst.addOperand(MCOperand::createImm(0));
3054       return;
3055     }
3056 
3057     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3058     if (!Memory.OffsetImm)
3059       Inst.addOperand(MCOperand::createImm(0));
3060     else if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
3061       // The lower two bits are always zero and as such are not encoded.
3062       int32_t Val = CE->getValue() / 4;
3063       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
3064       // Special case for #-0
3065       if (Val == std::numeric_limits<int32_t>::min())
3066         Val = 0;
3067       if (Val < 0)
3068         Val = -Val;
3069       Val = ARM_AM::getAM5Opc(AddSub, Val);
3070       Inst.addOperand(MCOperand::createImm(Val));
3071     } else
3072       Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
3073   }
3074 
addAddrMode5FP16Operands(MCInst & Inst,unsigned N) const3075   void addAddrMode5FP16Operands(MCInst &Inst, unsigned N) const {
3076     assert(N == 2 && "Invalid number of operands!");
3077     // If we have an immediate that's not a constant, treat it as a label
3078     // reference needing a fixup. If it is a constant, it's something else
3079     // and we reject it.
3080     if (isImm()) {
3081       Inst.addOperand(MCOperand::createExpr(getImm()));
3082       Inst.addOperand(MCOperand::createImm(0));
3083       return;
3084     }
3085 
3086     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3087     // The lower bit is always zero and as such is not encoded.
3088     if (!Memory.OffsetImm)
3089       Inst.addOperand(MCOperand::createImm(0));
3090     else if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
3091       int32_t Val = CE->getValue() / 2;
3092       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
3093       // Special case for #-0
3094       if (Val == std::numeric_limits<int32_t>::min())
3095         Val = 0;
3096       if (Val < 0)
3097         Val = -Val;
3098       Val = ARM_AM::getAM5FP16Opc(AddSub, Val);
3099       Inst.addOperand(MCOperand::createImm(Val));
3100     } else
3101       Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
3102   }
3103 
addMemImm8s4OffsetOperands(MCInst & Inst,unsigned N) const3104   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
3105     assert(N == 2 && "Invalid number of operands!");
3106     // If we have an immediate that's not a constant, treat it as a label
3107     // reference needing a fixup. If it is a constant, it's something else
3108     // and we reject it.
3109     if (isImm()) {
3110       Inst.addOperand(MCOperand::createExpr(getImm()));
3111       Inst.addOperand(MCOperand::createImm(0));
3112       return;
3113     }
3114 
3115     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3116     addExpr(Inst, Memory.OffsetImm);
3117   }
3118 
addMemImm7s4OffsetOperands(MCInst & Inst,unsigned N) const3119   void addMemImm7s4OffsetOperands(MCInst &Inst, unsigned N) const {
3120     assert(N == 2 && "Invalid number of operands!");
3121     // If we have an immediate that's not a constant, treat it as a label
3122     // reference needing a fixup. If it is a constant, it's something else
3123     // and we reject it.
3124     if (isImm()) {
3125       Inst.addOperand(MCOperand::createExpr(getImm()));
3126       Inst.addOperand(MCOperand::createImm(0));
3127       return;
3128     }
3129 
3130     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3131     addExpr(Inst, Memory.OffsetImm);
3132   }
3133 
addMemImm0_1020s4OffsetOperands(MCInst & Inst,unsigned N) const3134   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
3135     assert(N == 2 && "Invalid number of operands!");
3136     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3137     if (!Memory.OffsetImm)
3138       Inst.addOperand(MCOperand::createImm(0));
3139     else if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm))
3140       // The lower two bits are always zero and as such are not encoded.
3141       Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
3142     else
3143       Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
3144   }
3145 
addMemImmOffsetOperands(MCInst & Inst,unsigned N) const3146   void addMemImmOffsetOperands(MCInst &Inst, unsigned N) const {
3147     assert(N == 2 && "Invalid number of operands!");
3148     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3149     addExpr(Inst, Memory.OffsetImm);
3150   }
3151 
addMemRegRQOffsetOperands(MCInst & Inst,unsigned N) const3152   void addMemRegRQOffsetOperands(MCInst &Inst, unsigned N) const {
3153     assert(N == 2 && "Invalid number of operands!");
3154     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3155     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3156   }
3157 
addMemUImm12OffsetOperands(MCInst & Inst,unsigned N) const3158   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
3159     assert(N == 2 && "Invalid number of operands!");
3160     // If this is an immediate, it's a label reference.
3161     if (isImm()) {
3162       addExpr(Inst, getImm());
3163       Inst.addOperand(MCOperand::createImm(0));
3164       return;
3165     }
3166 
3167     // Otherwise, it's a normal memory reg+offset.
3168     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3169     addExpr(Inst, Memory.OffsetImm);
3170   }
3171 
addMemImm12OffsetOperands(MCInst & Inst,unsigned N) const3172   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
3173     assert(N == 2 && "Invalid number of operands!");
3174     // If this is an immediate, it's a label reference.
3175     if (isImm()) {
3176       addExpr(Inst, getImm());
3177       Inst.addOperand(MCOperand::createImm(0));
3178       return;
3179     }
3180 
3181     // Otherwise, it's a normal memory reg+offset.
3182     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3183     addExpr(Inst, Memory.OffsetImm);
3184   }
3185 
addConstPoolAsmImmOperands(MCInst & Inst,unsigned N) const3186   void addConstPoolAsmImmOperands(MCInst &Inst, unsigned N) const {
3187     assert(N == 1 && "Invalid number of operands!");
3188     // This is container for the immediate that we will create the constant
3189     // pool from
3190     addExpr(Inst, getConstantPoolImm());
3191   }
3192 
addMemTBBOperands(MCInst & Inst,unsigned N) const3193   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
3194     assert(N == 2 && "Invalid number of operands!");
3195     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3196     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3197   }
3198 
addMemTBHOperands(MCInst & Inst,unsigned N) const3199   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
3200     assert(N == 2 && "Invalid number of operands!");
3201     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3202     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3203   }
3204 
addMemRegOffsetOperands(MCInst & Inst,unsigned N) const3205   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
3206     assert(N == 3 && "Invalid number of operands!");
3207     unsigned Val =
3208       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
3209                         Memory.ShiftImm, Memory.ShiftType);
3210     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3211     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3212     Inst.addOperand(MCOperand::createImm(Val));
3213   }
3214 
addT2MemRegOffsetOperands(MCInst & Inst,unsigned N) const3215   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
3216     assert(N == 3 && "Invalid number of operands!");
3217     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3218     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3219     Inst.addOperand(MCOperand::createImm(Memory.ShiftImm));
3220   }
3221 
addMemThumbRROperands(MCInst & Inst,unsigned N) const3222   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
3223     assert(N == 2 && "Invalid number of operands!");
3224     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3225     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3226   }
3227 
addMemThumbRIs4Operands(MCInst & Inst,unsigned N) const3228   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
3229     assert(N == 2 && "Invalid number of operands!");
3230     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3231     if (!Memory.OffsetImm)
3232       Inst.addOperand(MCOperand::createImm(0));
3233     else if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm))
3234       // The lower two bits are always zero and as such are not encoded.
3235       Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
3236     else
3237       Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
3238   }
3239 
addMemThumbRIs2Operands(MCInst & Inst,unsigned N) const3240   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
3241     assert(N == 2 && "Invalid number of operands!");
3242     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3243     if (!Memory.OffsetImm)
3244       Inst.addOperand(MCOperand::createImm(0));
3245     else if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm))
3246       Inst.addOperand(MCOperand::createImm(CE->getValue() / 2));
3247     else
3248       Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
3249   }
3250 
addMemThumbRIs1Operands(MCInst & Inst,unsigned N) const3251   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
3252     assert(N == 2 && "Invalid number of operands!");
3253     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3254     addExpr(Inst, Memory.OffsetImm);
3255   }
3256 
addMemThumbSPIOperands(MCInst & Inst,unsigned N) const3257   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
3258     assert(N == 2 && "Invalid number of operands!");
3259     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3260     if (!Memory.OffsetImm)
3261       Inst.addOperand(MCOperand::createImm(0));
3262     else if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm))
3263       // The lower two bits are always zero and as such are not encoded.
3264       Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
3265     else
3266       Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
3267   }
3268 
addPostIdxImm8Operands(MCInst & Inst,unsigned N) const3269   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
3270     assert(N == 1 && "Invalid number of operands!");
3271     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3272     assert(CE && "non-constant post-idx-imm8 operand!");
3273     int Imm = CE->getValue();
3274     bool isAdd = Imm >= 0;
3275     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
3276     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
3277     Inst.addOperand(MCOperand::createImm(Imm));
3278   }
3279 
addPostIdxImm8s4Operands(MCInst & Inst,unsigned N) const3280   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
3281     assert(N == 1 && "Invalid number of operands!");
3282     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3283     assert(CE && "non-constant post-idx-imm8s4 operand!");
3284     int Imm = CE->getValue();
3285     bool isAdd = Imm >= 0;
3286     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
3287     // Immediate is scaled by 4.
3288     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
3289     Inst.addOperand(MCOperand::createImm(Imm));
3290   }
3291 
addPostIdxRegOperands(MCInst & Inst,unsigned N) const3292   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
3293     assert(N == 2 && "Invalid number of operands!");
3294     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
3295     Inst.addOperand(MCOperand::createImm(PostIdxReg.isAdd));
3296   }
3297 
addPostIdxRegShiftedOperands(MCInst & Inst,unsigned N) const3298   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
3299     assert(N == 2 && "Invalid number of operands!");
3300     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
3301     // The sign, shift type, and shift amount are encoded in a single operand
3302     // using the AM2 encoding helpers.
3303     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
3304     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
3305                                      PostIdxReg.ShiftTy);
3306     Inst.addOperand(MCOperand::createImm(Imm));
3307   }
3308 
addPowerTwoOperands(MCInst & Inst,unsigned N) const3309   void addPowerTwoOperands(MCInst &Inst, unsigned N) const {
3310     assert(N == 1 && "Invalid number of operands!");
3311     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3312     Inst.addOperand(MCOperand::createImm(CE->getValue()));
3313   }
3314 
addMSRMaskOperands(MCInst & Inst,unsigned N) const3315   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
3316     assert(N == 1 && "Invalid number of operands!");
3317     Inst.addOperand(MCOperand::createImm(unsigned(getMSRMask())));
3318   }
3319 
addBankedRegOperands(MCInst & Inst,unsigned N) const3320   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
3321     assert(N == 1 && "Invalid number of operands!");
3322     Inst.addOperand(MCOperand::createImm(unsigned(getBankedReg())));
3323   }
3324 
addProcIFlagsOperands(MCInst & Inst,unsigned N) const3325   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
3326     assert(N == 1 && "Invalid number of operands!");
3327     Inst.addOperand(MCOperand::createImm(unsigned(getProcIFlags())));
3328   }
3329 
addVecListOperands(MCInst & Inst,unsigned N) const3330   void addVecListOperands(MCInst &Inst, unsigned N) const {
3331     assert(N == 1 && "Invalid number of operands!");
3332     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
3333   }
3334 
addMVEVecListOperands(MCInst & Inst,unsigned N) const3335   void addMVEVecListOperands(MCInst &Inst, unsigned N) const {
3336     assert(N == 1 && "Invalid number of operands!");
3337 
3338     // When we come here, the VectorList field will identify a range
3339     // of q-registers by its base register and length, and it will
3340     // have already been error-checked to be the expected length of
3341     // range and contain only q-regs in the range q0-q7. So we can
3342     // count on the base register being in the range q0-q6 (for 2
3343     // regs) or q0-q4 (for 4)
3344     //
3345     // The MVE instructions taking a register range of this kind will
3346     // need an operand in the QQPR or QQQQPR class, representing the
3347     // entire range as a unit. So we must translate into that class,
3348     // by finding the index of the base register in the MQPR reg
3349     // class, and returning the super-register at the corresponding
3350     // index in the target class.
3351 
3352     const MCRegisterClass *RC_in = &ARMMCRegisterClasses[ARM::MQPRRegClassID];
3353     const MCRegisterClass *RC_out = (VectorList.Count == 2) ?
3354       &ARMMCRegisterClasses[ARM::QQPRRegClassID] :
3355       &ARMMCRegisterClasses[ARM::QQQQPRRegClassID];
3356 
3357     unsigned I, E = RC_out->getNumRegs();
3358     for (I = 0; I < E; I++)
3359       if (RC_in->getRegister(I) == VectorList.RegNum)
3360         break;
3361     assert(I < E && "Invalid vector list start register!");
3362 
3363     Inst.addOperand(MCOperand::createReg(RC_out->getRegister(I)));
3364   }
3365 
addVecListIndexedOperands(MCInst & Inst,unsigned N) const3366   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
3367     assert(N == 2 && "Invalid number of operands!");
3368     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
3369     Inst.addOperand(MCOperand::createImm(VectorList.LaneIndex));
3370   }
3371 
addVectorIndex8Operands(MCInst & Inst,unsigned N) const3372   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
3373     assert(N == 1 && "Invalid number of operands!");
3374     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3375   }
3376 
addVectorIndex16Operands(MCInst & Inst,unsigned N) const3377   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
3378     assert(N == 1 && "Invalid number of operands!");
3379     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3380   }
3381 
addVectorIndex32Operands(MCInst & Inst,unsigned N) const3382   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
3383     assert(N == 1 && "Invalid number of operands!");
3384     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3385   }
3386 
addVectorIndex64Operands(MCInst & Inst,unsigned N) const3387   void addVectorIndex64Operands(MCInst &Inst, unsigned N) const {
3388     assert(N == 1 && "Invalid number of operands!");
3389     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3390   }
3391 
addMVEVectorIndexOperands(MCInst & Inst,unsigned N) const3392   void addMVEVectorIndexOperands(MCInst &Inst, unsigned N) const {
3393     assert(N == 1 && "Invalid number of operands!");
3394     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3395   }
3396 
addMVEPairVectorIndexOperands(MCInst & Inst,unsigned N) const3397   void addMVEPairVectorIndexOperands(MCInst &Inst, unsigned N) const {
3398     assert(N == 1 && "Invalid number of operands!");
3399     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3400   }
3401 
addNEONi8splatOperands(MCInst & Inst,unsigned N) const3402   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
3403     assert(N == 1 && "Invalid number of operands!");
3404     // The immediate encodes the type of constant as well as the value.
3405     // Mask in that this is an i8 splat.
3406     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3407     Inst.addOperand(MCOperand::createImm(CE->getValue() | 0xe00));
3408   }
3409 
addNEONi16splatOperands(MCInst & Inst,unsigned N) const3410   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
3411     assert(N == 1 && "Invalid number of operands!");
3412     // The immediate encodes the type of constant as well as the value.
3413     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3414     unsigned Value = CE->getValue();
3415     Value = ARM_AM::encodeNEONi16splat(Value);
3416     Inst.addOperand(MCOperand::createImm(Value));
3417   }
3418 
addNEONi16splatNotOperands(MCInst & Inst,unsigned N) const3419   void addNEONi16splatNotOperands(MCInst &Inst, unsigned N) const {
3420     assert(N == 1 && "Invalid number of operands!");
3421     // The immediate encodes the type of constant as well as the value.
3422     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3423     unsigned Value = CE->getValue();
3424     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
3425     Inst.addOperand(MCOperand::createImm(Value));
3426   }
3427 
addNEONi32splatOperands(MCInst & Inst,unsigned N) const3428   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
3429     assert(N == 1 && "Invalid number of operands!");
3430     // The immediate encodes the type of constant as well as the value.
3431     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3432     unsigned Value = CE->getValue();
3433     Value = ARM_AM::encodeNEONi32splat(Value);
3434     Inst.addOperand(MCOperand::createImm(Value));
3435   }
3436 
addNEONi32splatNotOperands(MCInst & Inst,unsigned N) const3437   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
3438     assert(N == 1 && "Invalid number of operands!");
3439     // The immediate encodes the type of constant as well as the value.
3440     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3441     unsigned Value = CE->getValue();
3442     Value = ARM_AM::encodeNEONi32splat(~Value);
3443     Inst.addOperand(MCOperand::createImm(Value));
3444   }
3445 
addNEONi8ReplicateOperands(MCInst & Inst,bool Inv) const3446   void addNEONi8ReplicateOperands(MCInst &Inst, bool Inv) const {
3447     // The immediate encodes the type of constant as well as the value.
3448     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3449     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
3450             Inst.getOpcode() == ARM::VMOVv16i8) &&
3451           "All instructions that wants to replicate non-zero byte "
3452           "always must be replaced with VMOVv8i8 or VMOVv16i8.");
3453     unsigned Value = CE->getValue();
3454     if (Inv)
3455       Value = ~Value;
3456     unsigned B = Value & 0xff;
3457     B |= 0xe00; // cmode = 0b1110
3458     Inst.addOperand(MCOperand::createImm(B));
3459   }
3460 
addNEONinvi8ReplicateOperands(MCInst & Inst,unsigned N) const3461   void addNEONinvi8ReplicateOperands(MCInst &Inst, unsigned N) const {
3462     assert(N == 1 && "Invalid number of operands!");
3463     addNEONi8ReplicateOperands(Inst, true);
3464   }
3465 
encodeNeonVMOVImmediate(unsigned Value)3466   static unsigned encodeNeonVMOVImmediate(unsigned Value) {
3467     if (Value >= 256 && Value <= 0xffff)
3468       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
3469     else if (Value > 0xffff && Value <= 0xffffff)
3470       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
3471     else if (Value > 0xffffff)
3472       Value = (Value >> 24) | 0x600;
3473     return Value;
3474   }
3475 
addNEONi32vmovOperands(MCInst & Inst,unsigned N) const3476   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
3477     assert(N == 1 && "Invalid number of operands!");
3478     // The immediate encodes the type of constant as well as the value.
3479     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3480     unsigned Value = encodeNeonVMOVImmediate(CE->getValue());
3481     Inst.addOperand(MCOperand::createImm(Value));
3482   }
3483 
addNEONvmovi8ReplicateOperands(MCInst & Inst,unsigned N) const3484   void addNEONvmovi8ReplicateOperands(MCInst &Inst, unsigned N) const {
3485     assert(N == 1 && "Invalid number of operands!");
3486     addNEONi8ReplicateOperands(Inst, false);
3487   }
3488 
addNEONvmovi16ReplicateOperands(MCInst & Inst,unsigned N) const3489   void addNEONvmovi16ReplicateOperands(MCInst &Inst, unsigned N) const {
3490     assert(N == 1 && "Invalid number of operands!");
3491     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3492     assert((Inst.getOpcode() == ARM::VMOVv4i16 ||
3493             Inst.getOpcode() == ARM::VMOVv8i16 ||
3494             Inst.getOpcode() == ARM::VMVNv4i16 ||
3495             Inst.getOpcode() == ARM::VMVNv8i16) &&
3496           "All instructions that want to replicate non-zero half-word "
3497           "always must be replaced with V{MOV,MVN}v{4,8}i16.");
3498     uint64_t Value = CE->getValue();
3499     unsigned Elem = Value & 0xffff;
3500     if (Elem >= 256)
3501       Elem = (Elem >> 8) | 0x200;
3502     Inst.addOperand(MCOperand::createImm(Elem));
3503   }
3504 
addNEONi32vmovNegOperands(MCInst & Inst,unsigned N) const3505   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
3506     assert(N == 1 && "Invalid number of operands!");
3507     // The immediate encodes the type of constant as well as the value.
3508     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3509     unsigned Value = encodeNeonVMOVImmediate(~CE->getValue());
3510     Inst.addOperand(MCOperand::createImm(Value));
3511   }
3512 
addNEONvmovi32ReplicateOperands(MCInst & Inst,unsigned N) const3513   void addNEONvmovi32ReplicateOperands(MCInst &Inst, unsigned N) const {
3514     assert(N == 1 && "Invalid number of operands!");
3515     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3516     assert((Inst.getOpcode() == ARM::VMOVv2i32 ||
3517             Inst.getOpcode() == ARM::VMOVv4i32 ||
3518             Inst.getOpcode() == ARM::VMVNv2i32 ||
3519             Inst.getOpcode() == ARM::VMVNv4i32) &&
3520           "All instructions that want to replicate non-zero word "
3521           "always must be replaced with V{MOV,MVN}v{2,4}i32.");
3522     uint64_t Value = CE->getValue();
3523     unsigned Elem = encodeNeonVMOVImmediate(Value & 0xffffffff);
3524     Inst.addOperand(MCOperand::createImm(Elem));
3525   }
3526 
addNEONi64splatOperands(MCInst & Inst,unsigned N) const3527   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
3528     assert(N == 1 && "Invalid number of operands!");
3529     // The immediate encodes the type of constant as well as the value.
3530     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3531     uint64_t Value = CE->getValue();
3532     unsigned Imm = 0;
3533     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
3534       Imm |= (Value & 1) << i;
3535     }
3536     Inst.addOperand(MCOperand::createImm(Imm | 0x1e00));
3537   }
3538 
addComplexRotationEvenOperands(MCInst & Inst,unsigned N) const3539   void addComplexRotationEvenOperands(MCInst &Inst, unsigned N) const {
3540     assert(N == 1 && "Invalid number of operands!");
3541     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3542     Inst.addOperand(MCOperand::createImm(CE->getValue() / 90));
3543   }
3544 
addComplexRotationOddOperands(MCInst & Inst,unsigned N) const3545   void addComplexRotationOddOperands(MCInst &Inst, unsigned N) const {
3546     assert(N == 1 && "Invalid number of operands!");
3547     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3548     Inst.addOperand(MCOperand::createImm((CE->getValue() - 90) / 180));
3549   }
3550 
addMveSaturateOperands(MCInst & Inst,unsigned N) const3551   void addMveSaturateOperands(MCInst &Inst, unsigned N) const {
3552     assert(N == 1 && "Invalid number of operands!");
3553     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3554     unsigned Imm = CE->getValue();
3555     assert((Imm == 48 || Imm == 64) && "Invalid saturate operand");
3556     Inst.addOperand(MCOperand::createImm(Imm == 48 ? 1 : 0));
3557   }
3558 
3559   void print(raw_ostream &OS) const override;
3560 
CreateITMask(unsigned Mask,SMLoc S)3561   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
3562     auto Op = std::make_unique<ARMOperand>(k_ITCondMask);
3563     Op->ITMask.Mask = Mask;
3564     Op->StartLoc = S;
3565     Op->EndLoc = S;
3566     return Op;
3567   }
3568 
CreateCondCode(ARMCC::CondCodes CC,SMLoc S)3569   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
3570                                                     SMLoc S) {
3571     auto Op = std::make_unique<ARMOperand>(k_CondCode);
3572     Op->CC.Val = CC;
3573     Op->StartLoc = S;
3574     Op->EndLoc = S;
3575     return Op;
3576   }
3577 
CreateVPTPred(ARMVCC::VPTCodes CC,SMLoc S)3578   static std::unique_ptr<ARMOperand> CreateVPTPred(ARMVCC::VPTCodes CC,
3579                                                    SMLoc S) {
3580     auto Op = std::make_unique<ARMOperand>(k_VPTPred);
3581     Op->VCC.Val = CC;
3582     Op->StartLoc = S;
3583     Op->EndLoc = S;
3584     return Op;
3585   }
3586 
CreateCoprocNum(unsigned CopVal,SMLoc S)3587   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
3588     auto Op = std::make_unique<ARMOperand>(k_CoprocNum);
3589     Op->Cop.Val = CopVal;
3590     Op->StartLoc = S;
3591     Op->EndLoc = S;
3592     return Op;
3593   }
3594 
CreateCoprocReg(unsigned CopVal,SMLoc S)3595   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
3596     auto Op = std::make_unique<ARMOperand>(k_CoprocReg);
3597     Op->Cop.Val = CopVal;
3598     Op->StartLoc = S;
3599     Op->EndLoc = S;
3600     return Op;
3601   }
3602 
CreateCoprocOption(unsigned Val,SMLoc S,SMLoc E)3603   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
3604                                                         SMLoc E) {
3605     auto Op = std::make_unique<ARMOperand>(k_CoprocOption);
3606     Op->Cop.Val = Val;
3607     Op->StartLoc = S;
3608     Op->EndLoc = E;
3609     return Op;
3610   }
3611 
CreateCCOut(unsigned RegNum,SMLoc S)3612   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
3613     auto Op = std::make_unique<ARMOperand>(k_CCOut);
3614     Op->Reg.RegNum = RegNum;
3615     Op->StartLoc = S;
3616     Op->EndLoc = S;
3617     return Op;
3618   }
3619 
CreateToken(StringRef Str,SMLoc S)3620   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
3621     auto Op = std::make_unique<ARMOperand>(k_Token);
3622     Op->Tok.Data = Str.data();
3623     Op->Tok.Length = Str.size();
3624     Op->StartLoc = S;
3625     Op->EndLoc = S;
3626     return Op;
3627   }
3628 
CreateReg(unsigned RegNum,SMLoc S,SMLoc E)3629   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
3630                                                SMLoc E) {
3631     auto Op = std::make_unique<ARMOperand>(k_Register);
3632     Op->Reg.RegNum = RegNum;
3633     Op->StartLoc = S;
3634     Op->EndLoc = E;
3635     return Op;
3636   }
3637 
3638   static std::unique_ptr<ARMOperand>
CreateShiftedRegister(ARM_AM::ShiftOpc ShTy,unsigned SrcReg,unsigned ShiftReg,unsigned ShiftImm,SMLoc S,SMLoc E)3639   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
3640                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
3641                         SMLoc E) {
3642     auto Op = std::make_unique<ARMOperand>(k_ShiftedRegister);
3643     Op->RegShiftedReg.ShiftTy = ShTy;
3644     Op->RegShiftedReg.SrcReg = SrcReg;
3645     Op->RegShiftedReg.ShiftReg = ShiftReg;
3646     Op->RegShiftedReg.ShiftImm = ShiftImm;
3647     Op->StartLoc = S;
3648     Op->EndLoc = E;
3649     return Op;
3650   }
3651 
3652   static std::unique_ptr<ARMOperand>
CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy,unsigned SrcReg,unsigned ShiftImm,SMLoc S,SMLoc E)3653   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
3654                          unsigned ShiftImm, SMLoc S, SMLoc E) {
3655     auto Op = std::make_unique<ARMOperand>(k_ShiftedImmediate);
3656     Op->RegShiftedImm.ShiftTy = ShTy;
3657     Op->RegShiftedImm.SrcReg = SrcReg;
3658     Op->RegShiftedImm.ShiftImm = ShiftImm;
3659     Op->StartLoc = S;
3660     Op->EndLoc = E;
3661     return Op;
3662   }
3663 
CreateShifterImm(bool isASR,unsigned Imm,SMLoc S,SMLoc E)3664   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
3665                                                       SMLoc S, SMLoc E) {
3666     auto Op = std::make_unique<ARMOperand>(k_ShifterImmediate);
3667     Op->ShifterImm.isASR = isASR;
3668     Op->ShifterImm.Imm = Imm;
3669     Op->StartLoc = S;
3670     Op->EndLoc = E;
3671     return Op;
3672   }
3673 
CreateRotImm(unsigned Imm,SMLoc S,SMLoc E)3674   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
3675                                                   SMLoc E) {
3676     auto Op = std::make_unique<ARMOperand>(k_RotateImmediate);
3677     Op->RotImm.Imm = Imm;
3678     Op->StartLoc = S;
3679     Op->EndLoc = E;
3680     return Op;
3681   }
3682 
CreateModImm(unsigned Bits,unsigned Rot,SMLoc S,SMLoc E)3683   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
3684                                                   SMLoc S, SMLoc E) {
3685     auto Op = std::make_unique<ARMOperand>(k_ModifiedImmediate);
3686     Op->ModImm.Bits = Bits;
3687     Op->ModImm.Rot = Rot;
3688     Op->StartLoc = S;
3689     Op->EndLoc = E;
3690     return Op;
3691   }
3692 
3693   static std::unique_ptr<ARMOperand>
CreateConstantPoolImm(const MCExpr * Val,SMLoc S,SMLoc E)3694   CreateConstantPoolImm(const MCExpr *Val, SMLoc S, SMLoc E) {
3695     auto Op = std::make_unique<ARMOperand>(k_ConstantPoolImmediate);
3696     Op->Imm.Val = Val;
3697     Op->StartLoc = S;
3698     Op->EndLoc = E;
3699     return Op;
3700   }
3701 
3702   static std::unique_ptr<ARMOperand>
CreateBitfield(unsigned LSB,unsigned Width,SMLoc S,SMLoc E)3703   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
3704     auto Op = std::make_unique<ARMOperand>(k_BitfieldDescriptor);
3705     Op->Bitfield.LSB = LSB;
3706     Op->Bitfield.Width = Width;
3707     Op->StartLoc = S;
3708     Op->EndLoc = E;
3709     return Op;
3710   }
3711 
3712   static std::unique_ptr<ARMOperand>
CreateRegList(SmallVectorImpl<std::pair<unsigned,unsigned>> & Regs,SMLoc StartLoc,SMLoc EndLoc)3713   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
3714                 SMLoc StartLoc, SMLoc EndLoc) {
3715     assert(Regs.size() > 0 && "RegList contains no registers?");
3716     KindTy Kind = k_RegisterList;
3717 
3718     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
3719             Regs.front().second)) {
3720       if (Regs.back().second == ARM::VPR)
3721         Kind = k_FPDRegisterListWithVPR;
3722       else
3723         Kind = k_DPRRegisterList;
3724     } else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(
3725                    Regs.front().second)) {
3726       if (Regs.back().second == ARM::VPR)
3727         Kind = k_FPSRegisterListWithVPR;
3728       else
3729         Kind = k_SPRRegisterList;
3730     }
3731 
3732     if (Kind == k_RegisterList && Regs.back().second == ARM::APSR)
3733       Kind = k_RegisterListWithAPSR;
3734 
3735     assert(llvm::is_sorted(Regs) && "Register list must be sorted by encoding");
3736 
3737     auto Op = std::make_unique<ARMOperand>(Kind);
3738     for (const auto &P : Regs)
3739       Op->Registers.push_back(P.second);
3740 
3741     Op->StartLoc = StartLoc;
3742     Op->EndLoc = EndLoc;
3743     return Op;
3744   }
3745 
CreateVectorList(unsigned RegNum,unsigned Count,bool isDoubleSpaced,SMLoc S,SMLoc E)3746   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
3747                                                       unsigned Count,
3748                                                       bool isDoubleSpaced,
3749                                                       SMLoc S, SMLoc E) {
3750     auto Op = std::make_unique<ARMOperand>(k_VectorList);
3751     Op->VectorList.RegNum = RegNum;
3752     Op->VectorList.Count = Count;
3753     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3754     Op->StartLoc = S;
3755     Op->EndLoc = E;
3756     return Op;
3757   }
3758 
3759   static std::unique_ptr<ARMOperand>
CreateVectorListAllLanes(unsigned RegNum,unsigned Count,bool isDoubleSpaced,SMLoc S,SMLoc E)3760   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
3761                            SMLoc S, SMLoc E) {
3762     auto Op = std::make_unique<ARMOperand>(k_VectorListAllLanes);
3763     Op->VectorList.RegNum = RegNum;
3764     Op->VectorList.Count = Count;
3765     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3766     Op->StartLoc = S;
3767     Op->EndLoc = E;
3768     return Op;
3769   }
3770 
3771   static std::unique_ptr<ARMOperand>
CreateVectorListIndexed(unsigned RegNum,unsigned Count,unsigned Index,bool isDoubleSpaced,SMLoc S,SMLoc E)3772   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
3773                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
3774     auto Op = std::make_unique<ARMOperand>(k_VectorListIndexed);
3775     Op->VectorList.RegNum = RegNum;
3776     Op->VectorList.Count = Count;
3777     Op->VectorList.LaneIndex = Index;
3778     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3779     Op->StartLoc = S;
3780     Op->EndLoc = E;
3781     return Op;
3782   }
3783 
3784   static std::unique_ptr<ARMOperand>
CreateVectorIndex(unsigned Idx,SMLoc S,SMLoc E,MCContext & Ctx)3785   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
3786     auto Op = std::make_unique<ARMOperand>(k_VectorIndex);
3787     Op->VectorIndex.Val = Idx;
3788     Op->StartLoc = S;
3789     Op->EndLoc = E;
3790     return Op;
3791   }
3792 
CreateImm(const MCExpr * Val,SMLoc S,SMLoc E)3793   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
3794                                                SMLoc E) {
3795     auto Op = std::make_unique<ARMOperand>(k_Immediate);
3796     Op->Imm.Val = Val;
3797     Op->StartLoc = S;
3798     Op->EndLoc = E;
3799     return Op;
3800   }
3801 
3802   static std::unique_ptr<ARMOperand>
CreateMem(unsigned BaseRegNum,const MCExpr * OffsetImm,unsigned OffsetRegNum,ARM_AM::ShiftOpc ShiftType,unsigned ShiftImm,unsigned Alignment,bool isNegative,SMLoc S,SMLoc E,SMLoc AlignmentLoc=SMLoc ())3803   CreateMem(unsigned BaseRegNum, const MCExpr *OffsetImm, unsigned OffsetRegNum,
3804             ARM_AM::ShiftOpc ShiftType, unsigned ShiftImm, unsigned Alignment,
3805             bool isNegative, SMLoc S, SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
3806     auto Op = std::make_unique<ARMOperand>(k_Memory);
3807     Op->Memory.BaseRegNum = BaseRegNum;
3808     Op->Memory.OffsetImm = OffsetImm;
3809     Op->Memory.OffsetRegNum = OffsetRegNum;
3810     Op->Memory.ShiftType = ShiftType;
3811     Op->Memory.ShiftImm = ShiftImm;
3812     Op->Memory.Alignment = Alignment;
3813     Op->Memory.isNegative = isNegative;
3814     Op->StartLoc = S;
3815     Op->EndLoc = E;
3816     Op->AlignmentLoc = AlignmentLoc;
3817     return Op;
3818   }
3819 
3820   static std::unique_ptr<ARMOperand>
CreatePostIdxReg(unsigned RegNum,bool isAdd,ARM_AM::ShiftOpc ShiftTy,unsigned ShiftImm,SMLoc S,SMLoc E)3821   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
3822                    unsigned ShiftImm, SMLoc S, SMLoc E) {
3823     auto Op = std::make_unique<ARMOperand>(k_PostIndexRegister);
3824     Op->PostIdxReg.RegNum = RegNum;
3825     Op->PostIdxReg.isAdd = isAdd;
3826     Op->PostIdxReg.ShiftTy = ShiftTy;
3827     Op->PostIdxReg.ShiftImm = ShiftImm;
3828     Op->StartLoc = S;
3829     Op->EndLoc = E;
3830     return Op;
3831   }
3832 
CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,SMLoc S)3833   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
3834                                                          SMLoc S) {
3835     auto Op = std::make_unique<ARMOperand>(k_MemBarrierOpt);
3836     Op->MBOpt.Val = Opt;
3837     Op->StartLoc = S;
3838     Op->EndLoc = S;
3839     return Op;
3840   }
3841 
3842   static std::unique_ptr<ARMOperand>
CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt,SMLoc S)3843   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
3844     auto Op = std::make_unique<ARMOperand>(k_InstSyncBarrierOpt);
3845     Op->ISBOpt.Val = Opt;
3846     Op->StartLoc = S;
3847     Op->EndLoc = S;
3848     return Op;
3849   }
3850 
3851   static std::unique_ptr<ARMOperand>
CreateTraceSyncBarrierOpt(ARM_TSB::TraceSyncBOpt Opt,SMLoc S)3852   CreateTraceSyncBarrierOpt(ARM_TSB::TraceSyncBOpt Opt, SMLoc S) {
3853     auto Op = std::make_unique<ARMOperand>(k_TraceSyncBarrierOpt);
3854     Op->TSBOpt.Val = Opt;
3855     Op->StartLoc = S;
3856     Op->EndLoc = S;
3857     return Op;
3858   }
3859 
CreateProcIFlags(ARM_PROC::IFlags IFlags,SMLoc S)3860   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
3861                                                       SMLoc S) {
3862     auto Op = std::make_unique<ARMOperand>(k_ProcIFlags);
3863     Op->IFlags.Val = IFlags;
3864     Op->StartLoc = S;
3865     Op->EndLoc = S;
3866     return Op;
3867   }
3868 
CreateMSRMask(unsigned MMask,SMLoc S)3869   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
3870     auto Op = std::make_unique<ARMOperand>(k_MSRMask);
3871     Op->MMask.Val = MMask;
3872     Op->StartLoc = S;
3873     Op->EndLoc = S;
3874     return Op;
3875   }
3876 
CreateBankedReg(unsigned Reg,SMLoc S)3877   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
3878     auto Op = std::make_unique<ARMOperand>(k_BankedReg);
3879     Op->BankedReg.Val = Reg;
3880     Op->StartLoc = S;
3881     Op->EndLoc = S;
3882     return Op;
3883   }
3884 };
3885 
3886 } // end anonymous namespace.
3887 
print(raw_ostream & OS) const3888 void ARMOperand::print(raw_ostream &OS) const {
3889   auto RegName = [](unsigned Reg) {
3890     if (Reg)
3891       return ARMInstPrinter::getRegisterName(Reg);
3892     else
3893       return "noreg";
3894   };
3895 
3896   switch (Kind) {
3897   case k_CondCode:
3898     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
3899     break;
3900   case k_VPTPred:
3901     OS << "<ARMVCC::" << ARMVPTPredToString(getVPTPred()) << ">";
3902     break;
3903   case k_CCOut:
3904     OS << "<ccout " << RegName(getReg()) << ">";
3905     break;
3906   case k_ITCondMask: {
3907     static const char *const MaskStr[] = {
3908       "(invalid)", "(tttt)", "(ttt)", "(ttte)",
3909       "(tt)",      "(ttet)", "(tte)", "(ttee)",
3910       "(t)",       "(tett)", "(tet)", "(tete)",
3911       "(te)",      "(teet)", "(tee)", "(teee)",
3912     };
3913     assert((ITMask.Mask & 0xf) == ITMask.Mask);
3914     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
3915     break;
3916   }
3917   case k_CoprocNum:
3918     OS << "<coprocessor number: " << getCoproc() << ">";
3919     break;
3920   case k_CoprocReg:
3921     OS << "<coprocessor register: " << getCoproc() << ">";
3922     break;
3923   case k_CoprocOption:
3924     OS << "<coprocessor option: " << CoprocOption.Val << ">";
3925     break;
3926   case k_MSRMask:
3927     OS << "<mask: " << getMSRMask() << ">";
3928     break;
3929   case k_BankedReg:
3930     OS << "<banked reg: " << getBankedReg() << ">";
3931     break;
3932   case k_Immediate:
3933     OS << *getImm();
3934     break;
3935   case k_MemBarrierOpt:
3936     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
3937     break;
3938   case k_InstSyncBarrierOpt:
3939     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
3940     break;
3941   case k_TraceSyncBarrierOpt:
3942     OS << "<ARM_TSB::" << TraceSyncBOptToString(getTraceSyncBarrierOpt()) << ">";
3943     break;
3944   case k_Memory:
3945     OS << "<memory";
3946     if (Memory.BaseRegNum)
3947       OS << " base:" << RegName(Memory.BaseRegNum);
3948     if (Memory.OffsetImm)
3949       OS << " offset-imm:" << *Memory.OffsetImm;
3950     if (Memory.OffsetRegNum)
3951       OS << " offset-reg:" << (Memory.isNegative ? "-" : "")
3952          << RegName(Memory.OffsetRegNum);
3953     if (Memory.ShiftType != ARM_AM::no_shift) {
3954       OS << " shift-type:" << ARM_AM::getShiftOpcStr(Memory.ShiftType);
3955       OS << " shift-imm:" << Memory.ShiftImm;
3956     }
3957     if (Memory.Alignment)
3958       OS << " alignment:" << Memory.Alignment;
3959     OS << ">";
3960     break;
3961   case k_PostIndexRegister:
3962     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
3963        << RegName(PostIdxReg.RegNum);
3964     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
3965       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
3966          << PostIdxReg.ShiftImm;
3967     OS << ">";
3968     break;
3969   case k_ProcIFlags: {
3970     OS << "<ARM_PROC::";
3971     unsigned IFlags = getProcIFlags();
3972     for (int i=2; i >= 0; --i)
3973       if (IFlags & (1 << i))
3974         OS << ARM_PROC::IFlagsToString(1 << i);
3975     OS << ">";
3976     break;
3977   }
3978   case k_Register:
3979     OS << "<register " << RegName(getReg()) << ">";
3980     break;
3981   case k_ShifterImmediate:
3982     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
3983        << " #" << ShifterImm.Imm << ">";
3984     break;
3985   case k_ShiftedRegister:
3986     OS << "<so_reg_reg " << RegName(RegShiftedReg.SrcReg) << " "
3987        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy) << " "
3988        << RegName(RegShiftedReg.ShiftReg) << ">";
3989     break;
3990   case k_ShiftedImmediate:
3991     OS << "<so_reg_imm " << RegName(RegShiftedImm.SrcReg) << " "
3992        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy) << " #"
3993        << RegShiftedImm.ShiftImm << ">";
3994     break;
3995   case k_RotateImmediate:
3996     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
3997     break;
3998   case k_ModifiedImmediate:
3999     OS << "<mod_imm #" << ModImm.Bits << ", #"
4000        <<  ModImm.Rot << ")>";
4001     break;
4002   case k_ConstantPoolImmediate:
4003     OS << "<constant_pool_imm #" << *getConstantPoolImm();
4004     break;
4005   case k_BitfieldDescriptor:
4006     OS << "<bitfield " << "lsb: " << Bitfield.LSB
4007        << ", width: " << Bitfield.Width << ">";
4008     break;
4009   case k_RegisterList:
4010   case k_RegisterListWithAPSR:
4011   case k_DPRRegisterList:
4012   case k_SPRRegisterList:
4013   case k_FPSRegisterListWithVPR:
4014   case k_FPDRegisterListWithVPR: {
4015     OS << "<register_list ";
4016 
4017     const SmallVectorImpl<unsigned> &RegList = getRegList();
4018     for (SmallVectorImpl<unsigned>::const_iterator
4019            I = RegList.begin(), E = RegList.end(); I != E; ) {
4020       OS << RegName(*I);
4021       if (++I < E) OS << ", ";
4022     }
4023 
4024     OS << ">";
4025     break;
4026   }
4027   case k_VectorList:
4028     OS << "<vector_list " << VectorList.Count << " * "
4029        << RegName(VectorList.RegNum) << ">";
4030     break;
4031   case k_VectorListAllLanes:
4032     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
4033        << RegName(VectorList.RegNum) << ">";
4034     break;
4035   case k_VectorListIndexed:
4036     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
4037        << VectorList.Count << " * " << RegName(VectorList.RegNum) << ">";
4038     break;
4039   case k_Token:
4040     OS << "'" << getToken() << "'";
4041     break;
4042   case k_VectorIndex:
4043     OS << "<vectorindex " << getVectorIndex() << ">";
4044     break;
4045   }
4046 }
4047 
4048 /// @name Auto-generated Match Functions
4049 /// {
4050 
4051 static unsigned MatchRegisterName(StringRef Name);
4052 
4053 /// }
4054 
ParseRegister(unsigned & RegNo,SMLoc & StartLoc,SMLoc & EndLoc)4055 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
4056                                  SMLoc &StartLoc, SMLoc &EndLoc) {
4057   const AsmToken &Tok = getParser().getTok();
4058   StartLoc = Tok.getLoc();
4059   EndLoc = Tok.getEndLoc();
4060   RegNo = tryParseRegister();
4061 
4062   return (RegNo == (unsigned)-1);
4063 }
4064 
tryParseRegister(unsigned & RegNo,SMLoc & StartLoc,SMLoc & EndLoc)4065 OperandMatchResultTy ARMAsmParser::tryParseRegister(unsigned &RegNo,
4066                                                     SMLoc &StartLoc,
4067                                                     SMLoc &EndLoc) {
4068   if (ParseRegister(RegNo, StartLoc, EndLoc))
4069     return MatchOperand_NoMatch;
4070   return MatchOperand_Success;
4071 }
4072 
4073 /// Try to parse a register name.  The token must be an Identifier when called,
4074 /// and if it is a register name the token is eaten and the register number is
4075 /// returned.  Otherwise return -1.
tryParseRegister()4076 int ARMAsmParser::tryParseRegister() {
4077   MCAsmParser &Parser = getParser();
4078   const AsmToken &Tok = Parser.getTok();
4079   if (Tok.isNot(AsmToken::Identifier)) return -1;
4080 
4081   std::string lowerCase = Tok.getString().lower();
4082   unsigned RegNum = MatchRegisterName(lowerCase);
4083   if (!RegNum) {
4084     RegNum = StringSwitch<unsigned>(lowerCase)
4085       .Case("r13", ARM::SP)
4086       .Case("r14", ARM::LR)
4087       .Case("r15", ARM::PC)
4088       .Case("ip", ARM::R12)
4089       // Additional register name aliases for 'gas' compatibility.
4090       .Case("a1", ARM::R0)
4091       .Case("a2", ARM::R1)
4092       .Case("a3", ARM::R2)
4093       .Case("a4", ARM::R3)
4094       .Case("v1", ARM::R4)
4095       .Case("v2", ARM::R5)
4096       .Case("v3", ARM::R6)
4097       .Case("v4", ARM::R7)
4098       .Case("v5", ARM::R8)
4099       .Case("v6", ARM::R9)
4100       .Case("v7", ARM::R10)
4101       .Case("v8", ARM::R11)
4102       .Case("sb", ARM::R9)
4103       .Case("sl", ARM::R10)
4104       .Case("fp", ARM::R11)
4105       .Default(0);
4106   }
4107   if (!RegNum) {
4108     // Check for aliases registered via .req. Canonicalize to lower case.
4109     // That's more consistent since register names are case insensitive, and
4110     // it's how the original entry was passed in from MC/MCParser/AsmParser.
4111     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
4112     // If no match, return failure.
4113     if (Entry == RegisterReqs.end())
4114       return -1;
4115     Parser.Lex(); // Eat identifier token.
4116     return Entry->getValue();
4117   }
4118 
4119   // Some FPUs only have 16 D registers, so D16-D31 are invalid
4120   if (!hasD32() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
4121     return -1;
4122 
4123   Parser.Lex(); // Eat identifier token.
4124 
4125   return RegNum;
4126 }
4127 
4128 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
4129 // If a recoverable error occurs, return 1. If an irrecoverable error
4130 // occurs, return -1. An irrecoverable error is one where tokens have been
4131 // consumed in the process of trying to parse the shifter (i.e., when it is
4132 // indeed a shifter operand, but malformed).
tryParseShiftRegister(OperandVector & Operands)4133 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
4134   MCAsmParser &Parser = getParser();
4135   SMLoc S = Parser.getTok().getLoc();
4136   const AsmToken &Tok = Parser.getTok();
4137   if (Tok.isNot(AsmToken::Identifier))
4138     return -1;
4139 
4140   std::string lowerCase = Tok.getString().lower();
4141   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
4142       .Case("asl", ARM_AM::lsl)
4143       .Case("lsl", ARM_AM::lsl)
4144       .Case("lsr", ARM_AM::lsr)
4145       .Case("asr", ARM_AM::asr)
4146       .Case("ror", ARM_AM::ror)
4147       .Case("rrx", ARM_AM::rrx)
4148       .Default(ARM_AM::no_shift);
4149 
4150   if (ShiftTy == ARM_AM::no_shift)
4151     return 1;
4152 
4153   Parser.Lex(); // Eat the operator.
4154 
4155   // The source register for the shift has already been added to the
4156   // operand list, so we need to pop it off and combine it into the shifted
4157   // register operand instead.
4158   std::unique_ptr<ARMOperand> PrevOp(
4159       (ARMOperand *)Operands.pop_back_val().release());
4160   if (!PrevOp->isReg())
4161     return Error(PrevOp->getStartLoc(), "shift must be of a register");
4162   int SrcReg = PrevOp->getReg();
4163 
4164   SMLoc EndLoc;
4165   int64_t Imm = 0;
4166   int ShiftReg = 0;
4167   if (ShiftTy == ARM_AM::rrx) {
4168     // RRX Doesn't have an explicit shift amount. The encoder expects
4169     // the shift register to be the same as the source register. Seems odd,
4170     // but OK.
4171     ShiftReg = SrcReg;
4172   } else {
4173     // Figure out if this is shifted by a constant or a register (for non-RRX).
4174     if (Parser.getTok().is(AsmToken::Hash) ||
4175         Parser.getTok().is(AsmToken::Dollar)) {
4176       Parser.Lex(); // Eat hash.
4177       SMLoc ImmLoc = Parser.getTok().getLoc();
4178       const MCExpr *ShiftExpr = nullptr;
4179       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
4180         Error(ImmLoc, "invalid immediate shift value");
4181         return -1;
4182       }
4183       // The expression must be evaluatable as an immediate.
4184       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
4185       if (!CE) {
4186         Error(ImmLoc, "invalid immediate shift value");
4187         return -1;
4188       }
4189       // Range check the immediate.
4190       // lsl, ror: 0 <= imm <= 31
4191       // lsr, asr: 0 <= imm <= 32
4192       Imm = CE->getValue();
4193       if (Imm < 0 ||
4194           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
4195           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
4196         Error(ImmLoc, "immediate shift value out of range");
4197         return -1;
4198       }
4199       // shift by zero is a nop. Always send it through as lsl.
4200       // ('as' compatibility)
4201       if (Imm == 0)
4202         ShiftTy = ARM_AM::lsl;
4203     } else if (Parser.getTok().is(AsmToken::Identifier)) {
4204       SMLoc L = Parser.getTok().getLoc();
4205       EndLoc = Parser.getTok().getEndLoc();
4206       ShiftReg = tryParseRegister();
4207       if (ShiftReg == -1) {
4208         Error(L, "expected immediate or register in shift operand");
4209         return -1;
4210       }
4211     } else {
4212       Error(Parser.getTok().getLoc(),
4213             "expected immediate or register in shift operand");
4214       return -1;
4215     }
4216   }
4217 
4218   if (ShiftReg && ShiftTy != ARM_AM::rrx)
4219     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
4220                                                          ShiftReg, Imm,
4221                                                          S, EndLoc));
4222   else
4223     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
4224                                                           S, EndLoc));
4225 
4226   return 0;
4227 }
4228 
4229 /// Try to parse a register name.  The token must be an Identifier when called.
4230 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
4231 /// if there is a "writeback". 'true' if it's not a register.
4232 ///
4233 /// TODO this is likely to change to allow different register types and or to
4234 /// parse for a specific register type.
tryParseRegisterWithWriteBack(OperandVector & Operands)4235 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
4236   MCAsmParser &Parser = getParser();
4237   SMLoc RegStartLoc = Parser.getTok().getLoc();
4238   SMLoc RegEndLoc = Parser.getTok().getEndLoc();
4239   int RegNo = tryParseRegister();
4240   if (RegNo == -1)
4241     return true;
4242 
4243   Operands.push_back(ARMOperand::CreateReg(RegNo, RegStartLoc, RegEndLoc));
4244 
4245   const AsmToken &ExclaimTok = Parser.getTok();
4246   if (ExclaimTok.is(AsmToken::Exclaim)) {
4247     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
4248                                                ExclaimTok.getLoc()));
4249     Parser.Lex(); // Eat exclaim token
4250     return false;
4251   }
4252 
4253   // Also check for an index operand. This is only legal for vector registers,
4254   // but that'll get caught OK in operand matching, so we don't need to
4255   // explicitly filter everything else out here.
4256   if (Parser.getTok().is(AsmToken::LBrac)) {
4257     SMLoc SIdx = Parser.getTok().getLoc();
4258     Parser.Lex(); // Eat left bracket token.
4259 
4260     const MCExpr *ImmVal;
4261     if (getParser().parseExpression(ImmVal))
4262       return true;
4263     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
4264     if (!MCE)
4265       return TokError("immediate value expected for vector index");
4266 
4267     if (Parser.getTok().isNot(AsmToken::RBrac))
4268       return Error(Parser.getTok().getLoc(), "']' expected");
4269 
4270     SMLoc E = Parser.getTok().getEndLoc();
4271     Parser.Lex(); // Eat right bracket token.
4272 
4273     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
4274                                                      SIdx, E,
4275                                                      getContext()));
4276   }
4277 
4278   return false;
4279 }
4280 
4281 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
4282 /// instruction with a symbolic operand name.
4283 /// We accept "crN" syntax for GAS compatibility.
4284 /// <operand-name> ::= <prefix><number>
4285 /// If CoprocOp is 'c', then:
4286 ///   <prefix> ::= c | cr
4287 /// If CoprocOp is 'p', then :
4288 ///   <prefix> ::= p
4289 /// <number> ::= integer in range [0, 15]
MatchCoprocessorOperandName(StringRef Name,char CoprocOp)4290 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
4291   // Use the same layout as the tablegen'erated register name matcher. Ugly,
4292   // but efficient.
4293   if (Name.size() < 2 || Name[0] != CoprocOp)
4294     return -1;
4295   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
4296 
4297   switch (Name.size()) {
4298   default: return -1;
4299   case 1:
4300     switch (Name[0]) {
4301     default:  return -1;
4302     case '0': return 0;
4303     case '1': return 1;
4304     case '2': return 2;
4305     case '3': return 3;
4306     case '4': return 4;
4307     case '5': return 5;
4308     case '6': return 6;
4309     case '7': return 7;
4310     case '8': return 8;
4311     case '9': return 9;
4312     }
4313   case 2:
4314     if (Name[0] != '1')
4315       return -1;
4316     switch (Name[1]) {
4317     default:  return -1;
4318     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
4319     // However, old cores (v5/v6) did use them in that way.
4320     case '0': return 10;
4321     case '1': return 11;
4322     case '2': return 12;
4323     case '3': return 13;
4324     case '4': return 14;
4325     case '5': return 15;
4326     }
4327   }
4328 }
4329 
4330 /// parseITCondCode - Try to parse a condition code for an IT instruction.
4331 OperandMatchResultTy
parseITCondCode(OperandVector & Operands)4332 ARMAsmParser::parseITCondCode(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   unsigned CC = ARMCondCodeFromString(Tok.getString());
4339   if (CC == ~0U)
4340     return MatchOperand_NoMatch;
4341   Parser.Lex(); // Eat the token.
4342 
4343   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
4344 
4345   return MatchOperand_Success;
4346 }
4347 
4348 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
4349 /// token must be an Identifier when called, and if it is a coprocessor
4350 /// number, the token is eaten and the operand is added to the operand list.
4351 OperandMatchResultTy
parseCoprocNumOperand(OperandVector & Operands)4352 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
4353   MCAsmParser &Parser = getParser();
4354   SMLoc S = Parser.getTok().getLoc();
4355   const AsmToken &Tok = Parser.getTok();
4356   if (Tok.isNot(AsmToken::Identifier))
4357     return MatchOperand_NoMatch;
4358 
4359   int Num = MatchCoprocessorOperandName(Tok.getString().lower(), 'p');
4360   if (Num == -1)
4361     return MatchOperand_NoMatch;
4362   if (!isValidCoprocessorNumber(Num, getSTI().getFeatureBits()))
4363     return MatchOperand_NoMatch;
4364 
4365   Parser.Lex(); // Eat identifier token.
4366   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
4367   return MatchOperand_Success;
4368 }
4369 
4370 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
4371 /// token must be an Identifier when called, and if it is a coprocessor
4372 /// number, the token is eaten and the operand is added to the operand list.
4373 OperandMatchResultTy
parseCoprocRegOperand(OperandVector & Operands)4374 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
4375   MCAsmParser &Parser = getParser();
4376   SMLoc S = Parser.getTok().getLoc();
4377   const AsmToken &Tok = Parser.getTok();
4378   if (Tok.isNot(AsmToken::Identifier))
4379     return MatchOperand_NoMatch;
4380 
4381   int Reg = MatchCoprocessorOperandName(Tok.getString().lower(), 'c');
4382   if (Reg == -1)
4383     return MatchOperand_NoMatch;
4384 
4385   Parser.Lex(); // Eat identifier token.
4386   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
4387   return MatchOperand_Success;
4388 }
4389 
4390 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
4391 /// coproc_option : '{' imm0_255 '}'
4392 OperandMatchResultTy
parseCoprocOptionOperand(OperandVector & Operands)4393 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
4394   MCAsmParser &Parser = getParser();
4395   SMLoc S = Parser.getTok().getLoc();
4396 
4397   // If this isn't a '{', this isn't a coprocessor immediate operand.
4398   if (Parser.getTok().isNot(AsmToken::LCurly))
4399     return MatchOperand_NoMatch;
4400   Parser.Lex(); // Eat the '{'
4401 
4402   const MCExpr *Expr;
4403   SMLoc Loc = Parser.getTok().getLoc();
4404   if (getParser().parseExpression(Expr)) {
4405     Error(Loc, "illegal expression");
4406     return MatchOperand_ParseFail;
4407   }
4408   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4409   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
4410     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
4411     return MatchOperand_ParseFail;
4412   }
4413   int Val = CE->getValue();
4414 
4415   // Check for and consume the closing '}'
4416   if (Parser.getTok().isNot(AsmToken::RCurly))
4417     return MatchOperand_ParseFail;
4418   SMLoc E = Parser.getTok().getEndLoc();
4419   Parser.Lex(); // Eat the '}'
4420 
4421   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
4422   return MatchOperand_Success;
4423 }
4424 
4425 // For register list parsing, we need to map from raw GPR register numbering
4426 // to the enumeration values. The enumeration values aren't sorted by
4427 // register number due to our using "sp", "lr" and "pc" as canonical names.
getNextRegister(unsigned Reg)4428 static unsigned getNextRegister(unsigned Reg) {
4429   // If this is a GPR, we need to do it manually, otherwise we can rely
4430   // on the sort ordering of the enumeration since the other reg-classes
4431   // are sane.
4432   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
4433     return Reg + 1;
4434   switch(Reg) {
4435   default: llvm_unreachable("Invalid GPR number!");
4436   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
4437   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
4438   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
4439   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
4440   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
4441   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
4442   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
4443   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
4444   }
4445 }
4446 
4447 // Insert an <Encoding, Register> pair in an ordered vector. Return true on
4448 // success, or false, if duplicate encoding found.
4449 static bool
insertNoDuplicates(SmallVectorImpl<std::pair<unsigned,unsigned>> & Regs,unsigned Enc,unsigned Reg)4450 insertNoDuplicates(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
4451                    unsigned Enc, unsigned Reg) {
4452   Regs.emplace_back(Enc, Reg);
4453   for (auto I = Regs.rbegin(), J = I + 1, E = Regs.rend(); J != E; ++I, ++J) {
4454     if (J->first == Enc) {
4455       Regs.erase(J.base());
4456       return false;
4457     }
4458     if (J->first < Enc)
4459       break;
4460     std::swap(*I, *J);
4461   }
4462   return true;
4463 }
4464 
4465 /// Parse a register list.
parseRegisterList(OperandVector & Operands,bool EnforceOrder)4466 bool ARMAsmParser::parseRegisterList(OperandVector &Operands,
4467                                      bool EnforceOrder) {
4468   MCAsmParser &Parser = getParser();
4469   if (Parser.getTok().isNot(AsmToken::LCurly))
4470     return TokError("Token is not a Left Curly Brace");
4471   SMLoc S = Parser.getTok().getLoc();
4472   Parser.Lex(); // Eat '{' token.
4473   SMLoc RegLoc = Parser.getTok().getLoc();
4474 
4475   // Check the first register in the list to see what register class
4476   // this is a list of.
4477   int Reg = tryParseRegister();
4478   if (Reg == -1)
4479     return Error(RegLoc, "register expected");
4480 
4481   // The reglist instructions have at most 16 registers, so reserve
4482   // space for that many.
4483   int EReg = 0;
4484   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
4485 
4486   // Allow Q regs and just interpret them as the two D sub-registers.
4487   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4488     Reg = getDRegFromQReg(Reg);
4489     EReg = MRI->getEncodingValue(Reg);
4490     Registers.emplace_back(EReg, Reg);
4491     ++Reg;
4492   }
4493   const MCRegisterClass *RC;
4494   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
4495     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
4496   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
4497     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
4498   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
4499     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
4500   else if (ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(Reg))
4501     RC = &ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID];
4502   else
4503     return Error(RegLoc, "invalid register in register list");
4504 
4505   // Store the register.
4506   EReg = MRI->getEncodingValue(Reg);
4507   Registers.emplace_back(EReg, Reg);
4508 
4509   // This starts immediately after the first register token in the list,
4510   // so we can see either a comma or a minus (range separator) as a legal
4511   // next token.
4512   while (Parser.getTok().is(AsmToken::Comma) ||
4513          Parser.getTok().is(AsmToken::Minus)) {
4514     if (Parser.getTok().is(AsmToken::Minus)) {
4515       Parser.Lex(); // Eat the minus.
4516       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
4517       int EndReg = tryParseRegister();
4518       if (EndReg == -1)
4519         return Error(AfterMinusLoc, "register expected");
4520       // Allow Q regs and just interpret them as the two D sub-registers.
4521       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
4522         EndReg = getDRegFromQReg(EndReg) + 1;
4523       // If the register is the same as the start reg, there's nothing
4524       // more to do.
4525       if (Reg == EndReg)
4526         continue;
4527       // The register must be in the same register class as the first.
4528       if (!RC->contains(EndReg))
4529         return Error(AfterMinusLoc, "invalid register in register list");
4530       // Ranges must go from low to high.
4531       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
4532         return Error(AfterMinusLoc, "bad range in register list");
4533 
4534       // Add all the registers in the range to the register list.
4535       while (Reg != EndReg) {
4536         Reg = getNextRegister(Reg);
4537         EReg = MRI->getEncodingValue(Reg);
4538         if (!insertNoDuplicates(Registers, EReg, Reg)) {
4539           Warning(AfterMinusLoc, StringRef("duplicated register (") +
4540                                      ARMInstPrinter::getRegisterName(Reg) +
4541                                      ") in register list");
4542         }
4543       }
4544       continue;
4545     }
4546     Parser.Lex(); // Eat the comma.
4547     RegLoc = Parser.getTok().getLoc();
4548     int OldReg = Reg;
4549     const AsmToken RegTok = Parser.getTok();
4550     Reg = tryParseRegister();
4551     if (Reg == -1)
4552       return Error(RegLoc, "register expected");
4553     // Allow Q regs and just interpret them as the two D sub-registers.
4554     bool isQReg = false;
4555     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4556       Reg = getDRegFromQReg(Reg);
4557       isQReg = true;
4558     }
4559     if (!RC->contains(Reg) &&
4560         RC->getID() == ARMMCRegisterClasses[ARM::GPRRegClassID].getID() &&
4561         ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(Reg)) {
4562       // switch the register classes, as GPRwithAPSRnospRegClassID is a partial
4563       // subset of GPRRegClassId except it contains APSR as well.
4564       RC = &ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID];
4565     }
4566     if (Reg == ARM::VPR &&
4567         (RC == &ARMMCRegisterClasses[ARM::SPRRegClassID] ||
4568          RC == &ARMMCRegisterClasses[ARM::DPRRegClassID] ||
4569          RC == &ARMMCRegisterClasses[ARM::FPWithVPRRegClassID])) {
4570       RC = &ARMMCRegisterClasses[ARM::FPWithVPRRegClassID];
4571       EReg = MRI->getEncodingValue(Reg);
4572       if (!insertNoDuplicates(Registers, EReg, Reg)) {
4573         Warning(RegLoc, "duplicated register (" + RegTok.getString() +
4574                             ") in register list");
4575       }
4576       continue;
4577     }
4578     // The register must be in the same register class as the first.
4579     if (!RC->contains(Reg))
4580       return Error(RegLoc, "invalid register in register list");
4581     // In most cases, the list must be monotonically increasing. An
4582     // exception is CLRM, which is order-independent anyway, so
4583     // there's no potential for confusion if you write clrm {r2,r1}
4584     // instead of clrm {r1,r2}.
4585     if (EnforceOrder &&
4586         MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
4587       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
4588         Warning(RegLoc, "register list not in ascending order");
4589       else if (!ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(Reg))
4590         return Error(RegLoc, "register list not in ascending order");
4591     }
4592     // VFP register lists must also be contiguous.
4593     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
4594         RC != &ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID] &&
4595         Reg != OldReg + 1)
4596       return Error(RegLoc, "non-contiguous register range");
4597     EReg = MRI->getEncodingValue(Reg);
4598     if (!insertNoDuplicates(Registers, EReg, Reg)) {
4599       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
4600                           ") in register list");
4601     }
4602     if (isQReg) {
4603       EReg = MRI->getEncodingValue(++Reg);
4604       Registers.emplace_back(EReg, Reg);
4605     }
4606   }
4607 
4608   if (Parser.getTok().isNot(AsmToken::RCurly))
4609     return Error(Parser.getTok().getLoc(), "'}' expected");
4610   SMLoc E = Parser.getTok().getEndLoc();
4611   Parser.Lex(); // Eat '}' token.
4612 
4613   // Push the register list operand.
4614   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
4615 
4616   // The ARM system instruction variants for LDM/STM have a '^' token here.
4617   if (Parser.getTok().is(AsmToken::Caret)) {
4618     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
4619     Parser.Lex(); // Eat '^' token.
4620   }
4621 
4622   return false;
4623 }
4624 
4625 // Helper function to parse the lane index for vector lists.
4626 OperandMatchResultTy ARMAsmParser::
parseVectorLane(VectorLaneTy & LaneKind,unsigned & Index,SMLoc & EndLoc)4627 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
4628   MCAsmParser &Parser = getParser();
4629   Index = 0; // Always return a defined index value.
4630   if (Parser.getTok().is(AsmToken::LBrac)) {
4631     Parser.Lex(); // Eat the '['.
4632     if (Parser.getTok().is(AsmToken::RBrac)) {
4633       // "Dn[]" is the 'all lanes' syntax.
4634       LaneKind = AllLanes;
4635       EndLoc = Parser.getTok().getEndLoc();
4636       Parser.Lex(); // Eat the ']'.
4637       return MatchOperand_Success;
4638     }
4639 
4640     // There's an optional '#' token here. Normally there wouldn't be, but
4641     // inline assemble puts one in, and it's friendly to accept that.
4642     if (Parser.getTok().is(AsmToken::Hash))
4643       Parser.Lex(); // Eat '#' or '$'.
4644 
4645     const MCExpr *LaneIndex;
4646     SMLoc Loc = Parser.getTok().getLoc();
4647     if (getParser().parseExpression(LaneIndex)) {
4648       Error(Loc, "illegal expression");
4649       return MatchOperand_ParseFail;
4650     }
4651     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
4652     if (!CE) {
4653       Error(Loc, "lane index must be empty or an integer");
4654       return MatchOperand_ParseFail;
4655     }
4656     if (Parser.getTok().isNot(AsmToken::RBrac)) {
4657       Error(Parser.getTok().getLoc(), "']' expected");
4658       return MatchOperand_ParseFail;
4659     }
4660     EndLoc = Parser.getTok().getEndLoc();
4661     Parser.Lex(); // Eat the ']'.
4662     int64_t Val = CE->getValue();
4663 
4664     // FIXME: Make this range check context sensitive for .8, .16, .32.
4665     if (Val < 0 || Val > 7) {
4666       Error(Parser.getTok().getLoc(), "lane index out of range");
4667       return MatchOperand_ParseFail;
4668     }
4669     Index = Val;
4670     LaneKind = IndexedLane;
4671     return MatchOperand_Success;
4672   }
4673   LaneKind = NoLanes;
4674   return MatchOperand_Success;
4675 }
4676 
4677 // parse a vector register list
4678 OperandMatchResultTy
parseVectorList(OperandVector & Operands)4679 ARMAsmParser::parseVectorList(OperandVector &Operands) {
4680   MCAsmParser &Parser = getParser();
4681   VectorLaneTy LaneKind;
4682   unsigned LaneIndex;
4683   SMLoc S = Parser.getTok().getLoc();
4684   // As an extension (to match gas), support a plain D register or Q register
4685   // (without encosing curly braces) as a single or double entry list,
4686   // respectively.
4687   if (!hasMVE() && Parser.getTok().is(AsmToken::Identifier)) {
4688     SMLoc E = Parser.getTok().getEndLoc();
4689     int Reg = tryParseRegister();
4690     if (Reg == -1)
4691       return MatchOperand_NoMatch;
4692     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
4693       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
4694       if (Res != MatchOperand_Success)
4695         return Res;
4696       switch (LaneKind) {
4697       case NoLanes:
4698         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
4699         break;
4700       case AllLanes:
4701         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
4702                                                                 S, E));
4703         break;
4704       case IndexedLane:
4705         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
4706                                                                LaneIndex,
4707                                                                false, S, E));
4708         break;
4709       }
4710       return MatchOperand_Success;
4711     }
4712     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4713       Reg = getDRegFromQReg(Reg);
4714       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
4715       if (Res != MatchOperand_Success)
4716         return Res;
4717       switch (LaneKind) {
4718       case NoLanes:
4719         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
4720                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
4721         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
4722         break;
4723       case AllLanes:
4724         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
4725                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
4726         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
4727                                                                 S, E));
4728         break;
4729       case IndexedLane:
4730         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
4731                                                                LaneIndex,
4732                                                                false, S, E));
4733         break;
4734       }
4735       return MatchOperand_Success;
4736     }
4737     Error(S, "vector register expected");
4738     return MatchOperand_ParseFail;
4739   }
4740 
4741   if (Parser.getTok().isNot(AsmToken::LCurly))
4742     return MatchOperand_NoMatch;
4743 
4744   Parser.Lex(); // Eat '{' token.
4745   SMLoc RegLoc = Parser.getTok().getLoc();
4746 
4747   int Reg = tryParseRegister();
4748   if (Reg == -1) {
4749     Error(RegLoc, "register expected");
4750     return MatchOperand_ParseFail;
4751   }
4752   unsigned Count = 1;
4753   int Spacing = 0;
4754   unsigned FirstReg = Reg;
4755 
4756   if (hasMVE() && !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(Reg)) {
4757       Error(Parser.getTok().getLoc(), "vector register in range Q0-Q7 expected");
4758       return MatchOperand_ParseFail;
4759   }
4760   // The list is of D registers, but we also allow Q regs and just interpret
4761   // them as the two D sub-registers.
4762   else if (!hasMVE() && ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4763     FirstReg = Reg = getDRegFromQReg(Reg);
4764     Spacing = 1; // double-spacing requires explicit D registers, otherwise
4765                  // it's ambiguous with four-register single spaced.
4766     ++Reg;
4767     ++Count;
4768   }
4769 
4770   SMLoc E;
4771   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
4772     return MatchOperand_ParseFail;
4773 
4774   while (Parser.getTok().is(AsmToken::Comma) ||
4775          Parser.getTok().is(AsmToken::Minus)) {
4776     if (Parser.getTok().is(AsmToken::Minus)) {
4777       if (!Spacing)
4778         Spacing = 1; // Register range implies a single spaced list.
4779       else if (Spacing == 2) {
4780         Error(Parser.getTok().getLoc(),
4781               "sequential registers in double spaced list");
4782         return MatchOperand_ParseFail;
4783       }
4784       Parser.Lex(); // Eat the minus.
4785       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
4786       int EndReg = tryParseRegister();
4787       if (EndReg == -1) {
4788         Error(AfterMinusLoc, "register expected");
4789         return MatchOperand_ParseFail;
4790       }
4791       // Allow Q regs and just interpret them as the two D sub-registers.
4792       if (!hasMVE() && ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
4793         EndReg = getDRegFromQReg(EndReg) + 1;
4794       // If the register is the same as the start reg, there's nothing
4795       // more to do.
4796       if (Reg == EndReg)
4797         continue;
4798       // The register must be in the same register class as the first.
4799       if ((hasMVE() &&
4800            !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(EndReg)) ||
4801           (!hasMVE() &&
4802            !ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg))) {
4803         Error(AfterMinusLoc, "invalid register in register list");
4804         return MatchOperand_ParseFail;
4805       }
4806       // Ranges must go from low to high.
4807       if (Reg > EndReg) {
4808         Error(AfterMinusLoc, "bad range in register list");
4809         return MatchOperand_ParseFail;
4810       }
4811       // Parse the lane specifier if present.
4812       VectorLaneTy NextLaneKind;
4813       unsigned NextLaneIndex;
4814       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
4815           MatchOperand_Success)
4816         return MatchOperand_ParseFail;
4817       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4818         Error(AfterMinusLoc, "mismatched lane index in register list");
4819         return MatchOperand_ParseFail;
4820       }
4821 
4822       // Add all the registers in the range to the register list.
4823       Count += EndReg - Reg;
4824       Reg = EndReg;
4825       continue;
4826     }
4827     Parser.Lex(); // Eat the comma.
4828     RegLoc = Parser.getTok().getLoc();
4829     int OldReg = Reg;
4830     Reg = tryParseRegister();
4831     if (Reg == -1) {
4832       Error(RegLoc, "register expected");
4833       return MatchOperand_ParseFail;
4834     }
4835 
4836     if (hasMVE()) {
4837       if (!ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(Reg)) {
4838         Error(RegLoc, "vector register in range Q0-Q7 expected");
4839         return MatchOperand_ParseFail;
4840       }
4841       Spacing = 1;
4842     }
4843     // vector register lists must be contiguous.
4844     // It's OK to use the enumeration values directly here rather, as the
4845     // VFP register classes have the enum sorted properly.
4846     //
4847     // The list is of D registers, but we also allow Q regs and just interpret
4848     // them as the two D sub-registers.
4849     else if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4850       if (!Spacing)
4851         Spacing = 1; // Register range implies a single spaced list.
4852       else if (Spacing == 2) {
4853         Error(RegLoc,
4854               "invalid register in double-spaced list (must be 'D' register')");
4855         return MatchOperand_ParseFail;
4856       }
4857       Reg = getDRegFromQReg(Reg);
4858       if (Reg != OldReg + 1) {
4859         Error(RegLoc, "non-contiguous register range");
4860         return MatchOperand_ParseFail;
4861       }
4862       ++Reg;
4863       Count += 2;
4864       // Parse the lane specifier if present.
4865       VectorLaneTy NextLaneKind;
4866       unsigned NextLaneIndex;
4867       SMLoc LaneLoc = Parser.getTok().getLoc();
4868       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
4869           MatchOperand_Success)
4870         return MatchOperand_ParseFail;
4871       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4872         Error(LaneLoc, "mismatched lane index in register list");
4873         return MatchOperand_ParseFail;
4874       }
4875       continue;
4876     }
4877     // Normal D register.
4878     // Figure out the register spacing (single or double) of the list if
4879     // we don't know it already.
4880     if (!Spacing)
4881       Spacing = 1 + (Reg == OldReg + 2);
4882 
4883     // Just check that it's contiguous and keep going.
4884     if (Reg != OldReg + Spacing) {
4885       Error(RegLoc, "non-contiguous register range");
4886       return MatchOperand_ParseFail;
4887     }
4888     ++Count;
4889     // Parse the lane specifier if present.
4890     VectorLaneTy NextLaneKind;
4891     unsigned NextLaneIndex;
4892     SMLoc EndLoc = Parser.getTok().getLoc();
4893     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
4894       return MatchOperand_ParseFail;
4895     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4896       Error(EndLoc, "mismatched lane index in register list");
4897       return MatchOperand_ParseFail;
4898     }
4899   }
4900 
4901   if (Parser.getTok().isNot(AsmToken::RCurly)) {
4902     Error(Parser.getTok().getLoc(), "'}' expected");
4903     return MatchOperand_ParseFail;
4904   }
4905   E = Parser.getTok().getEndLoc();
4906   Parser.Lex(); // Eat '}' token.
4907 
4908   switch (LaneKind) {
4909   case NoLanes:
4910   case AllLanes: {
4911     // Two-register operands have been converted to the
4912     // composite register classes.
4913     if (Count == 2 && !hasMVE()) {
4914       const MCRegisterClass *RC = (Spacing == 1) ?
4915         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
4916         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
4917       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
4918     }
4919     auto Create = (LaneKind == NoLanes ? ARMOperand::CreateVectorList :
4920                    ARMOperand::CreateVectorListAllLanes);
4921     Operands.push_back(Create(FirstReg, Count, (Spacing == 2), S, E));
4922     break;
4923   }
4924   case IndexedLane:
4925     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
4926                                                            LaneIndex,
4927                                                            (Spacing == 2),
4928                                                            S, E));
4929     break;
4930   }
4931   return MatchOperand_Success;
4932 }
4933 
4934 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
4935 OperandMatchResultTy
parseMemBarrierOptOperand(OperandVector & Operands)4936 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
4937   MCAsmParser &Parser = getParser();
4938   SMLoc S = Parser.getTok().getLoc();
4939   const AsmToken &Tok = Parser.getTok();
4940   unsigned Opt;
4941 
4942   if (Tok.is(AsmToken::Identifier)) {
4943     StringRef OptStr = Tok.getString();
4944 
4945     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
4946       .Case("sy",    ARM_MB::SY)
4947       .Case("st",    ARM_MB::ST)
4948       .Case("ld",    ARM_MB::LD)
4949       .Case("sh",    ARM_MB::ISH)
4950       .Case("ish",   ARM_MB::ISH)
4951       .Case("shst",  ARM_MB::ISHST)
4952       .Case("ishst", ARM_MB::ISHST)
4953       .Case("ishld", ARM_MB::ISHLD)
4954       .Case("nsh",   ARM_MB::NSH)
4955       .Case("un",    ARM_MB::NSH)
4956       .Case("nshst", ARM_MB::NSHST)
4957       .Case("nshld", ARM_MB::NSHLD)
4958       .Case("unst",  ARM_MB::NSHST)
4959       .Case("osh",   ARM_MB::OSH)
4960       .Case("oshst", ARM_MB::OSHST)
4961       .Case("oshld", ARM_MB::OSHLD)
4962       .Default(~0U);
4963 
4964     // ishld, oshld, nshld and ld are only available from ARMv8.
4965     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
4966                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
4967       Opt = ~0U;
4968 
4969     if (Opt == ~0U)
4970       return MatchOperand_NoMatch;
4971 
4972     Parser.Lex(); // Eat identifier token.
4973   } else if (Tok.is(AsmToken::Hash) ||
4974              Tok.is(AsmToken::Dollar) ||
4975              Tok.is(AsmToken::Integer)) {
4976     if (Parser.getTok().isNot(AsmToken::Integer))
4977       Parser.Lex(); // Eat '#' or '$'.
4978     SMLoc Loc = Parser.getTok().getLoc();
4979 
4980     const MCExpr *MemBarrierID;
4981     if (getParser().parseExpression(MemBarrierID)) {
4982       Error(Loc, "illegal expression");
4983       return MatchOperand_ParseFail;
4984     }
4985 
4986     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
4987     if (!CE) {
4988       Error(Loc, "constant expression expected");
4989       return MatchOperand_ParseFail;
4990     }
4991 
4992     int Val = CE->getValue();
4993     if (Val & ~0xf) {
4994       Error(Loc, "immediate value out of range");
4995       return MatchOperand_ParseFail;
4996     }
4997 
4998     Opt = ARM_MB::RESERVED_0 + Val;
4999   } else
5000     return MatchOperand_ParseFail;
5001 
5002   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
5003   return MatchOperand_Success;
5004 }
5005 
5006 OperandMatchResultTy
parseTraceSyncBarrierOptOperand(OperandVector & Operands)5007 ARMAsmParser::parseTraceSyncBarrierOptOperand(OperandVector &Operands) {
5008   MCAsmParser &Parser = getParser();
5009   SMLoc S = Parser.getTok().getLoc();
5010   const AsmToken &Tok = Parser.getTok();
5011 
5012   if (Tok.isNot(AsmToken::Identifier))
5013      return MatchOperand_NoMatch;
5014 
5015   if (!Tok.getString().equals_lower("csync"))
5016     return MatchOperand_NoMatch;
5017 
5018   Parser.Lex(); // Eat identifier token.
5019 
5020   Operands.push_back(ARMOperand::CreateTraceSyncBarrierOpt(ARM_TSB::CSYNC, S));
5021   return MatchOperand_Success;
5022 }
5023 
5024 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
5025 OperandMatchResultTy
parseInstSyncBarrierOptOperand(OperandVector & Operands)5026 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
5027   MCAsmParser &Parser = getParser();
5028   SMLoc S = Parser.getTok().getLoc();
5029   const AsmToken &Tok = Parser.getTok();
5030   unsigned Opt;
5031 
5032   if (Tok.is(AsmToken::Identifier)) {
5033     StringRef OptStr = Tok.getString();
5034 
5035     if (OptStr.equals_lower("sy"))
5036       Opt = ARM_ISB::SY;
5037     else
5038       return MatchOperand_NoMatch;
5039 
5040     Parser.Lex(); // Eat identifier token.
5041   } else if (Tok.is(AsmToken::Hash) ||
5042              Tok.is(AsmToken::Dollar) ||
5043              Tok.is(AsmToken::Integer)) {
5044     if (Parser.getTok().isNot(AsmToken::Integer))
5045       Parser.Lex(); // Eat '#' or '$'.
5046     SMLoc Loc = Parser.getTok().getLoc();
5047 
5048     const MCExpr *ISBarrierID;
5049     if (getParser().parseExpression(ISBarrierID)) {
5050       Error(Loc, "illegal expression");
5051       return MatchOperand_ParseFail;
5052     }
5053 
5054     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
5055     if (!CE) {
5056       Error(Loc, "constant expression expected");
5057       return MatchOperand_ParseFail;
5058     }
5059 
5060     int Val = CE->getValue();
5061     if (Val & ~0xf) {
5062       Error(Loc, "immediate value out of range");
5063       return MatchOperand_ParseFail;
5064     }
5065 
5066     Opt = ARM_ISB::RESERVED_0 + Val;
5067   } else
5068     return MatchOperand_ParseFail;
5069 
5070   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
5071           (ARM_ISB::InstSyncBOpt)Opt, S));
5072   return MatchOperand_Success;
5073 }
5074 
5075 
5076 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
5077 OperandMatchResultTy
parseProcIFlagsOperand(OperandVector & Operands)5078 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
5079   MCAsmParser &Parser = getParser();
5080   SMLoc S = Parser.getTok().getLoc();
5081   const AsmToken &Tok = Parser.getTok();
5082   if (!Tok.is(AsmToken::Identifier))
5083     return MatchOperand_NoMatch;
5084   StringRef IFlagsStr = Tok.getString();
5085 
5086   // An iflags string of "none" is interpreted to mean that none of the AIF
5087   // bits are set.  Not a terribly useful instruction, but a valid encoding.
5088   unsigned IFlags = 0;
5089   if (IFlagsStr != "none") {
5090         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
5091       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1).lower())
5092         .Case("a", ARM_PROC::A)
5093         .Case("i", ARM_PROC::I)
5094         .Case("f", ARM_PROC::F)
5095         .Default(~0U);
5096 
5097       // If some specific iflag is already set, it means that some letter is
5098       // present more than once, this is not acceptable.
5099       if (Flag == ~0U || (IFlags & Flag))
5100         return MatchOperand_NoMatch;
5101 
5102       IFlags |= Flag;
5103     }
5104   }
5105 
5106   Parser.Lex(); // Eat identifier token.
5107   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
5108   return MatchOperand_Success;
5109 }
5110 
5111 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
5112 OperandMatchResultTy
parseMSRMaskOperand(OperandVector & Operands)5113 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
5114   MCAsmParser &Parser = getParser();
5115   SMLoc S = Parser.getTok().getLoc();
5116   const AsmToken &Tok = Parser.getTok();
5117 
5118   if (Tok.is(AsmToken::Integer)) {
5119     int64_t Val = Tok.getIntVal();
5120     if (Val > 255 || Val < 0) {
5121       return MatchOperand_NoMatch;
5122     }
5123     unsigned SYSmvalue = Val & 0xFF;
5124     Parser.Lex();
5125     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
5126     return MatchOperand_Success;
5127   }
5128 
5129   if (!Tok.is(AsmToken::Identifier))
5130     return MatchOperand_NoMatch;
5131   StringRef Mask = Tok.getString();
5132 
5133   if (isMClass()) {
5134     auto TheReg = ARMSysReg::lookupMClassSysRegByName(Mask.lower());
5135     if (!TheReg || !TheReg->hasRequiredFeatures(getSTI().getFeatureBits()))
5136       return MatchOperand_NoMatch;
5137 
5138     unsigned SYSmvalue = TheReg->Encoding & 0xFFF;
5139 
5140     Parser.Lex(); // Eat identifier token.
5141     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
5142     return MatchOperand_Success;
5143   }
5144 
5145   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
5146   size_t Start = 0, Next = Mask.find('_');
5147   StringRef Flags = "";
5148   std::string SpecReg = Mask.slice(Start, Next).lower();
5149   if (Next != StringRef::npos)
5150     Flags = Mask.slice(Next+1, Mask.size());
5151 
5152   // FlagsVal contains the complete mask:
5153   // 3-0: Mask
5154   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
5155   unsigned FlagsVal = 0;
5156 
5157   if (SpecReg == "apsr") {
5158     FlagsVal = StringSwitch<unsigned>(Flags)
5159     .Case("nzcvq",  0x8) // same as CPSR_f
5160     .Case("g",      0x4) // same as CPSR_s
5161     .Case("nzcvqg", 0xc) // same as CPSR_fs
5162     .Default(~0U);
5163 
5164     if (FlagsVal == ~0U) {
5165       if (!Flags.empty())
5166         return MatchOperand_NoMatch;
5167       else
5168         FlagsVal = 8; // No flag
5169     }
5170   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
5171     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
5172     if (Flags == "all" || Flags == "")
5173       Flags = "fc";
5174     for (int i = 0, e = Flags.size(); i != e; ++i) {
5175       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
5176       .Case("c", 1)
5177       .Case("x", 2)
5178       .Case("s", 4)
5179       .Case("f", 8)
5180       .Default(~0U);
5181 
5182       // If some specific flag is already set, it means that some letter is
5183       // present more than once, this is not acceptable.
5184       if (Flag == ~0U || (FlagsVal & Flag))
5185         return MatchOperand_NoMatch;
5186       FlagsVal |= Flag;
5187     }
5188   } else // No match for special register.
5189     return MatchOperand_NoMatch;
5190 
5191   // Special register without flags is NOT equivalent to "fc" flags.
5192   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
5193   // two lines would enable gas compatibility at the expense of breaking
5194   // round-tripping.
5195   //
5196   // if (!FlagsVal)
5197   //  FlagsVal = 0x9;
5198 
5199   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
5200   if (SpecReg == "spsr")
5201     FlagsVal |= 16;
5202 
5203   Parser.Lex(); // Eat identifier token.
5204   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
5205   return MatchOperand_Success;
5206 }
5207 
5208 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
5209 /// use in the MRS/MSR instructions added to support virtualization.
5210 OperandMatchResultTy
parseBankedRegOperand(OperandVector & Operands)5211 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
5212   MCAsmParser &Parser = getParser();
5213   SMLoc S = Parser.getTok().getLoc();
5214   const AsmToken &Tok = Parser.getTok();
5215   if (!Tok.is(AsmToken::Identifier))
5216     return MatchOperand_NoMatch;
5217   StringRef RegName = Tok.getString();
5218 
5219   auto TheReg = ARMBankedReg::lookupBankedRegByName(RegName.lower());
5220   if (!TheReg)
5221     return MatchOperand_NoMatch;
5222   unsigned Encoding = TheReg->Encoding;
5223 
5224   Parser.Lex(); // Eat identifier token.
5225   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
5226   return MatchOperand_Success;
5227 }
5228 
5229 OperandMatchResultTy
parsePKHImm(OperandVector & Operands,StringRef Op,int Low,int High)5230 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
5231                           int High) {
5232   MCAsmParser &Parser = getParser();
5233   const AsmToken &Tok = Parser.getTok();
5234   if (Tok.isNot(AsmToken::Identifier)) {
5235     Error(Parser.getTok().getLoc(), Op + " operand expected.");
5236     return MatchOperand_ParseFail;
5237   }
5238   StringRef ShiftName = Tok.getString();
5239   std::string LowerOp = Op.lower();
5240   std::string UpperOp = Op.upper();
5241   if (ShiftName != LowerOp && ShiftName != UpperOp) {
5242     Error(Parser.getTok().getLoc(), Op + " operand expected.");
5243     return MatchOperand_ParseFail;
5244   }
5245   Parser.Lex(); // Eat shift type token.
5246 
5247   // There must be a '#' and a shift amount.
5248   if (Parser.getTok().isNot(AsmToken::Hash) &&
5249       Parser.getTok().isNot(AsmToken::Dollar)) {
5250     Error(Parser.getTok().getLoc(), "'#' expected");
5251     return MatchOperand_ParseFail;
5252   }
5253   Parser.Lex(); // Eat hash token.
5254 
5255   const MCExpr *ShiftAmount;
5256   SMLoc Loc = Parser.getTok().getLoc();
5257   SMLoc EndLoc;
5258   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
5259     Error(Loc, "illegal expression");
5260     return MatchOperand_ParseFail;
5261   }
5262   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
5263   if (!CE) {
5264     Error(Loc, "constant expression expected");
5265     return MatchOperand_ParseFail;
5266   }
5267   int Val = CE->getValue();
5268   if (Val < Low || Val > High) {
5269     Error(Loc, "immediate value out of range");
5270     return MatchOperand_ParseFail;
5271   }
5272 
5273   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
5274 
5275   return MatchOperand_Success;
5276 }
5277 
5278 OperandMatchResultTy
parseSetEndImm(OperandVector & Operands)5279 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
5280   MCAsmParser &Parser = getParser();
5281   const AsmToken &Tok = Parser.getTok();
5282   SMLoc S = Tok.getLoc();
5283   if (Tok.isNot(AsmToken::Identifier)) {
5284     Error(S, "'be' or 'le' operand expected");
5285     return MatchOperand_ParseFail;
5286   }
5287   int Val = StringSwitch<int>(Tok.getString().lower())
5288     .Case("be", 1)
5289     .Case("le", 0)
5290     .Default(-1);
5291   Parser.Lex(); // Eat the token.
5292 
5293   if (Val == -1) {
5294     Error(S, "'be' or 'le' operand expected");
5295     return MatchOperand_ParseFail;
5296   }
5297   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
5298                                                                   getContext()),
5299                                            S, Tok.getEndLoc()));
5300   return MatchOperand_Success;
5301 }
5302 
5303 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
5304 /// instructions. Legal values are:
5305 ///     lsl #n  'n' in [0,31]
5306 ///     asr #n  'n' in [1,32]
5307 ///             n == 32 encoded as n == 0.
5308 OperandMatchResultTy
parseShifterImm(OperandVector & Operands)5309 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
5310   MCAsmParser &Parser = getParser();
5311   const AsmToken &Tok = Parser.getTok();
5312   SMLoc S = Tok.getLoc();
5313   if (Tok.isNot(AsmToken::Identifier)) {
5314     Error(S, "shift operator 'asr' or 'lsl' expected");
5315     return MatchOperand_ParseFail;
5316   }
5317   StringRef ShiftName = Tok.getString();
5318   bool isASR;
5319   if (ShiftName == "lsl" || ShiftName == "LSL")
5320     isASR = false;
5321   else if (ShiftName == "asr" || ShiftName == "ASR")
5322     isASR = true;
5323   else {
5324     Error(S, "shift operator 'asr' or 'lsl' expected");
5325     return MatchOperand_ParseFail;
5326   }
5327   Parser.Lex(); // Eat the operator.
5328 
5329   // A '#' and a shift amount.
5330   if (Parser.getTok().isNot(AsmToken::Hash) &&
5331       Parser.getTok().isNot(AsmToken::Dollar)) {
5332     Error(Parser.getTok().getLoc(), "'#' expected");
5333     return MatchOperand_ParseFail;
5334   }
5335   Parser.Lex(); // Eat hash token.
5336   SMLoc ExLoc = Parser.getTok().getLoc();
5337 
5338   const MCExpr *ShiftAmount;
5339   SMLoc EndLoc;
5340   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
5341     Error(ExLoc, "malformed shift expression");
5342     return MatchOperand_ParseFail;
5343   }
5344   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
5345   if (!CE) {
5346     Error(ExLoc, "shift amount must be an immediate");
5347     return MatchOperand_ParseFail;
5348   }
5349 
5350   int64_t Val = CE->getValue();
5351   if (isASR) {
5352     // Shift amount must be in [1,32]
5353     if (Val < 1 || Val > 32) {
5354       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
5355       return MatchOperand_ParseFail;
5356     }
5357     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
5358     if (isThumb() && Val == 32) {
5359       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
5360       return MatchOperand_ParseFail;
5361     }
5362     if (Val == 32) Val = 0;
5363   } else {
5364     // Shift amount must be in [1,32]
5365     if (Val < 0 || Val > 31) {
5366       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
5367       return MatchOperand_ParseFail;
5368     }
5369   }
5370 
5371   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
5372 
5373   return MatchOperand_Success;
5374 }
5375 
5376 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
5377 /// of instructions. Legal values are:
5378 ///     ror #n  'n' in {0, 8, 16, 24}
5379 OperandMatchResultTy
parseRotImm(OperandVector & Operands)5380 ARMAsmParser::parseRotImm(OperandVector &Operands) {
5381   MCAsmParser &Parser = getParser();
5382   const AsmToken &Tok = Parser.getTok();
5383   SMLoc S = Tok.getLoc();
5384   if (Tok.isNot(AsmToken::Identifier))
5385     return MatchOperand_NoMatch;
5386   StringRef ShiftName = Tok.getString();
5387   if (ShiftName != "ror" && ShiftName != "ROR")
5388     return MatchOperand_NoMatch;
5389   Parser.Lex(); // Eat the operator.
5390 
5391   // A '#' and a rotate amount.
5392   if (Parser.getTok().isNot(AsmToken::Hash) &&
5393       Parser.getTok().isNot(AsmToken::Dollar)) {
5394     Error(Parser.getTok().getLoc(), "'#' expected");
5395     return MatchOperand_ParseFail;
5396   }
5397   Parser.Lex(); // Eat hash token.
5398   SMLoc ExLoc = Parser.getTok().getLoc();
5399 
5400   const MCExpr *ShiftAmount;
5401   SMLoc EndLoc;
5402   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
5403     Error(ExLoc, "malformed rotate expression");
5404     return MatchOperand_ParseFail;
5405   }
5406   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
5407   if (!CE) {
5408     Error(ExLoc, "rotate amount must be an immediate");
5409     return MatchOperand_ParseFail;
5410   }
5411 
5412   int64_t Val = CE->getValue();
5413   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
5414   // normally, zero is represented in asm by omitting the rotate operand
5415   // entirely.
5416   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
5417     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
5418     return MatchOperand_ParseFail;
5419   }
5420 
5421   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
5422 
5423   return MatchOperand_Success;
5424 }
5425 
5426 OperandMatchResultTy
parseModImm(OperandVector & Operands)5427 ARMAsmParser::parseModImm(OperandVector &Operands) {
5428   MCAsmParser &Parser = getParser();
5429   MCAsmLexer &Lexer = getLexer();
5430   int64_t Imm1, Imm2;
5431 
5432   SMLoc S = Parser.getTok().getLoc();
5433 
5434   // 1) A mod_imm operand can appear in the place of a register name:
5435   //   add r0, #mod_imm
5436   //   add r0, r0, #mod_imm
5437   // to correctly handle the latter, we bail out as soon as we see an
5438   // identifier.
5439   //
5440   // 2) Similarly, we do not want to parse into complex operands:
5441   //   mov r0, #mod_imm
5442   //   mov r0, :lower16:(_foo)
5443   if (Parser.getTok().is(AsmToken::Identifier) ||
5444       Parser.getTok().is(AsmToken::Colon))
5445     return MatchOperand_NoMatch;
5446 
5447   // Hash (dollar) is optional as per the ARMARM
5448   if (Parser.getTok().is(AsmToken::Hash) ||
5449       Parser.getTok().is(AsmToken::Dollar)) {
5450     // Avoid parsing into complex operands (#:)
5451     if (Lexer.peekTok().is(AsmToken::Colon))
5452       return MatchOperand_NoMatch;
5453 
5454     // Eat the hash (dollar)
5455     Parser.Lex();
5456   }
5457 
5458   SMLoc Sx1, Ex1;
5459   Sx1 = Parser.getTok().getLoc();
5460   const MCExpr *Imm1Exp;
5461   if (getParser().parseExpression(Imm1Exp, Ex1)) {
5462     Error(Sx1, "malformed expression");
5463     return MatchOperand_ParseFail;
5464   }
5465 
5466   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
5467 
5468   if (CE) {
5469     // Immediate must fit within 32-bits
5470     Imm1 = CE->getValue();
5471     int Enc = ARM_AM::getSOImmVal(Imm1);
5472     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
5473       // We have a match!
5474       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
5475                                                   (Enc & 0xF00) >> 7,
5476                                                   Sx1, Ex1));
5477       return MatchOperand_Success;
5478     }
5479 
5480     // We have parsed an immediate which is not for us, fallback to a plain
5481     // immediate. This can happen for instruction aliases. For an example,
5482     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
5483     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
5484     // instruction with a mod_imm operand. The alias is defined such that the
5485     // parser method is shared, that's why we have to do this here.
5486     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
5487       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
5488       return MatchOperand_Success;
5489     }
5490   } else {
5491     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
5492     // MCFixup). Fallback to a plain immediate.
5493     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
5494     return MatchOperand_Success;
5495   }
5496 
5497   // From this point onward, we expect the input to be a (#bits, #rot) pair
5498   if (Parser.getTok().isNot(AsmToken::Comma)) {
5499     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
5500     return MatchOperand_ParseFail;
5501   }
5502 
5503   if (Imm1 & ~0xFF) {
5504     Error(Sx1, "immediate operand must a number in the range [0, 255]");
5505     return MatchOperand_ParseFail;
5506   }
5507 
5508   // Eat the comma
5509   Parser.Lex();
5510 
5511   // Repeat for #rot
5512   SMLoc Sx2, Ex2;
5513   Sx2 = Parser.getTok().getLoc();
5514 
5515   // Eat the optional hash (dollar)
5516   if (Parser.getTok().is(AsmToken::Hash) ||
5517       Parser.getTok().is(AsmToken::Dollar))
5518     Parser.Lex();
5519 
5520   const MCExpr *Imm2Exp;
5521   if (getParser().parseExpression(Imm2Exp, Ex2)) {
5522     Error(Sx2, "malformed expression");
5523     return MatchOperand_ParseFail;
5524   }
5525 
5526   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
5527 
5528   if (CE) {
5529     Imm2 = CE->getValue();
5530     if (!(Imm2 & ~0x1E)) {
5531       // We have a match!
5532       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
5533       return MatchOperand_Success;
5534     }
5535     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
5536     return MatchOperand_ParseFail;
5537   } else {
5538     Error(Sx2, "constant expression expected");
5539     return MatchOperand_ParseFail;
5540   }
5541 }
5542 
5543 OperandMatchResultTy
parseBitfield(OperandVector & Operands)5544 ARMAsmParser::parseBitfield(OperandVector &Operands) {
5545   MCAsmParser &Parser = getParser();
5546   SMLoc S = Parser.getTok().getLoc();
5547   // The bitfield descriptor is really two operands, the LSB and the width.
5548   if (Parser.getTok().isNot(AsmToken::Hash) &&
5549       Parser.getTok().isNot(AsmToken::Dollar)) {
5550     Error(Parser.getTok().getLoc(), "'#' expected");
5551     return MatchOperand_ParseFail;
5552   }
5553   Parser.Lex(); // Eat hash token.
5554 
5555   const MCExpr *LSBExpr;
5556   SMLoc E = Parser.getTok().getLoc();
5557   if (getParser().parseExpression(LSBExpr)) {
5558     Error(E, "malformed immediate expression");
5559     return MatchOperand_ParseFail;
5560   }
5561   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
5562   if (!CE) {
5563     Error(E, "'lsb' operand must be an immediate");
5564     return MatchOperand_ParseFail;
5565   }
5566 
5567   int64_t LSB = CE->getValue();
5568   // The LSB must be in the range [0,31]
5569   if (LSB < 0 || LSB > 31) {
5570     Error(E, "'lsb' operand must be in the range [0,31]");
5571     return MatchOperand_ParseFail;
5572   }
5573   E = Parser.getTok().getLoc();
5574 
5575   // Expect another immediate operand.
5576   if (Parser.getTok().isNot(AsmToken::Comma)) {
5577     Error(Parser.getTok().getLoc(), "too few operands");
5578     return MatchOperand_ParseFail;
5579   }
5580   Parser.Lex(); // Eat hash token.
5581   if (Parser.getTok().isNot(AsmToken::Hash) &&
5582       Parser.getTok().isNot(AsmToken::Dollar)) {
5583     Error(Parser.getTok().getLoc(), "'#' expected");
5584     return MatchOperand_ParseFail;
5585   }
5586   Parser.Lex(); // Eat hash token.
5587 
5588   const MCExpr *WidthExpr;
5589   SMLoc EndLoc;
5590   if (getParser().parseExpression(WidthExpr, EndLoc)) {
5591     Error(E, "malformed immediate expression");
5592     return MatchOperand_ParseFail;
5593   }
5594   CE = dyn_cast<MCConstantExpr>(WidthExpr);
5595   if (!CE) {
5596     Error(E, "'width' operand must be an immediate");
5597     return MatchOperand_ParseFail;
5598   }
5599 
5600   int64_t Width = CE->getValue();
5601   // The LSB must be in the range [1,32-lsb]
5602   if (Width < 1 || Width > 32 - LSB) {
5603     Error(E, "'width' operand must be in the range [1,32-lsb]");
5604     return MatchOperand_ParseFail;
5605   }
5606 
5607   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
5608 
5609   return MatchOperand_Success;
5610 }
5611 
5612 OperandMatchResultTy
parsePostIdxReg(OperandVector & Operands)5613 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
5614   // Check for a post-index addressing register operand. Specifically:
5615   // postidx_reg := '+' register {, shift}
5616   //              | '-' register {, shift}
5617   //              | register {, shift}
5618 
5619   // This method must return MatchOperand_NoMatch without consuming any tokens
5620   // in the case where there is no match, as other alternatives take other
5621   // parse methods.
5622   MCAsmParser &Parser = getParser();
5623   AsmToken Tok = Parser.getTok();
5624   SMLoc S = Tok.getLoc();
5625   bool haveEaten = false;
5626   bool isAdd = true;
5627   if (Tok.is(AsmToken::Plus)) {
5628     Parser.Lex(); // Eat the '+' token.
5629     haveEaten = true;
5630   } else if (Tok.is(AsmToken::Minus)) {
5631     Parser.Lex(); // Eat the '-' token.
5632     isAdd = false;
5633     haveEaten = true;
5634   }
5635 
5636   SMLoc E = Parser.getTok().getEndLoc();
5637   int Reg = tryParseRegister();
5638   if (Reg == -1) {
5639     if (!haveEaten)
5640       return MatchOperand_NoMatch;
5641     Error(Parser.getTok().getLoc(), "register expected");
5642     return MatchOperand_ParseFail;
5643   }
5644 
5645   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
5646   unsigned ShiftImm = 0;
5647   if (Parser.getTok().is(AsmToken::Comma)) {
5648     Parser.Lex(); // Eat the ','.
5649     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
5650       return MatchOperand_ParseFail;
5651 
5652     // FIXME: Only approximates end...may include intervening whitespace.
5653     E = Parser.getTok().getLoc();
5654   }
5655 
5656   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
5657                                                   ShiftImm, S, E));
5658 
5659   return MatchOperand_Success;
5660 }
5661 
5662 OperandMatchResultTy
parseAM3Offset(OperandVector & Operands)5663 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
5664   // Check for a post-index addressing register operand. Specifically:
5665   // am3offset := '+' register
5666   //              | '-' register
5667   //              | register
5668   //              | # imm
5669   //              | # + imm
5670   //              | # - imm
5671 
5672   // This method must return MatchOperand_NoMatch without consuming any tokens
5673   // in the case where there is no match, as other alternatives take other
5674   // parse methods.
5675   MCAsmParser &Parser = getParser();
5676   AsmToken Tok = Parser.getTok();
5677   SMLoc S = Tok.getLoc();
5678 
5679   // Do immediates first, as we always parse those if we have a '#'.
5680   if (Parser.getTok().is(AsmToken::Hash) ||
5681       Parser.getTok().is(AsmToken::Dollar)) {
5682     Parser.Lex(); // Eat '#' or '$'.
5683     // Explicitly look for a '-', as we need to encode negative zero
5684     // differently.
5685     bool isNegative = Parser.getTok().is(AsmToken::Minus);
5686     const MCExpr *Offset;
5687     SMLoc E;
5688     if (getParser().parseExpression(Offset, E))
5689       return MatchOperand_ParseFail;
5690     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
5691     if (!CE) {
5692       Error(S, "constant expression expected");
5693       return MatchOperand_ParseFail;
5694     }
5695     // Negative zero is encoded as the flag value
5696     // std::numeric_limits<int32_t>::min().
5697     int32_t Val = CE->getValue();
5698     if (isNegative && Val == 0)
5699       Val = std::numeric_limits<int32_t>::min();
5700 
5701     Operands.push_back(
5702       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
5703 
5704     return MatchOperand_Success;
5705   }
5706 
5707   bool haveEaten = false;
5708   bool isAdd = true;
5709   if (Tok.is(AsmToken::Plus)) {
5710     Parser.Lex(); // Eat the '+' token.
5711     haveEaten = true;
5712   } else if (Tok.is(AsmToken::Minus)) {
5713     Parser.Lex(); // Eat the '-' token.
5714     isAdd = false;
5715     haveEaten = true;
5716   }
5717 
5718   Tok = Parser.getTok();
5719   int Reg = tryParseRegister();
5720   if (Reg == -1) {
5721     if (!haveEaten)
5722       return MatchOperand_NoMatch;
5723     Error(Tok.getLoc(), "register expected");
5724     return MatchOperand_ParseFail;
5725   }
5726 
5727   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
5728                                                   0, S, Tok.getEndLoc()));
5729 
5730   return MatchOperand_Success;
5731 }
5732 
5733 /// Convert parsed operands to MCInst.  Needed here because this instruction
5734 /// only has two register operands, but multiplication is commutative so
5735 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
cvtThumbMultiply(MCInst & Inst,const OperandVector & Operands)5736 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
5737                                     const OperandVector &Operands) {
5738   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
5739   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
5740   // If we have a three-operand form, make sure to set Rn to be the operand
5741   // that isn't the same as Rd.
5742   unsigned RegOp = 4;
5743   if (Operands.size() == 6 &&
5744       ((ARMOperand &)*Operands[4]).getReg() ==
5745           ((ARMOperand &)*Operands[3]).getReg())
5746     RegOp = 5;
5747   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
5748   Inst.addOperand(Inst.getOperand(0));
5749   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
5750 }
5751 
cvtThumbBranches(MCInst & Inst,const OperandVector & Operands)5752 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
5753                                     const OperandVector &Operands) {
5754   int CondOp = -1, ImmOp = -1;
5755   switch(Inst.getOpcode()) {
5756     case ARM::tB:
5757     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
5758 
5759     case ARM::t2B:
5760     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
5761 
5762     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
5763   }
5764   // first decide whether or not the branch should be conditional
5765   // by looking at it's location relative to an IT block
5766   if(inITBlock()) {
5767     // inside an IT block we cannot have any conditional branches. any
5768     // such instructions needs to be converted to unconditional form
5769     switch(Inst.getOpcode()) {
5770       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
5771       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
5772     }
5773   } else {
5774     // outside IT blocks we can only have unconditional branches with AL
5775     // condition code or conditional branches with non-AL condition code
5776     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
5777     switch(Inst.getOpcode()) {
5778       case ARM::tB:
5779       case ARM::tBcc:
5780         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc);
5781         break;
5782       case ARM::t2B:
5783       case ARM::t2Bcc:
5784         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
5785         break;
5786     }
5787   }
5788 
5789   // now decide on encoding size based on branch target range
5790   switch(Inst.getOpcode()) {
5791     // classify tB as either t2B or t1B based on range of immediate operand
5792     case ARM::tB: {
5793       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
5794       if (!op.isSignedOffset<11, 1>() && isThumb() && hasV8MBaseline())
5795         Inst.setOpcode(ARM::t2B);
5796       break;
5797     }
5798     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
5799     case ARM::tBcc: {
5800       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
5801       if (!op.isSignedOffset<8, 1>() && isThumb() && hasV8MBaseline())
5802         Inst.setOpcode(ARM::t2Bcc);
5803       break;
5804     }
5805   }
5806   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
5807   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
5808 }
5809 
cvtMVEVMOVQtoDReg(MCInst & Inst,const OperandVector & Operands)5810 void ARMAsmParser::cvtMVEVMOVQtoDReg(
5811   MCInst &Inst, const OperandVector &Operands) {
5812 
5813   // mnemonic, condition code, Rt, Rt2, Qd, idx, Qd again, idx2
5814   assert(Operands.size() == 8);
5815 
5816   ((ARMOperand &)*Operands[2]).addRegOperands(Inst, 1); // Rt
5817   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1); // Rt2
5818   ((ARMOperand &)*Operands[4]).addRegOperands(Inst, 1); // Qd
5819   ((ARMOperand &)*Operands[5]).addMVEPairVectorIndexOperands(Inst, 1); // idx
5820   // skip second copy of Qd in Operands[6]
5821   ((ARMOperand &)*Operands[7]).addMVEPairVectorIndexOperands(Inst, 1); // idx2
5822   ((ARMOperand &)*Operands[1]).addCondCodeOperands(Inst, 2); // condition code
5823 }
5824 
5825 /// Parse an ARM memory expression, return false if successful else return true
5826 /// or an error.  The first token must be a '[' when called.
parseMemory(OperandVector & Operands)5827 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
5828   MCAsmParser &Parser = getParser();
5829   SMLoc S, E;
5830   if (Parser.getTok().isNot(AsmToken::LBrac))
5831     return TokError("Token is not a Left Bracket");
5832   S = Parser.getTok().getLoc();
5833   Parser.Lex(); // Eat left bracket token.
5834 
5835   const AsmToken &BaseRegTok = Parser.getTok();
5836   int BaseRegNum = tryParseRegister();
5837   if (BaseRegNum == -1)
5838     return Error(BaseRegTok.getLoc(), "register expected");
5839 
5840   // The next token must either be a comma, a colon or a closing bracket.
5841   const AsmToken &Tok = Parser.getTok();
5842   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
5843       !Tok.is(AsmToken::RBrac))
5844     return Error(Tok.getLoc(), "malformed memory operand");
5845 
5846   if (Tok.is(AsmToken::RBrac)) {
5847     E = Tok.getEndLoc();
5848     Parser.Lex(); // Eat right bracket token.
5849 
5850     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5851                                              ARM_AM::no_shift, 0, 0, false,
5852                                              S, E));
5853 
5854     // If there's a pre-indexing writeback marker, '!', just add it as a token
5855     // operand. It's rather odd, but syntactically valid.
5856     if (Parser.getTok().is(AsmToken::Exclaim)) {
5857       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5858       Parser.Lex(); // Eat the '!'.
5859     }
5860 
5861     return false;
5862   }
5863 
5864   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
5865          "Lost colon or comma in memory operand?!");
5866   if (Tok.is(AsmToken::Comma)) {
5867     Parser.Lex(); // Eat the comma.
5868   }
5869 
5870   // If we have a ':', it's an alignment specifier.
5871   if (Parser.getTok().is(AsmToken::Colon)) {
5872     Parser.Lex(); // Eat the ':'.
5873     E = Parser.getTok().getLoc();
5874     SMLoc AlignmentLoc = Tok.getLoc();
5875 
5876     const MCExpr *Expr;
5877     if (getParser().parseExpression(Expr))
5878      return true;
5879 
5880     // The expression has to be a constant. Memory references with relocations
5881     // don't come through here, as they use the <label> forms of the relevant
5882     // instructions.
5883     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5884     if (!CE)
5885       return Error (E, "constant expression expected");
5886 
5887     unsigned Align = 0;
5888     switch (CE->getValue()) {
5889     default:
5890       return Error(E,
5891                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
5892     case 16:  Align = 2; break;
5893     case 32:  Align = 4; break;
5894     case 64:  Align = 8; break;
5895     case 128: Align = 16; break;
5896     case 256: Align = 32; break;
5897     }
5898 
5899     // Now we should have the closing ']'
5900     if (Parser.getTok().isNot(AsmToken::RBrac))
5901       return Error(Parser.getTok().getLoc(), "']' expected");
5902     E = Parser.getTok().getEndLoc();
5903     Parser.Lex(); // Eat right bracket token.
5904 
5905     // Don't worry about range checking the value here. That's handled by
5906     // the is*() predicates.
5907     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5908                                              ARM_AM::no_shift, 0, Align,
5909                                              false, S, E, AlignmentLoc));
5910 
5911     // If there's a pre-indexing writeback marker, '!', just add it as a token
5912     // operand.
5913     if (Parser.getTok().is(AsmToken::Exclaim)) {
5914       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5915       Parser.Lex(); // Eat the '!'.
5916     }
5917 
5918     return false;
5919   }
5920 
5921   // If we have a '#' or '$', it's an immediate offset, else assume it's a
5922   // register offset. Be friendly and also accept a plain integer or expression
5923   // (without a leading hash) for gas compatibility.
5924   if (Parser.getTok().is(AsmToken::Hash) ||
5925       Parser.getTok().is(AsmToken::Dollar) ||
5926       Parser.getTok().is(AsmToken::LParen) ||
5927       Parser.getTok().is(AsmToken::Integer)) {
5928     if (Parser.getTok().is(AsmToken::Hash) ||
5929         Parser.getTok().is(AsmToken::Dollar))
5930       Parser.Lex(); // Eat '#' or '$'
5931     E = Parser.getTok().getLoc();
5932 
5933     bool isNegative = getParser().getTok().is(AsmToken::Minus);
5934     const MCExpr *Offset, *AdjustedOffset;
5935     if (getParser().parseExpression(Offset))
5936      return true;
5937 
5938     if (const auto *CE = dyn_cast<MCConstantExpr>(Offset)) {
5939       // If the constant was #-0, represent it as
5940       // std::numeric_limits<int32_t>::min().
5941       int32_t Val = CE->getValue();
5942       if (isNegative && Val == 0)
5943         CE = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
5944                                     getContext());
5945       // Don't worry about range checking the value here. That's handled by
5946       // the is*() predicates.
5947       AdjustedOffset = CE;
5948     } else
5949       AdjustedOffset = Offset;
5950     Operands.push_back(ARMOperand::CreateMem(
5951         BaseRegNum, AdjustedOffset, 0, ARM_AM::no_shift, 0, 0, false, S, E));
5952 
5953     // Now we should have the closing ']'
5954     if (Parser.getTok().isNot(AsmToken::RBrac))
5955       return Error(Parser.getTok().getLoc(), "']' expected");
5956     E = Parser.getTok().getEndLoc();
5957     Parser.Lex(); // Eat right bracket token.
5958 
5959     // If there's a pre-indexing writeback marker, '!', just add it as a token
5960     // operand.
5961     if (Parser.getTok().is(AsmToken::Exclaim)) {
5962       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5963       Parser.Lex(); // Eat the '!'.
5964     }
5965 
5966     return false;
5967   }
5968 
5969   // The register offset is optionally preceded by a '+' or '-'
5970   bool isNegative = false;
5971   if (Parser.getTok().is(AsmToken::Minus)) {
5972     isNegative = true;
5973     Parser.Lex(); // Eat the '-'.
5974   } else if (Parser.getTok().is(AsmToken::Plus)) {
5975     // Nothing to do.
5976     Parser.Lex(); // Eat the '+'.
5977   }
5978 
5979   E = Parser.getTok().getLoc();
5980   int OffsetRegNum = tryParseRegister();
5981   if (OffsetRegNum == -1)
5982     return Error(E, "register expected");
5983 
5984   // If there's a shift operator, handle it.
5985   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
5986   unsigned ShiftImm = 0;
5987   if (Parser.getTok().is(AsmToken::Comma)) {
5988     Parser.Lex(); // Eat the ','.
5989     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
5990       return true;
5991   }
5992 
5993   // Now we should have the closing ']'
5994   if (Parser.getTok().isNot(AsmToken::RBrac))
5995     return Error(Parser.getTok().getLoc(), "']' expected");
5996   E = Parser.getTok().getEndLoc();
5997   Parser.Lex(); // Eat right bracket token.
5998 
5999   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
6000                                            ShiftType, ShiftImm, 0, isNegative,
6001                                            S, E));
6002 
6003   // If there's a pre-indexing writeback marker, '!', just add it as a token
6004   // operand.
6005   if (Parser.getTok().is(AsmToken::Exclaim)) {
6006     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
6007     Parser.Lex(); // Eat the '!'.
6008   }
6009 
6010   return false;
6011 }
6012 
6013 /// parseMemRegOffsetShift - one of these two:
6014 ///   ( lsl | lsr | asr | ror ) , # shift_amount
6015 ///   rrx
6016 /// return true if it parses a shift otherwise it returns false.
parseMemRegOffsetShift(ARM_AM::ShiftOpc & St,unsigned & Amount)6017 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
6018                                           unsigned &Amount) {
6019   MCAsmParser &Parser = getParser();
6020   SMLoc Loc = Parser.getTok().getLoc();
6021   const AsmToken &Tok = Parser.getTok();
6022   if (Tok.isNot(AsmToken::Identifier))
6023     return Error(Loc, "illegal shift operator");
6024   StringRef ShiftName = Tok.getString();
6025   if (ShiftName == "lsl" || ShiftName == "LSL" ||
6026       ShiftName == "asl" || ShiftName == "ASL")
6027     St = ARM_AM::lsl;
6028   else if (ShiftName == "lsr" || ShiftName == "LSR")
6029     St = ARM_AM::lsr;
6030   else if (ShiftName == "asr" || ShiftName == "ASR")
6031     St = ARM_AM::asr;
6032   else if (ShiftName == "ror" || ShiftName == "ROR")
6033     St = ARM_AM::ror;
6034   else if (ShiftName == "rrx" || ShiftName == "RRX")
6035     St = ARM_AM::rrx;
6036   else if (ShiftName == "uxtw" || ShiftName == "UXTW")
6037     St = ARM_AM::uxtw;
6038   else
6039     return Error(Loc, "illegal shift operator");
6040   Parser.Lex(); // Eat shift type token.
6041 
6042   // rrx stands alone.
6043   Amount = 0;
6044   if (St != ARM_AM::rrx) {
6045     Loc = Parser.getTok().getLoc();
6046     // A '#' and a shift amount.
6047     const AsmToken &HashTok = Parser.getTok();
6048     if (HashTok.isNot(AsmToken::Hash) &&
6049         HashTok.isNot(AsmToken::Dollar))
6050       return Error(HashTok.getLoc(), "'#' expected");
6051     Parser.Lex(); // Eat hash token.
6052 
6053     const MCExpr *Expr;
6054     if (getParser().parseExpression(Expr))
6055       return true;
6056     // Range check the immediate.
6057     // lsl, ror: 0 <= imm <= 31
6058     // lsr, asr: 0 <= imm <= 32
6059     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
6060     if (!CE)
6061       return Error(Loc, "shift amount must be an immediate");
6062     int64_t Imm = CE->getValue();
6063     if (Imm < 0 ||
6064         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
6065         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
6066       return Error(Loc, "immediate shift value out of range");
6067     // If <ShiftTy> #0, turn it into a no_shift.
6068     if (Imm == 0)
6069       St = ARM_AM::lsl;
6070     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
6071     if (Imm == 32)
6072       Imm = 0;
6073     Amount = Imm;
6074   }
6075 
6076   return false;
6077 }
6078 
6079 /// parseFPImm - A floating point immediate expression operand.
6080 OperandMatchResultTy
parseFPImm(OperandVector & Operands)6081 ARMAsmParser::parseFPImm(OperandVector &Operands) {
6082   MCAsmParser &Parser = getParser();
6083   // Anything that can accept a floating point constant as an operand
6084   // needs to go through here, as the regular parseExpression is
6085   // integer only.
6086   //
6087   // This routine still creates a generic Immediate operand, containing
6088   // a bitcast of the 64-bit floating point value. The various operands
6089   // that accept floats can check whether the value is valid for them
6090   // via the standard is*() predicates.
6091 
6092   SMLoc S = Parser.getTok().getLoc();
6093 
6094   if (Parser.getTok().isNot(AsmToken::Hash) &&
6095       Parser.getTok().isNot(AsmToken::Dollar))
6096     return MatchOperand_NoMatch;
6097 
6098   // Disambiguate the VMOV forms that can accept an FP immediate.
6099   // vmov.f32 <sreg>, #imm
6100   // vmov.f64 <dreg>, #imm
6101   // vmov.f32 <dreg>, #imm  @ vector f32x2
6102   // vmov.f32 <qreg>, #imm  @ vector f32x4
6103   //
6104   // There are also the NEON VMOV instructions which expect an
6105   // integer constant. Make sure we don't try to parse an FPImm
6106   // for these:
6107   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
6108   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
6109   bool isVmovf = TyOp.isToken() &&
6110                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64" ||
6111                   TyOp.getToken() == ".f16");
6112   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
6113   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
6114                                          Mnemonic.getToken() == "fconsts");
6115   if (!(isVmovf || isFconst))
6116     return MatchOperand_NoMatch;
6117 
6118   Parser.Lex(); // Eat '#' or '$'.
6119 
6120   // Handle negation, as that still comes through as a separate token.
6121   bool isNegative = false;
6122   if (Parser.getTok().is(AsmToken::Minus)) {
6123     isNegative = true;
6124     Parser.Lex();
6125   }
6126   const AsmToken &Tok = Parser.getTok();
6127   SMLoc Loc = Tok.getLoc();
6128   if (Tok.is(AsmToken::Real) && isVmovf) {
6129     APFloat RealVal(APFloat::IEEEsingle(), Tok.getString());
6130     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
6131     // If we had a '-' in front, toggle the sign bit.
6132     IntVal ^= (uint64_t)isNegative << 31;
6133     Parser.Lex(); // Eat the token.
6134     Operands.push_back(ARMOperand::CreateImm(
6135           MCConstantExpr::create(IntVal, getContext()),
6136           S, Parser.getTok().getLoc()));
6137     return MatchOperand_Success;
6138   }
6139   // Also handle plain integers. Instructions which allow floating point
6140   // immediates also allow a raw encoded 8-bit value.
6141   if (Tok.is(AsmToken::Integer) && isFconst) {
6142     int64_t Val = Tok.getIntVal();
6143     Parser.Lex(); // Eat the token.
6144     if (Val > 255 || Val < 0) {
6145       Error(Loc, "encoded floating point value out of range");
6146       return MatchOperand_ParseFail;
6147     }
6148     float RealVal = ARM_AM::getFPImmFloat(Val);
6149     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
6150 
6151     Operands.push_back(ARMOperand::CreateImm(
6152         MCConstantExpr::create(Val, getContext()), S,
6153         Parser.getTok().getLoc()));
6154     return MatchOperand_Success;
6155   }
6156 
6157   Error(Loc, "invalid floating point immediate");
6158   return MatchOperand_ParseFail;
6159 }
6160 
6161 /// Parse a arm instruction operand.  For now this parses the operand regardless
6162 /// of the mnemonic.
parseOperand(OperandVector & Operands,StringRef Mnemonic)6163 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
6164   MCAsmParser &Parser = getParser();
6165   SMLoc S, E;
6166 
6167   // Check if the current operand has a custom associated parser, if so, try to
6168   // custom parse the operand, or fallback to the general approach.
6169   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
6170   if (ResTy == MatchOperand_Success)
6171     return false;
6172   // If there wasn't a custom match, try the generic matcher below. Otherwise,
6173   // there was a match, but an error occurred, in which case, just return that
6174   // the operand parsing failed.
6175   if (ResTy == MatchOperand_ParseFail)
6176     return true;
6177 
6178   switch (getLexer().getKind()) {
6179   default:
6180     Error(Parser.getTok().getLoc(), "unexpected token in operand");
6181     return true;
6182   case AsmToken::Identifier: {
6183     // If we've seen a branch mnemonic, the next operand must be a label.  This
6184     // is true even if the label is a register name.  So "br r1" means branch to
6185     // label "r1".
6186     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
6187     if (!ExpectLabel) {
6188       if (!tryParseRegisterWithWriteBack(Operands))
6189         return false;
6190       int Res = tryParseShiftRegister(Operands);
6191       if (Res == 0) // success
6192         return false;
6193       else if (Res == -1) // irrecoverable error
6194         return true;
6195       // If this is VMRS, check for the apsr_nzcv operand.
6196       if (Mnemonic == "vmrs" &&
6197           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
6198         S = Parser.getTok().getLoc();
6199         Parser.Lex();
6200         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
6201         return false;
6202       }
6203     }
6204 
6205     // Fall though for the Identifier case that is not a register or a
6206     // special name.
6207     LLVM_FALLTHROUGH;
6208   }
6209   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
6210   case AsmToken::Integer: // things like 1f and 2b as a branch targets
6211   case AsmToken::String:  // quoted label names.
6212   case AsmToken::Dot: {   // . as a branch target
6213     // This was not a register so parse other operands that start with an
6214     // identifier (like labels) as expressions and create them as immediates.
6215     const MCExpr *IdVal;
6216     S = Parser.getTok().getLoc();
6217     if (getParser().parseExpression(IdVal))
6218       return true;
6219     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6220     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
6221     return false;
6222   }
6223   case AsmToken::LBrac:
6224     return parseMemory(Operands);
6225   case AsmToken::LCurly:
6226     return parseRegisterList(Operands, !Mnemonic.startswith("clr"));
6227   case AsmToken::Dollar:
6228   case AsmToken::Hash: {
6229     // #42 -> immediate
6230     // $ 42 -> immediate
6231     // $foo -> symbol name
6232     // $42 -> symbol name
6233     S = Parser.getTok().getLoc();
6234 
6235     // Favor the interpretation of $-prefixed operands as symbol names.
6236     // Cases where immediates are explicitly expected are handled by their
6237     // specific ParseMethod implementations.
6238     auto AdjacentToken = getLexer().peekTok(/*ShouldSkipSpace=*/false);
6239     bool ExpectIdentifier = Parser.getTok().is(AsmToken::Dollar) &&
6240                             (AdjacentToken.is(AsmToken::Identifier) ||
6241                              AdjacentToken.is(AsmToken::Integer));
6242     if (!ExpectIdentifier) {
6243       // Token is not part of identifier. Drop leading $ or # before parsing
6244       // expression.
6245       Parser.Lex();
6246     }
6247 
6248     if (Parser.getTok().isNot(AsmToken::Colon)) {
6249       bool IsNegative = Parser.getTok().is(AsmToken::Minus);
6250       const MCExpr *ImmVal;
6251       if (getParser().parseExpression(ImmVal))
6252         return true;
6253       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
6254       if (CE) {
6255         int32_t Val = CE->getValue();
6256         if (IsNegative && Val == 0)
6257           ImmVal = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
6258                                           getContext());
6259       }
6260       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6261       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
6262 
6263       // There can be a trailing '!' on operands that we want as a separate
6264       // '!' Token operand. Handle that here. For example, the compatibility
6265       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
6266       if (Parser.getTok().is(AsmToken::Exclaim)) {
6267         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
6268                                                    Parser.getTok().getLoc()));
6269         Parser.Lex(); // Eat exclaim token
6270       }
6271       return false;
6272     }
6273     // w/ a ':' after the '#', it's just like a plain ':'.
6274     LLVM_FALLTHROUGH;
6275   }
6276   case AsmToken::Colon: {
6277     S = Parser.getTok().getLoc();
6278     // ":lower16:" and ":upper16:" expression prefixes
6279     // FIXME: Check it's an expression prefix,
6280     // e.g. (FOO - :lower16:BAR) isn't legal.
6281     ARMMCExpr::VariantKind RefKind;
6282     if (parsePrefix(RefKind))
6283       return true;
6284 
6285     const MCExpr *SubExprVal;
6286     if (getParser().parseExpression(SubExprVal))
6287       return true;
6288 
6289     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
6290                                               getContext());
6291     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6292     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
6293     return false;
6294   }
6295   case AsmToken::Equal: {
6296     S = Parser.getTok().getLoc();
6297     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
6298       return Error(S, "unexpected token in operand");
6299     Parser.Lex(); // Eat '='
6300     const MCExpr *SubExprVal;
6301     if (getParser().parseExpression(SubExprVal))
6302       return true;
6303     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6304 
6305     // execute-only: we assume that assembly programmers know what they are
6306     // doing and allow literal pool creation here
6307     Operands.push_back(ARMOperand::CreateConstantPoolImm(SubExprVal, S, E));
6308     return false;
6309   }
6310   }
6311 }
6312 
6313 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
6314 //  :lower16: and :upper16:.
parsePrefix(ARMMCExpr::VariantKind & RefKind)6315 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
6316   MCAsmParser &Parser = getParser();
6317   RefKind = ARMMCExpr::VK_ARM_None;
6318 
6319   // consume an optional '#' (GNU compatibility)
6320   if (getLexer().is(AsmToken::Hash))
6321     Parser.Lex();
6322 
6323   // :lower16: and :upper16: modifiers
6324   assert(getLexer().is(AsmToken::Colon) && "expected a :");
6325   Parser.Lex(); // Eat ':'
6326 
6327   if (getLexer().isNot(AsmToken::Identifier)) {
6328     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
6329     return true;
6330   }
6331 
6332   enum {
6333     COFF = (1 << MCContext::IsCOFF),
6334     ELF = (1 << MCContext::IsELF),
6335     MACHO = (1 << MCContext::IsMachO),
6336     WASM = (1 << MCContext::IsWasm),
6337   };
6338   static const struct PrefixEntry {
6339     const char *Spelling;
6340     ARMMCExpr::VariantKind VariantKind;
6341     uint8_t SupportedFormats;
6342   } PrefixEntries[] = {
6343     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
6344     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
6345   };
6346 
6347   StringRef IDVal = Parser.getTok().getIdentifier();
6348 
6349   const auto &Prefix =
6350       llvm::find_if(PrefixEntries, [&IDVal](const PrefixEntry &PE) {
6351         return PE.Spelling == IDVal;
6352       });
6353   if (Prefix == std::end(PrefixEntries)) {
6354     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
6355     return true;
6356   }
6357 
6358   uint8_t CurrentFormat;
6359   switch (getContext().getObjectFileType()) {
6360   case MCContext::IsMachO:
6361     CurrentFormat = MACHO;
6362     break;
6363   case MCContext::IsELF:
6364     CurrentFormat = ELF;
6365     break;
6366   case MCContext::IsCOFF:
6367     CurrentFormat = COFF;
6368     break;
6369   case MCContext::IsWasm:
6370     CurrentFormat = WASM;
6371     break;
6372   case MCContext::IsXCOFF:
6373     llvm_unreachable("unexpected object format");
6374     break;
6375   }
6376 
6377   if (~Prefix->SupportedFormats & CurrentFormat) {
6378     Error(Parser.getTok().getLoc(),
6379           "cannot represent relocation in the current file format");
6380     return true;
6381   }
6382 
6383   RefKind = Prefix->VariantKind;
6384   Parser.Lex();
6385 
6386   if (getLexer().isNot(AsmToken::Colon)) {
6387     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
6388     return true;
6389   }
6390   Parser.Lex(); // Eat the last ':'
6391 
6392   return false;
6393 }
6394 
6395 /// Given a mnemonic, split out possible predication code and carry
6396 /// setting letters to form a canonical mnemonic and flags.
6397 //
6398 // FIXME: Would be nice to autogen this.
6399 // FIXME: This is a bit of a maze of special cases.
splitMnemonic(StringRef Mnemonic,StringRef ExtraToken,unsigned & PredicationCode,unsigned & VPTPredicationCode,bool & CarrySetting,unsigned & ProcessorIMod,StringRef & ITMask)6400 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
6401                                       StringRef ExtraToken,
6402                                       unsigned &PredicationCode,
6403                                       unsigned &VPTPredicationCode,
6404                                       bool &CarrySetting,
6405                                       unsigned &ProcessorIMod,
6406                                       StringRef &ITMask) {
6407   PredicationCode = ARMCC::AL;
6408   VPTPredicationCode = ARMVCC::None;
6409   CarrySetting = false;
6410   ProcessorIMod = 0;
6411 
6412   // Ignore some mnemonics we know aren't predicated forms.
6413   //
6414   // FIXME: Would be nice to autogen this.
6415   if ((Mnemonic == "movs" && isThumb()) ||
6416       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
6417       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
6418       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
6419       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
6420       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
6421       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
6422       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
6423       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
6424       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
6425       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
6426       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
6427       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
6428       Mnemonic.startswith("vsel") || Mnemonic == "vins" || Mnemonic == "vmovx" ||
6429       Mnemonic == "bxns"  || Mnemonic == "blxns" ||
6430       Mnemonic == "vdot"  || Mnemonic == "vmmla"  ||
6431       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
6432       Mnemonic == "vcmla" || Mnemonic == "vcadd" ||
6433       Mnemonic == "vfmal" || Mnemonic == "vfmsl" ||
6434       Mnemonic == "wls" || Mnemonic == "le" || Mnemonic == "dls" ||
6435       Mnemonic == "csel" || Mnemonic == "csinc" ||
6436       Mnemonic == "csinv" || Mnemonic == "csneg" || Mnemonic == "cinc" ||
6437       Mnemonic == "cinv" || Mnemonic == "cneg" || Mnemonic == "cset" ||
6438       Mnemonic == "csetm")
6439     return Mnemonic;
6440 
6441   // First, split out any predication code. Ignore mnemonics we know aren't
6442   // predicated but do have a carry-set and so weren't caught above.
6443   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
6444       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
6445       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
6446       Mnemonic != "sbcs" && Mnemonic != "rscs" &&
6447       !(hasMVE() &&
6448         (Mnemonic == "vmine" ||
6449          Mnemonic == "vshle" || Mnemonic == "vshlt" || Mnemonic == "vshllt" ||
6450          Mnemonic == "vrshle" || Mnemonic == "vrshlt" ||
6451          Mnemonic == "vmvne" || Mnemonic == "vorne" ||
6452          Mnemonic == "vnege" || Mnemonic == "vnegt" ||
6453          Mnemonic == "vmule" || Mnemonic == "vmult" ||
6454          Mnemonic == "vrintne" ||
6455          Mnemonic == "vcmult" || Mnemonic == "vcmule" ||
6456          Mnemonic == "vpsele" || Mnemonic == "vpselt" ||
6457          Mnemonic.startswith("vq")))) {
6458     unsigned CC = ARMCondCodeFromString(Mnemonic.substr(Mnemonic.size()-2));
6459     if (CC != ~0U) {
6460       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
6461       PredicationCode = CC;
6462     }
6463   }
6464 
6465   // Next, determine if we have a carry setting bit. We explicitly ignore all
6466   // the instructions we know end in 's'.
6467   if (Mnemonic.endswith("s") &&
6468       !(Mnemonic == "cps" || Mnemonic == "mls" ||
6469         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
6470         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
6471         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
6472         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
6473         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
6474         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
6475         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
6476         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
6477         Mnemonic == "bxns" || Mnemonic == "blxns" || Mnemonic == "vfmas" ||
6478         Mnemonic == "vmlas" ||
6479         (Mnemonic == "movs" && isThumb()))) {
6480     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
6481     CarrySetting = true;
6482   }
6483 
6484   // The "cps" instruction can have a interrupt mode operand which is glued into
6485   // the mnemonic. Check if this is the case, split it and parse the imod op
6486   if (Mnemonic.startswith("cps")) {
6487     // Split out any imod code.
6488     unsigned IMod =
6489       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
6490       .Case("ie", ARM_PROC::IE)
6491       .Case("id", ARM_PROC::ID)
6492       .Default(~0U);
6493     if (IMod != ~0U) {
6494       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
6495       ProcessorIMod = IMod;
6496     }
6497   }
6498 
6499   if (isMnemonicVPTPredicable(Mnemonic, ExtraToken) && Mnemonic != "vmovlt" &&
6500       Mnemonic != "vshllt" && Mnemonic != "vrshrnt" && Mnemonic != "vshrnt" &&
6501       Mnemonic != "vqrshrunt" && Mnemonic != "vqshrunt" &&
6502       Mnemonic != "vqrshrnt" && Mnemonic != "vqshrnt" && Mnemonic != "vmullt" &&
6503       Mnemonic != "vqmovnt" && Mnemonic != "vqmovunt" &&
6504       Mnemonic != "vqmovnt" && Mnemonic != "vmovnt" && Mnemonic != "vqdmullt" &&
6505       Mnemonic != "vpnot" && Mnemonic != "vcvtt" && Mnemonic != "vcvt") {
6506     unsigned CC = ARMVectorCondCodeFromString(Mnemonic.substr(Mnemonic.size()-1));
6507     if (CC != ~0U) {
6508       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-1);
6509       VPTPredicationCode = CC;
6510     }
6511     return Mnemonic;
6512   }
6513 
6514   // The "it" instruction has the condition mask on the end of the mnemonic.
6515   if (Mnemonic.startswith("it")) {
6516     ITMask = Mnemonic.slice(2, Mnemonic.size());
6517     Mnemonic = Mnemonic.slice(0, 2);
6518   }
6519 
6520   if (Mnemonic.startswith("vpst")) {
6521     ITMask = Mnemonic.slice(4, Mnemonic.size());
6522     Mnemonic = Mnemonic.slice(0, 4);
6523   }
6524   else if (Mnemonic.startswith("vpt")) {
6525     ITMask = Mnemonic.slice(3, Mnemonic.size());
6526     Mnemonic = Mnemonic.slice(0, 3);
6527   }
6528 
6529   return Mnemonic;
6530 }
6531 
6532 /// Given a canonical mnemonic, determine if the instruction ever allows
6533 /// inclusion of carry set or predication code operands.
6534 //
6535 // FIXME: It would be nice to autogen this.
getMnemonicAcceptInfo(StringRef Mnemonic,StringRef ExtraToken,StringRef FullInst,bool & CanAcceptCarrySet,bool & CanAcceptPredicationCode,bool & CanAcceptVPTPredicationCode)6536 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic,
6537                                          StringRef ExtraToken,
6538                                          StringRef FullInst,
6539                                          bool &CanAcceptCarrySet,
6540                                          bool &CanAcceptPredicationCode,
6541                                          bool &CanAcceptVPTPredicationCode) {
6542   CanAcceptVPTPredicationCode = isMnemonicVPTPredicable(Mnemonic, ExtraToken);
6543 
6544   CanAcceptCarrySet =
6545       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
6546       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
6547       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
6548       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
6549       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
6550       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
6551       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
6552       (!isThumb() &&
6553        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
6554         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
6555 
6556   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
6557       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
6558       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
6559       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
6560       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
6561       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
6562       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
6563       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
6564       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
6565       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
6566       (FullInst.startswith("vmull") && FullInst.endswith(".p64")) ||
6567       Mnemonic == "vmovx" || Mnemonic == "vins" ||
6568       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
6569       Mnemonic == "vcmla" || Mnemonic == "vcadd" ||
6570       Mnemonic == "vfmal" || Mnemonic == "vfmsl" ||
6571       Mnemonic == "vfmat" || Mnemonic == "vfmab" ||
6572       Mnemonic == "vdot"  || Mnemonic == "vmmla" ||
6573       Mnemonic == "sb"    || Mnemonic == "ssbb"  ||
6574       Mnemonic == "pssbb" || Mnemonic == "vsmmla" ||
6575       Mnemonic == "vummla" || Mnemonic == "vusmmla" ||
6576       Mnemonic == "vusdot" || Mnemonic == "vsudot" ||
6577       Mnemonic == "bfcsel" || Mnemonic == "wls" ||
6578       Mnemonic == "dls" || Mnemonic == "le" || Mnemonic == "csel" ||
6579       Mnemonic == "csinc" || Mnemonic == "csinv" || Mnemonic == "csneg" ||
6580       Mnemonic == "cinc" || Mnemonic == "cinv" || Mnemonic == "cneg" ||
6581       Mnemonic == "cset" || Mnemonic == "csetm" ||
6582       Mnemonic.startswith("vpt") || Mnemonic.startswith("vpst") ||
6583       (hasCDE() && MS.isCDEInstr(Mnemonic) &&
6584        !MS.isITPredicableCDEInstr(Mnemonic)) ||
6585       (hasMVE() &&
6586        (Mnemonic.startswith("vst2") || Mnemonic.startswith("vld2") ||
6587         Mnemonic.startswith("vst4") || Mnemonic.startswith("vld4") ||
6588         Mnemonic.startswith("wlstp") || Mnemonic.startswith("dlstp") ||
6589         Mnemonic.startswith("letp")))) {
6590     // These mnemonics are never predicable
6591     CanAcceptPredicationCode = false;
6592   } else if (!isThumb()) {
6593     // Some instructions are only predicable in Thumb mode
6594     CanAcceptPredicationCode =
6595         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
6596         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
6597         Mnemonic != "dmb" && Mnemonic != "dfb" && Mnemonic != "dsb" &&
6598         Mnemonic != "isb" && Mnemonic != "pld" && Mnemonic != "pli" &&
6599         Mnemonic != "pldw" && Mnemonic != "ldc2" && Mnemonic != "ldc2l" &&
6600         Mnemonic != "stc2" && Mnemonic != "stc2l" &&
6601         Mnemonic != "tsb" &&
6602         !Mnemonic.startswith("rfe") && !Mnemonic.startswith("srs");
6603   } else if (isThumbOne()) {
6604     if (hasV6MOps())
6605       CanAcceptPredicationCode = Mnemonic != "movs";
6606     else
6607       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
6608   } else
6609     CanAcceptPredicationCode = true;
6610 }
6611 
6612 // Some Thumb instructions have two operand forms that are not
6613 // available as three operand, convert to two operand form if possible.
6614 //
6615 // FIXME: We would really like to be able to tablegen'erate this.
tryConvertingToTwoOperandForm(StringRef Mnemonic,bool CarrySetting,OperandVector & Operands)6616 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
6617                                                  bool CarrySetting,
6618                                                  OperandVector &Operands) {
6619   if (Operands.size() != 6)
6620     return;
6621 
6622   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6623         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
6624   if (!Op3.isReg() || !Op4.isReg())
6625     return;
6626 
6627   auto Op3Reg = Op3.getReg();
6628   auto Op4Reg = Op4.getReg();
6629 
6630   // For most Thumb2 cases we just generate the 3 operand form and reduce
6631   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
6632   // won't accept SP or PC so we do the transformation here taking care
6633   // with immediate range in the 'add sp, sp #imm' case.
6634   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
6635   if (isThumbTwo()) {
6636     if (Mnemonic != "add")
6637       return;
6638     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
6639                         (Op5.isReg() && Op5.getReg() == ARM::PC);
6640     if (!TryTransform) {
6641       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
6642                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
6643                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
6644                        Op5.isImm() && !Op5.isImm0_508s4());
6645     }
6646     if (!TryTransform)
6647       return;
6648   } else if (!isThumbOne())
6649     return;
6650 
6651   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
6652         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
6653         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
6654         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
6655     return;
6656 
6657   // If first 2 operands of a 3 operand instruction are the same
6658   // then transform to 2 operand version of the same instruction
6659   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
6660   bool Transform = Op3Reg == Op4Reg;
6661 
6662   // For communtative operations, we might be able to transform if we swap
6663   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
6664   // as tADDrsp.
6665   const ARMOperand *LastOp = &Op5;
6666   bool Swap = false;
6667   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
6668       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
6669        Mnemonic == "and" || Mnemonic == "eor" ||
6670        Mnemonic == "adc" || Mnemonic == "orr")) {
6671     Swap = true;
6672     LastOp = &Op4;
6673     Transform = true;
6674   }
6675 
6676   // If both registers are the same then remove one of them from
6677   // the operand list, with certain exceptions.
6678   if (Transform) {
6679     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
6680     // 2 operand forms don't exist.
6681     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
6682         LastOp->isReg())
6683       Transform = false;
6684 
6685     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
6686     // 3-bits because the ARMARM says not to.
6687     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
6688       Transform = false;
6689   }
6690 
6691   if (Transform) {
6692     if (Swap)
6693       std::swap(Op4, Op5);
6694     Operands.erase(Operands.begin() + 3);
6695   }
6696 }
6697 
shouldOmitCCOutOperand(StringRef Mnemonic,OperandVector & Operands)6698 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
6699                                           OperandVector &Operands) {
6700   // FIXME: This is all horribly hacky. We really need a better way to deal
6701   // with optional operands like this in the matcher table.
6702 
6703   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
6704   // another does not. Specifically, the MOVW instruction does not. So we
6705   // special case it here and remove the defaulted (non-setting) cc_out
6706   // operand if that's the instruction we're trying to match.
6707   //
6708   // We do this as post-processing of the explicit operands rather than just
6709   // conditionally adding the cc_out in the first place because we need
6710   // to check the type of the parsed immediate operand.
6711   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
6712       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
6713       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
6714       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
6715     return true;
6716 
6717   // Register-register 'add' for thumb does not have a cc_out operand
6718   // when there are only two register operands.
6719   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
6720       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6721       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6722       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
6723     return true;
6724   // Register-register 'add' for thumb does not have a cc_out operand
6725   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
6726   // have to check the immediate range here since Thumb2 has a variant
6727   // that can handle a different range and has a cc_out operand.
6728   if (((isThumb() && Mnemonic == "add") ||
6729        (isThumbTwo() && Mnemonic == "sub")) &&
6730       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6731       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6732       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
6733       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6734       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
6735        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
6736     return true;
6737   // For Thumb2, add/sub immediate does not have a cc_out operand for the
6738   // imm0_4095 variant. That's the least-preferred variant when
6739   // selecting via the generic "add" mnemonic, so to know that we
6740   // should remove the cc_out operand, we have to explicitly check that
6741   // it's not one of the other variants. Ugh.
6742   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
6743       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6744       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6745       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
6746     // Nest conditions rather than one big 'if' statement for readability.
6747     //
6748     // If both registers are low, we're in an IT block, and the immediate is
6749     // in range, we should use encoding T1 instead, which has a cc_out.
6750     if (inITBlock() &&
6751         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
6752         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
6753         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
6754       return false;
6755     // Check against T3. If the second register is the PC, this is an
6756     // alternate form of ADR, which uses encoding T4, so check for that too.
6757     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
6758         (static_cast<ARMOperand &>(*Operands[5]).isT2SOImm() ||
6759          static_cast<ARMOperand &>(*Operands[5]).isT2SOImmNeg()))
6760       return false;
6761 
6762     // Otherwise, we use encoding T4, which does not have a cc_out
6763     // operand.
6764     return true;
6765   }
6766 
6767   // The thumb2 multiply instruction doesn't have a CCOut register, so
6768   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
6769   // use the 16-bit encoding or not.
6770   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
6771       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6772       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6773       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6774       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
6775       // If the registers aren't low regs, the destination reg isn't the
6776       // same as one of the source regs, or the cc_out operand is zero
6777       // outside of an IT block, we have to use the 32-bit encoding, so
6778       // remove the cc_out operand.
6779       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
6780        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
6781        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
6782        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
6783                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
6784                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
6785                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
6786     return true;
6787 
6788   // Also check the 'mul' syntax variant that doesn't specify an explicit
6789   // destination register.
6790   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
6791       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6792       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6793       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6794       // If the registers aren't low regs  or the cc_out operand is zero
6795       // outside of an IT block, we have to use the 32-bit encoding, so
6796       // remove the cc_out operand.
6797       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
6798        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
6799        !inITBlock()))
6800     return true;
6801 
6802   // Register-register 'add/sub' for thumb does not have a cc_out operand
6803   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
6804   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
6805   // right, this will result in better diagnostics (which operand is off)
6806   // anyway.
6807   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
6808       (Operands.size() == 5 || Operands.size() == 6) &&
6809       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6810       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
6811       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6812       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
6813        (Operands.size() == 6 &&
6814         static_cast<ARMOperand &>(*Operands[5]).isImm()))) {
6815     // Thumb2 (add|sub){s}{p}.w GPRnopc, sp, #{T2SOImm} has cc_out
6816     return (!(isThumbTwo() &&
6817               (static_cast<ARMOperand &>(*Operands[4]).isT2SOImm() ||
6818                static_cast<ARMOperand &>(*Operands[4]).isT2SOImmNeg())));
6819   }
6820   // Fixme: Should join all the thumb+thumb2 (add|sub) in a single if case
6821   // Thumb2 ADD r0, #4095 -> ADDW r0, r0, #4095 (T4)
6822   // Thumb2 SUB r0, #4095 -> SUBW r0, r0, #4095
6823   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
6824       (Operands.size() == 5) &&
6825       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6826       static_cast<ARMOperand &>(*Operands[3]).getReg() != ARM::SP &&
6827       static_cast<ARMOperand &>(*Operands[3]).getReg() != ARM::PC &&
6828       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6829       static_cast<ARMOperand &>(*Operands[4]).isImm()) {
6830     const ARMOperand &IMM = static_cast<ARMOperand &>(*Operands[4]);
6831     if (IMM.isT2SOImm() || IMM.isT2SOImmNeg())
6832       return false; // add.w / sub.w
6833     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IMM.getImm())) {
6834       const int64_t Value = CE->getValue();
6835       // Thumb1 imm8 sub / add
6836       if ((Value < ((1 << 7) - 1) << 2) && inITBlock() && (!(Value & 3)) &&
6837           isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()))
6838         return false;
6839       return true; // Thumb2 T4 addw / subw
6840     }
6841   }
6842   return false;
6843 }
6844 
shouldOmitPredicateOperand(StringRef Mnemonic,OperandVector & Operands)6845 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
6846                                               OperandVector &Operands) {
6847   // VRINT{Z, X} have a predicate operand in VFP, but not in NEON
6848   unsigned RegIdx = 3;
6849   if ((((Mnemonic == "vrintz" || Mnemonic == "vrintx") && !hasMVE()) ||
6850       Mnemonic == "vrintr") &&
6851       (static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32" ||
6852        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f16")) {
6853     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6854         (static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32" ||
6855          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f16"))
6856       RegIdx = 4;
6857 
6858     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
6859         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
6860              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
6861          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
6862              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
6863       return true;
6864   }
6865   return false;
6866 }
6867 
shouldOmitVectorPredicateOperand(StringRef Mnemonic,OperandVector & Operands)6868 bool ARMAsmParser::shouldOmitVectorPredicateOperand(StringRef Mnemonic,
6869                                                     OperandVector &Operands) {
6870   if (!hasMVE() || Operands.size() < 3)
6871     return true;
6872 
6873   if (Mnemonic.startswith("vld2") || Mnemonic.startswith("vld4") ||
6874       Mnemonic.startswith("vst2") || Mnemonic.startswith("vst4"))
6875     return true;
6876 
6877   if (Mnemonic.startswith("vctp") || Mnemonic.startswith("vpnot"))
6878     return false;
6879 
6880   if (Mnemonic.startswith("vmov") &&
6881       !(Mnemonic.startswith("vmovl") || Mnemonic.startswith("vmovn") ||
6882         Mnemonic.startswith("vmovx"))) {
6883     for (auto &Operand : Operands) {
6884       if (static_cast<ARMOperand &>(*Operand).isVectorIndex() ||
6885           ((*Operand).isReg() &&
6886            (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(
6887              (*Operand).getReg()) ||
6888             ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
6889               (*Operand).getReg())))) {
6890         return true;
6891       }
6892     }
6893     return false;
6894   } else {
6895     for (auto &Operand : Operands) {
6896       // We check the larger class QPR instead of just the legal class
6897       // MQPR, to more accurately report errors when using Q registers
6898       // outside of the allowed range.
6899       if (static_cast<ARMOperand &>(*Operand).isVectorIndex() ||
6900           (Operand->isReg() &&
6901            (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
6902              Operand->getReg()))))
6903         return false;
6904     }
6905     return true;
6906   }
6907 }
6908 
isDataTypeToken(StringRef Tok)6909 static bool isDataTypeToken(StringRef Tok) {
6910   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
6911     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
6912     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
6913     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
6914     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
6915     Tok == ".f" || Tok == ".d";
6916 }
6917 
6918 // FIXME: This bit should probably be handled via an explicit match class
6919 // in the .td files that matches the suffix instead of having it be
6920 // a literal string token the way it is now.
doesIgnoreDataTypeSuffix(StringRef Mnemonic,StringRef DT)6921 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
6922   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
6923 }
6924 
6925 static void applyMnemonicAliases(StringRef &Mnemonic,
6926                                  const FeatureBitset &Features,
6927                                  unsigned VariantID);
6928 
6929 // The GNU assembler has aliases of ldrd and strd with the second register
6930 // omitted. We don't have a way to do that in tablegen, so fix it up here.
6931 //
6932 // We have to be careful to not emit an invalid Rt2 here, because the rest of
6933 // the assembly parser could then generate confusing diagnostics refering to
6934 // it. If we do find anything that prevents us from doing the transformation we
6935 // bail out, and let the assembly parser report an error on the instruction as
6936 // it is written.
fixupGNULDRDAlias(StringRef Mnemonic,OperandVector & Operands)6937 void ARMAsmParser::fixupGNULDRDAlias(StringRef Mnemonic,
6938                                      OperandVector &Operands) {
6939   if (Mnemonic != "ldrd" && Mnemonic != "strd")
6940     return;
6941   if (Operands.size() < 4)
6942     return;
6943 
6944   ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
6945   ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6946 
6947   if (!Op2.isReg())
6948     return;
6949   if (!Op3.isGPRMem())
6950     return;
6951 
6952   const MCRegisterClass &GPR = MRI->getRegClass(ARM::GPRRegClassID);
6953   if (!GPR.contains(Op2.getReg()))
6954     return;
6955 
6956   unsigned RtEncoding = MRI->getEncodingValue(Op2.getReg());
6957   if (!isThumb() && (RtEncoding & 1)) {
6958     // In ARM mode, the registers must be from an aligned pair, this
6959     // restriction does not apply in Thumb mode.
6960     return;
6961   }
6962   if (Op2.getReg() == ARM::PC)
6963     return;
6964   unsigned PairedReg = GPR.getRegister(RtEncoding + 1);
6965   if (!PairedReg || PairedReg == ARM::PC ||
6966       (PairedReg == ARM::SP && !hasV8Ops()))
6967     return;
6968 
6969   Operands.insert(
6970       Operands.begin() + 3,
6971       ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
6972 }
6973 
6974 // Dual-register instruction have the following syntax:
6975 // <mnemonic> <predicate>? <coproc>, <Rdest>, <Rdest+1>, <Rsrc>, ..., #imm
6976 // This function tries to remove <Rdest+1> and replace <Rdest> with a pair
6977 // operand. If the conversion fails an error is diagnosed, and the function
6978 // returns true.
CDEConvertDualRegOperand(StringRef Mnemonic,OperandVector & Operands)6979 bool ARMAsmParser::CDEConvertDualRegOperand(StringRef Mnemonic,
6980                                             OperandVector &Operands) {
6981   assert(MS.isCDEDualRegInstr(Mnemonic));
6982   bool isPredicable =
6983       Mnemonic == "cx1da" || Mnemonic == "cx2da" || Mnemonic == "cx3da";
6984   size_t NumPredOps = isPredicable ? 1 : 0;
6985 
6986   if (Operands.size() <= 3 + NumPredOps)
6987     return false;
6988 
6989   StringRef Op2Diag(
6990       "operand must be an even-numbered register in the range [r0, r10]");
6991 
6992   const MCParsedAsmOperand &Op2 = *Operands[2 + NumPredOps];
6993   if (!Op2.isReg())
6994     return Error(Op2.getStartLoc(), Op2Diag);
6995 
6996   unsigned RNext;
6997   unsigned RPair;
6998   switch (Op2.getReg()) {
6999   default:
7000     return Error(Op2.getStartLoc(), Op2Diag);
7001   case ARM::R0:
7002     RNext = ARM::R1;
7003     RPair = ARM::R0_R1;
7004     break;
7005   case ARM::R2:
7006     RNext = ARM::R3;
7007     RPair = ARM::R2_R3;
7008     break;
7009   case ARM::R4:
7010     RNext = ARM::R5;
7011     RPair = ARM::R4_R5;
7012     break;
7013   case ARM::R6:
7014     RNext = ARM::R7;
7015     RPair = ARM::R6_R7;
7016     break;
7017   case ARM::R8:
7018     RNext = ARM::R9;
7019     RPair = ARM::R8_R9;
7020     break;
7021   case ARM::R10:
7022     RNext = ARM::R11;
7023     RPair = ARM::R10_R11;
7024     break;
7025   }
7026 
7027   const MCParsedAsmOperand &Op3 = *Operands[3 + NumPredOps];
7028   if (!Op3.isReg() || Op3.getReg() != RNext)
7029     return Error(Op3.getStartLoc(), "operand must be a consecutive register");
7030 
7031   Operands.erase(Operands.begin() + 3 + NumPredOps);
7032   Operands[2 + NumPredOps] =
7033       ARMOperand::CreateReg(RPair, Op2.getStartLoc(), Op2.getEndLoc());
7034   return false;
7035 }
7036 
7037 /// Parse an arm instruction mnemonic followed by its operands.
ParseInstruction(ParseInstructionInfo & Info,StringRef Name,SMLoc NameLoc,OperandVector & Operands)7038 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
7039                                     SMLoc NameLoc, OperandVector &Operands) {
7040   MCAsmParser &Parser = getParser();
7041 
7042   // Apply mnemonic aliases before doing anything else, as the destination
7043   // mnemonic may include suffices and we want to handle them normally.
7044   // The generic tblgen'erated code does this later, at the start of
7045   // MatchInstructionImpl(), but that's too late for aliases that include
7046   // any sort of suffix.
7047   const FeatureBitset &AvailableFeatures = getAvailableFeatures();
7048   unsigned AssemblerDialect = getParser().getAssemblerDialect();
7049   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
7050 
7051   // First check for the ARM-specific .req directive.
7052   if (Parser.getTok().is(AsmToken::Identifier) &&
7053       Parser.getTok().getIdentifier().lower() == ".req") {
7054     parseDirectiveReq(Name, NameLoc);
7055     // We always return 'error' for this, as we're done with this
7056     // statement and don't need to match the 'instruction."
7057     return true;
7058   }
7059 
7060   // Create the leading tokens for the mnemonic, split by '.' characters.
7061   size_t Start = 0, Next = Name.find('.');
7062   StringRef Mnemonic = Name.slice(Start, Next);
7063   StringRef ExtraToken = Name.slice(Next, Name.find(' ', Next + 1));
7064 
7065   // Split out the predication code and carry setting flag from the mnemonic.
7066   unsigned PredicationCode;
7067   unsigned VPTPredicationCode;
7068   unsigned ProcessorIMod;
7069   bool CarrySetting;
7070   StringRef ITMask;
7071   Mnemonic = splitMnemonic(Mnemonic, ExtraToken, PredicationCode, VPTPredicationCode,
7072                            CarrySetting, ProcessorIMod, ITMask);
7073 
7074   // In Thumb1, only the branch (B) instruction can be predicated.
7075   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
7076     return Error(NameLoc, "conditional execution not supported in Thumb1");
7077   }
7078 
7079   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
7080 
7081   // Handle the mask for IT and VPT instructions. In ARMOperand and
7082   // MCOperand, this is stored in a format independent of the
7083   // condition code: the lowest set bit indicates the end of the
7084   // encoding, and above that, a 1 bit indicates 'else', and an 0
7085   // indicates 'then'. E.g.
7086   //    IT    -> 1000
7087   //    ITx   -> x100    (ITT -> 0100, ITE -> 1100)
7088   //    ITxy  -> xy10    (e.g. ITET -> 1010)
7089   //    ITxyz -> xyz1    (e.g. ITEET -> 1101)
7090   // Note: See the ARM::PredBlockMask enum in
7091   //   /lib/Target/ARM/Utils/ARMBaseInfo.h
7092   if (Mnemonic == "it" || Mnemonic.startswith("vpt") ||
7093       Mnemonic.startswith("vpst")) {
7094     SMLoc Loc = Mnemonic == "it"  ? SMLoc::getFromPointer(NameLoc.getPointer() + 2) :
7095                 Mnemonic == "vpt" ? SMLoc::getFromPointer(NameLoc.getPointer() + 3) :
7096                                     SMLoc::getFromPointer(NameLoc.getPointer() + 4);
7097     if (ITMask.size() > 3) {
7098       if (Mnemonic == "it")
7099         return Error(Loc, "too many conditions on IT instruction");
7100       return Error(Loc, "too many conditions on VPT instruction");
7101     }
7102     unsigned Mask = 8;
7103     for (unsigned i = ITMask.size(); i != 0; --i) {
7104       char pos = ITMask[i - 1];
7105       if (pos != 't' && pos != 'e') {
7106         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
7107       }
7108       Mask >>= 1;
7109       if (ITMask[i - 1] == 'e')
7110         Mask |= 8;
7111     }
7112     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
7113   }
7114 
7115   // FIXME: This is all a pretty gross hack. We should automatically handle
7116   // optional operands like this via tblgen.
7117 
7118   // Next, add the CCOut and ConditionCode operands, if needed.
7119   //
7120   // For mnemonics which can ever incorporate a carry setting bit or predication
7121   // code, our matching model involves us always generating CCOut and
7122   // ConditionCode operands to match the mnemonic "as written" and then we let
7123   // the matcher deal with finding the right instruction or generating an
7124   // appropriate error.
7125   bool CanAcceptCarrySet, CanAcceptPredicationCode, CanAcceptVPTPredicationCode;
7126   getMnemonicAcceptInfo(Mnemonic, ExtraToken, Name, CanAcceptCarrySet,
7127                         CanAcceptPredicationCode, CanAcceptVPTPredicationCode);
7128 
7129   // If we had a carry-set on an instruction that can't do that, issue an
7130   // error.
7131   if (!CanAcceptCarrySet && CarrySetting) {
7132     return Error(NameLoc, "instruction '" + Mnemonic +
7133                  "' can not set flags, but 's' suffix specified");
7134   }
7135   // If we had a predication code on an instruction that can't do that, issue an
7136   // error.
7137   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
7138     return Error(NameLoc, "instruction '" + Mnemonic +
7139                  "' is not predicable, but condition code specified");
7140   }
7141 
7142   // If we had a VPT predication code on an instruction that can't do that, issue an
7143   // error.
7144   if (!CanAcceptVPTPredicationCode && VPTPredicationCode != ARMVCC::None) {
7145     return Error(NameLoc, "instruction '" + Mnemonic +
7146                  "' is not VPT predicable, but VPT code T/E is specified");
7147   }
7148 
7149   // Add the carry setting operand, if necessary.
7150   if (CanAcceptCarrySet) {
7151     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
7152     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
7153                                                Loc));
7154   }
7155 
7156   // Add the predication code operand, if necessary.
7157   if (CanAcceptPredicationCode) {
7158     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
7159                                       CarrySetting);
7160     Operands.push_back(ARMOperand::CreateCondCode(
7161                        ARMCC::CondCodes(PredicationCode), Loc));
7162   }
7163 
7164   // Add the VPT predication code operand, if necessary.
7165   // FIXME: We don't add them for the instructions filtered below as these can
7166   // have custom operands which need special parsing.  This parsing requires
7167   // the operand to be in the same place in the OperandVector as their
7168   // definition in tblgen.  Since these instructions may also have the
7169   // scalar predication operand we do not add the vector one and leave until
7170   // now to fix it up.
7171   if (CanAcceptVPTPredicationCode && Mnemonic != "vmov" &&
7172       !Mnemonic.startswith("vcmp") &&
7173       !(Mnemonic.startswith("vcvt") && Mnemonic != "vcvta" &&
7174         Mnemonic != "vcvtn" && Mnemonic != "vcvtp" && Mnemonic != "vcvtm")) {
7175     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
7176                                       CarrySetting);
7177     Operands.push_back(ARMOperand::CreateVPTPred(
7178                          ARMVCC::VPTCodes(VPTPredicationCode), Loc));
7179   }
7180 
7181   // Add the processor imod operand, if necessary.
7182   if (ProcessorIMod) {
7183     Operands.push_back(ARMOperand::CreateImm(
7184           MCConstantExpr::create(ProcessorIMod, getContext()),
7185                                  NameLoc, NameLoc));
7186   } else if (Mnemonic == "cps" && isMClass()) {
7187     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
7188   }
7189 
7190   // Add the remaining tokens in the mnemonic.
7191   while (Next != StringRef::npos) {
7192     Start = Next;
7193     Next = Name.find('.', Start + 1);
7194     ExtraToken = Name.slice(Start, Next);
7195 
7196     // Some NEON instructions have an optional datatype suffix that is
7197     // completely ignored. Check for that.
7198     if (isDataTypeToken(ExtraToken) &&
7199         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
7200       continue;
7201 
7202     // For for ARM mode generate an error if the .n qualifier is used.
7203     if (ExtraToken == ".n" && !isThumb()) {
7204       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
7205       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
7206                    "arm mode");
7207     }
7208 
7209     // The .n qualifier is always discarded as that is what the tables
7210     // and matcher expect.  In ARM mode the .w qualifier has no effect,
7211     // so discard it to avoid errors that can be caused by the matcher.
7212     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
7213       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
7214       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
7215     }
7216   }
7217 
7218   // Read the remaining operands.
7219   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7220     // Read the first operand.
7221     if (parseOperand(Operands, Mnemonic)) {
7222       return true;
7223     }
7224 
7225     while (parseOptionalToken(AsmToken::Comma)) {
7226       // Parse and remember the operand.
7227       if (parseOperand(Operands, Mnemonic)) {
7228         return true;
7229       }
7230     }
7231   }
7232 
7233   if (parseToken(AsmToken::EndOfStatement, "unexpected token in argument list"))
7234     return true;
7235 
7236   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
7237 
7238   if (hasCDE() && MS.isCDEInstr(Mnemonic)) {
7239     // Dual-register instructions use even-odd register pairs as their
7240     // destination operand, in assembly such pair is spelled as two
7241     // consecutive registers, without any special syntax. ConvertDualRegOperand
7242     // tries to convert such operand into register pair, e.g. r2, r3 -> r2_r3.
7243     // It returns true, if an error message has been emitted. If the function
7244     // returns false, the function either succeeded or an error (e.g. missing
7245     // operand) will be diagnosed elsewhere.
7246     if (MS.isCDEDualRegInstr(Mnemonic)) {
7247       bool GotError = CDEConvertDualRegOperand(Mnemonic, Operands);
7248       if (GotError)
7249         return GotError;
7250     }
7251   }
7252 
7253   // Some instructions, mostly Thumb, have forms for the same mnemonic that
7254   // do and don't have a cc_out optional-def operand. With some spot-checks
7255   // of the operand list, we can figure out which variant we're trying to
7256   // parse and adjust accordingly before actually matching. We shouldn't ever
7257   // try to remove a cc_out operand that was explicitly set on the
7258   // mnemonic, of course (CarrySetting == true). Reason number #317 the
7259   // table driven matcher doesn't fit well with the ARM instruction set.
7260   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
7261     Operands.erase(Operands.begin() + 1);
7262 
7263   // Some instructions have the same mnemonic, but don't always
7264   // have a predicate. Distinguish them here and delete the
7265   // appropriate predicate if needed.  This could be either the scalar
7266   // predication code or the vector predication code.
7267   if (PredicationCode == ARMCC::AL &&
7268       shouldOmitPredicateOperand(Mnemonic, Operands))
7269     Operands.erase(Operands.begin() + 1);
7270 
7271 
7272   if (hasMVE()) {
7273     if (!shouldOmitVectorPredicateOperand(Mnemonic, Operands) &&
7274         Mnemonic == "vmov" && PredicationCode == ARMCC::LT) {
7275       // Very nasty hack to deal with the vector predicated variant of vmovlt
7276       // the scalar predicated vmov with condition 'lt'.  We can not tell them
7277       // apart until we have parsed their operands.
7278       Operands.erase(Operands.begin() + 1);
7279       Operands.erase(Operands.begin());
7280       SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
7281       SMLoc PLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
7282                                          Mnemonic.size() - 1 + CarrySetting);
7283       Operands.insert(Operands.begin(),
7284                       ARMOperand::CreateVPTPred(ARMVCC::None, PLoc));
7285       Operands.insert(Operands.begin(),
7286                       ARMOperand::CreateToken(StringRef("vmovlt"), MLoc));
7287     } else if (Mnemonic == "vcvt" && PredicationCode == ARMCC::NE &&
7288                !shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
7289       // Another nasty hack to deal with the ambiguity between vcvt with scalar
7290       // predication 'ne' and vcvtn with vector predication 'e'.  As above we
7291       // can only distinguish between the two after we have parsed their
7292       // operands.
7293       Operands.erase(Operands.begin() + 1);
7294       Operands.erase(Operands.begin());
7295       SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
7296       SMLoc PLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
7297                                          Mnemonic.size() - 1 + CarrySetting);
7298       Operands.insert(Operands.begin(),
7299                       ARMOperand::CreateVPTPred(ARMVCC::Else, PLoc));
7300       Operands.insert(Operands.begin(),
7301                       ARMOperand::CreateToken(StringRef("vcvtn"), MLoc));
7302     } else if (Mnemonic == "vmul" && PredicationCode == ARMCC::LT &&
7303                !shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
7304       // Another hack, this time to distinguish between scalar predicated vmul
7305       // with 'lt' predication code and the vector instruction vmullt with
7306       // vector predication code "none"
7307       Operands.erase(Operands.begin() + 1);
7308       Operands.erase(Operands.begin());
7309       SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
7310       Operands.insert(Operands.begin(),
7311                       ARMOperand::CreateToken(StringRef("vmullt"), MLoc));
7312     }
7313     // For vmov and vcmp, as mentioned earlier, we did not add the vector
7314     // predication code, since these may contain operands that require
7315     // special parsing.  So now we have to see if they require vector
7316     // predication and replace the scalar one with the vector predication
7317     // operand if that is the case.
7318     else if (Mnemonic == "vmov" || Mnemonic.startswith("vcmp") ||
7319              (Mnemonic.startswith("vcvt") && !Mnemonic.startswith("vcvta") &&
7320               !Mnemonic.startswith("vcvtn") && !Mnemonic.startswith("vcvtp") &&
7321               !Mnemonic.startswith("vcvtm"))) {
7322       if (!shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
7323         // We could not split the vector predicate off vcvt because it might
7324         // have been the scalar vcvtt instruction.  Now we know its a vector
7325         // instruction, we still need to check whether its the vector
7326         // predicated vcvt with 'Then' predication or the vector vcvtt.  We can
7327         // distinguish the two based on the suffixes, if it is any of
7328         // ".f16.f32", ".f32.f16", ".f16.f64" or ".f64.f16" then it is the vcvtt.
7329         if (Mnemonic.startswith("vcvtt") && Operands.size() >= 4) {
7330           auto Sz1 = static_cast<ARMOperand &>(*Operands[2]);
7331           auto Sz2 = static_cast<ARMOperand &>(*Operands[3]);
7332           if (!(Sz1.isToken() && Sz1.getToken().startswith(".f") &&
7333               Sz2.isToken() && Sz2.getToken().startswith(".f"))) {
7334             Operands.erase(Operands.begin());
7335             SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
7336             VPTPredicationCode = ARMVCC::Then;
7337 
7338             Mnemonic = Mnemonic.substr(0, 4);
7339             Operands.insert(Operands.begin(),
7340                             ARMOperand::CreateToken(Mnemonic, MLoc));
7341           }
7342         }
7343         Operands.erase(Operands.begin() + 1);
7344         SMLoc PLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
7345                                           Mnemonic.size() + CarrySetting);
7346         Operands.insert(Operands.begin() + 1,
7347                         ARMOperand::CreateVPTPred(
7348                             ARMVCC::VPTCodes(VPTPredicationCode), PLoc));
7349       }
7350     } else if (CanAcceptVPTPredicationCode) {
7351       // For all other instructions, make sure only one of the two
7352       // predication operands is left behind, depending on whether we should
7353       // use the vector predication.
7354       if (shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
7355         if (CanAcceptPredicationCode)
7356           Operands.erase(Operands.begin() + 2);
7357         else
7358           Operands.erase(Operands.begin() + 1);
7359       } else if (CanAcceptPredicationCode && PredicationCode == ARMCC::AL) {
7360         Operands.erase(Operands.begin() + 1);
7361       }
7362     }
7363   }
7364 
7365   if (VPTPredicationCode != ARMVCC::None) {
7366     bool usedVPTPredicationCode = false;
7367     for (unsigned I = 1; I < Operands.size(); ++I)
7368       if (static_cast<ARMOperand &>(*Operands[I]).isVPTPred())
7369         usedVPTPredicationCode = true;
7370     if (!usedVPTPredicationCode) {
7371       // If we have a VPT predication code and we haven't just turned it
7372       // into an operand, then it was a mistake for splitMnemonic to
7373       // separate it from the rest of the mnemonic in the first place,
7374       // and this may lead to wrong disassembly (e.g. scalar floating
7375       // point VCMPE is actually a different instruction from VCMP, so
7376       // we mustn't treat them the same). In that situation, glue it
7377       // back on.
7378       Mnemonic = Name.slice(0, Mnemonic.size() + 1);
7379       Operands.erase(Operands.begin());
7380       Operands.insert(Operands.begin(),
7381                       ARMOperand::CreateToken(Mnemonic, NameLoc));
7382     }
7383   }
7384 
7385     // ARM mode 'blx' need special handling, as the register operand version
7386     // is predicable, but the label operand version is not. So, we can't rely
7387     // on the Mnemonic based checking to correctly figure out when to put
7388     // a k_CondCode operand in the list. If we're trying to match the label
7389     // version, remove the k_CondCode operand here.
7390     if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
7391         static_cast<ARMOperand &>(*Operands[2]).isImm())
7392       Operands.erase(Operands.begin() + 1);
7393 
7394     // Adjust operands of ldrexd/strexd to MCK_GPRPair.
7395     // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
7396     // a single GPRPair reg operand is used in the .td file to replace the two
7397     // GPRs. However, when parsing from asm, the two GRPs cannot be
7398     // automatically
7399     // expressed as a GPRPair, so we have to manually merge them.
7400     // FIXME: We would really like to be able to tablegen'erate this.
7401     if (!isThumb() && Operands.size() > 4 &&
7402         (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
7403          Mnemonic == "stlexd")) {
7404       bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
7405       unsigned Idx = isLoad ? 2 : 3;
7406       ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
7407       ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
7408 
7409       const MCRegisterClass &MRC = MRI->getRegClass(ARM::GPRRegClassID);
7410       // Adjust only if Op1 and Op2 are GPRs.
7411       if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
7412           MRC.contains(Op2.getReg())) {
7413         unsigned Reg1 = Op1.getReg();
7414         unsigned Reg2 = Op2.getReg();
7415         unsigned Rt = MRI->getEncodingValue(Reg1);
7416         unsigned Rt2 = MRI->getEncodingValue(Reg2);
7417 
7418         // Rt2 must be Rt + 1 and Rt must be even.
7419         if (Rt + 1 != Rt2 || (Rt & 1)) {
7420           return Error(Op2.getStartLoc(),
7421                        isLoad ? "destination operands must be sequential"
7422                               : "source operands must be sequential");
7423         }
7424         unsigned NewReg = MRI->getMatchingSuperReg(
7425             Reg1, ARM::gsub_0, &(MRI->getRegClass(ARM::GPRPairRegClassID)));
7426         Operands[Idx] =
7427             ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
7428         Operands.erase(Operands.begin() + Idx + 1);
7429       }
7430   }
7431 
7432   // GNU Assembler extension (compatibility).
7433   fixupGNULDRDAlias(Mnemonic, Operands);
7434 
7435   // FIXME: As said above, this is all a pretty gross hack.  This instruction
7436   // does not fit with other "subs" and tblgen.
7437   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
7438   // so the Mnemonic is the original name "subs" and delete the predicate
7439   // operand so it will match the table entry.
7440   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
7441       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
7442       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
7443       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
7444       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
7445       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
7446     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
7447     Operands.erase(Operands.begin() + 1);
7448   }
7449   return false;
7450 }
7451 
7452 // Validate context-sensitive operand constraints.
7453 
7454 // return 'true' if register list contains non-low GPR registers,
7455 // 'false' otherwise. If Reg is in the register list or is HiReg, set
7456 // 'containsReg' to true.
checkLowRegisterList(const MCInst & Inst,unsigned OpNo,unsigned Reg,unsigned HiReg,bool & containsReg)7457 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
7458                                  unsigned Reg, unsigned HiReg,
7459                                  bool &containsReg) {
7460   containsReg = false;
7461   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
7462     unsigned OpReg = Inst.getOperand(i).getReg();
7463     if (OpReg == Reg)
7464       containsReg = true;
7465     // Anything other than a low register isn't legal here.
7466     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
7467       return true;
7468   }
7469   return false;
7470 }
7471 
7472 // Check if the specified regisgter is in the register list of the inst,
7473 // starting at the indicated operand number.
listContainsReg(const MCInst & Inst,unsigned OpNo,unsigned Reg)7474 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
7475   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
7476     unsigned OpReg = Inst.getOperand(i).getReg();
7477     if (OpReg == Reg)
7478       return true;
7479   }
7480   return false;
7481 }
7482 
7483 // Return true if instruction has the interesting property of being
7484 // allowed in IT blocks, but not being predicable.
instIsBreakpoint(const MCInst & Inst)7485 static bool instIsBreakpoint(const MCInst &Inst) {
7486     return Inst.getOpcode() == ARM::tBKPT ||
7487            Inst.getOpcode() == ARM::BKPT ||
7488            Inst.getOpcode() == ARM::tHLT ||
7489            Inst.getOpcode() == ARM::HLT;
7490 }
7491 
validatetLDMRegList(const MCInst & Inst,const OperandVector & Operands,unsigned ListNo,bool IsARPop)7492 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
7493                                        const OperandVector &Operands,
7494                                        unsigned ListNo, bool IsARPop) {
7495   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
7496   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
7497 
7498   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
7499   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
7500   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
7501 
7502   if (!IsARPop && ListContainsSP)
7503     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7504                  "SP may not be in the register list");
7505   else if (ListContainsPC && ListContainsLR)
7506     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7507                  "PC and LR may not be in the register list simultaneously");
7508   return false;
7509 }
7510 
validatetSTMRegList(const MCInst & Inst,const OperandVector & Operands,unsigned ListNo)7511 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
7512                                        const OperandVector &Operands,
7513                                        unsigned ListNo) {
7514   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
7515   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
7516 
7517   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
7518   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
7519 
7520   if (ListContainsSP && ListContainsPC)
7521     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7522                  "SP and PC may not be in the register list");
7523   else if (ListContainsSP)
7524     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7525                  "SP may not be in the register list");
7526   else if (ListContainsPC)
7527     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7528                  "PC may not be in the register list");
7529   return false;
7530 }
7531 
validateLDRDSTRD(MCInst & Inst,const OperandVector & Operands,bool Load,bool ARMMode,bool Writeback)7532 bool ARMAsmParser::validateLDRDSTRD(MCInst &Inst,
7533                                     const OperandVector &Operands,
7534                                     bool Load, bool ARMMode, bool Writeback) {
7535   unsigned RtIndex = Load || !Writeback ? 0 : 1;
7536   unsigned Rt = MRI->getEncodingValue(Inst.getOperand(RtIndex).getReg());
7537   unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(RtIndex + 1).getReg());
7538 
7539   if (ARMMode) {
7540     // Rt can't be R14.
7541     if (Rt == 14)
7542       return Error(Operands[3]->getStartLoc(),
7543                   "Rt can't be R14");
7544 
7545     // Rt must be even-numbered.
7546     if ((Rt & 1) == 1)
7547       return Error(Operands[3]->getStartLoc(),
7548                    "Rt must be even-numbered");
7549 
7550     // Rt2 must be Rt + 1.
7551     if (Rt2 != Rt + 1) {
7552       if (Load)
7553         return Error(Operands[3]->getStartLoc(),
7554                      "destination operands must be sequential");
7555       else
7556         return Error(Operands[3]->getStartLoc(),
7557                      "source operands must be sequential");
7558     }
7559 
7560     // FIXME: Diagnose m == 15
7561     // FIXME: Diagnose ldrd with m == t || m == t2.
7562   }
7563 
7564   if (!ARMMode && Load) {
7565     if (Rt2 == Rt)
7566       return Error(Operands[3]->getStartLoc(),
7567                    "destination operands can't be identical");
7568   }
7569 
7570   if (Writeback) {
7571     unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
7572 
7573     if (Rn == Rt || Rn == Rt2) {
7574       if (Load)
7575         return Error(Operands[3]->getStartLoc(),
7576                      "base register needs to be different from destination "
7577                      "registers");
7578       else
7579         return Error(Operands[3]->getStartLoc(),
7580                      "source register and base register can't be identical");
7581     }
7582 
7583     // FIXME: Diagnose ldrd/strd with writeback and n == 15.
7584     // (Except the immediate form of ldrd?)
7585   }
7586 
7587   return false;
7588 }
7589 
findFirstVectorPredOperandIdx(const MCInstrDesc & MCID)7590 static int findFirstVectorPredOperandIdx(const MCInstrDesc &MCID) {
7591   for (unsigned i = 0; i < MCID.NumOperands; ++i) {
7592     if (ARM::isVpred(MCID.OpInfo[i].OperandType))
7593       return i;
7594   }
7595   return -1;
7596 }
7597 
isVectorPredicable(const MCInstrDesc & MCID)7598 static bool isVectorPredicable(const MCInstrDesc &MCID) {
7599   return findFirstVectorPredOperandIdx(MCID) != -1;
7600 }
7601 
7602 // FIXME: We would really like to be able to tablegen'erate this.
validateInstruction(MCInst & Inst,const OperandVector & Operands)7603 bool ARMAsmParser::validateInstruction(MCInst &Inst,
7604                                        const OperandVector &Operands) {
7605   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
7606   SMLoc Loc = Operands[0]->getStartLoc();
7607 
7608   // Check the IT block state first.
7609   // NOTE: BKPT and HLT instructions have the interesting property of being
7610   // allowed in IT blocks, but not being predicable. They just always execute.
7611   if (inITBlock() && !instIsBreakpoint(Inst)) {
7612     // The instruction must be predicable.
7613     if (!MCID.isPredicable())
7614       return Error(Loc, "instructions in IT block must be predicable");
7615     ARMCC::CondCodes Cond = ARMCC::CondCodes(
7616         Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm());
7617     if (Cond != currentITCond()) {
7618       // Find the condition code Operand to get its SMLoc information.
7619       SMLoc CondLoc;
7620       for (unsigned I = 1; I < Operands.size(); ++I)
7621         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
7622           CondLoc = Operands[I]->getStartLoc();
7623       return Error(CondLoc, "incorrect condition in IT block; got '" +
7624                                 StringRef(ARMCondCodeToString(Cond)) +
7625                                 "', but expected '" +
7626                                 ARMCondCodeToString(currentITCond()) + "'");
7627     }
7628   // Check for non-'al' condition codes outside of the IT block.
7629   } else if (isThumbTwo() && MCID.isPredicable() &&
7630              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
7631              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
7632              Inst.getOpcode() != ARM::t2Bcc &&
7633              Inst.getOpcode() != ARM::t2BFic) {
7634     return Error(Loc, "predicated instructions must be in IT block");
7635   } else if (!isThumb() && !useImplicitITARM() && MCID.isPredicable() &&
7636              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
7637                  ARMCC::AL) {
7638     return Warning(Loc, "predicated instructions should be in IT block");
7639   } else if (!MCID.isPredicable()) {
7640     // Check the instruction doesn't have a predicate operand anyway
7641     // that it's not allowed to use. Sometimes this happens in order
7642     // to keep instructions the same shape even though one cannot
7643     // legally be predicated, e.g. vmul.f16 vs vmul.f32.
7644     for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i) {
7645       if (MCID.OpInfo[i].isPredicate()) {
7646         if (Inst.getOperand(i).getImm() != ARMCC::AL)
7647           return Error(Loc, "instruction is not predicable");
7648         break;
7649       }
7650     }
7651   }
7652 
7653   // PC-setting instructions in an IT block, but not the last instruction of
7654   // the block, are UNPREDICTABLE.
7655   if (inExplicitITBlock() && !lastInITBlock() && isITBlockTerminator(Inst)) {
7656     return Error(Loc, "instruction must be outside of IT block or the last instruction in an IT block");
7657   }
7658 
7659   if (inVPTBlock() && !instIsBreakpoint(Inst)) {
7660     unsigned Bit = extractITMaskBit(VPTState.Mask, VPTState.CurPosition);
7661     if (!isVectorPredicable(MCID))
7662       return Error(Loc, "instruction in VPT block must be predicable");
7663     unsigned Pred = Inst.getOperand(findFirstVectorPredOperandIdx(MCID)).getImm();
7664     unsigned VPTPred = Bit ? ARMVCC::Else : ARMVCC::Then;
7665     if (Pred != VPTPred) {
7666       SMLoc PredLoc;
7667       for (unsigned I = 1; I < Operands.size(); ++I)
7668         if (static_cast<ARMOperand &>(*Operands[I]).isVPTPred())
7669           PredLoc = Operands[I]->getStartLoc();
7670       return Error(PredLoc, "incorrect predication in VPT block; got '" +
7671                    StringRef(ARMVPTPredToString(ARMVCC::VPTCodes(Pred))) +
7672                    "', but expected '" +
7673                    ARMVPTPredToString(ARMVCC::VPTCodes(VPTPred)) + "'");
7674     }
7675   }
7676   else if (isVectorPredicable(MCID) &&
7677            Inst.getOperand(findFirstVectorPredOperandIdx(MCID)).getImm() !=
7678            ARMVCC::None)
7679     return Error(Loc, "VPT predicated instructions must be in VPT block");
7680 
7681   const unsigned Opcode = Inst.getOpcode();
7682   switch (Opcode) {
7683   case ARM::t2IT: {
7684     // Encoding is unpredictable if it ever results in a notional 'NV'
7685     // predicate. Since we don't parse 'NV' directly this means an 'AL'
7686     // predicate with an "else" mask bit.
7687     unsigned Cond = Inst.getOperand(0).getImm();
7688     unsigned Mask = Inst.getOperand(1).getImm();
7689 
7690     // Conditions only allowing a 't' are those with no set bit except
7691     // the lowest-order one that indicates the end of the sequence. In
7692     // other words, powers of 2.
7693     if (Cond == ARMCC::AL && countPopulation(Mask) != 1)
7694       return Error(Loc, "unpredictable IT predicate sequence");
7695     break;
7696   }
7697   case ARM::LDRD:
7698     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/true,
7699                          /*Writeback*/false))
7700       return true;
7701     break;
7702   case ARM::LDRD_PRE:
7703   case ARM::LDRD_POST:
7704     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/true,
7705                          /*Writeback*/true))
7706       return true;
7707     break;
7708   case ARM::t2LDRDi8:
7709     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/false,
7710                          /*Writeback*/false))
7711       return true;
7712     break;
7713   case ARM::t2LDRD_PRE:
7714   case ARM::t2LDRD_POST:
7715     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/false,
7716                          /*Writeback*/true))
7717       return true;
7718     break;
7719   case ARM::t2BXJ: {
7720     const unsigned RmReg = Inst.getOperand(0).getReg();
7721     // Rm = SP is no longer unpredictable in v8-A
7722     if (RmReg == ARM::SP && !hasV8Ops())
7723       return Error(Operands[2]->getStartLoc(),
7724                    "r13 (SP) is an unpredictable operand to BXJ");
7725     return false;
7726   }
7727   case ARM::STRD:
7728     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/true,
7729                          /*Writeback*/false))
7730       return true;
7731     break;
7732   case ARM::STRD_PRE:
7733   case ARM::STRD_POST:
7734     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/true,
7735                          /*Writeback*/true))
7736       return true;
7737     break;
7738   case ARM::t2STRD_PRE:
7739   case ARM::t2STRD_POST:
7740     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/false,
7741                          /*Writeback*/true))
7742       return true;
7743     break;
7744   case ARM::STR_PRE_IMM:
7745   case ARM::STR_PRE_REG:
7746   case ARM::t2STR_PRE:
7747   case ARM::STR_POST_IMM:
7748   case ARM::STR_POST_REG:
7749   case ARM::t2STR_POST:
7750   case ARM::STRH_PRE:
7751   case ARM::t2STRH_PRE:
7752   case ARM::STRH_POST:
7753   case ARM::t2STRH_POST:
7754   case ARM::STRB_PRE_IMM:
7755   case ARM::STRB_PRE_REG:
7756   case ARM::t2STRB_PRE:
7757   case ARM::STRB_POST_IMM:
7758   case ARM::STRB_POST_REG:
7759   case ARM::t2STRB_POST: {
7760     // Rt must be different from Rn.
7761     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
7762     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
7763 
7764     if (Rt == Rn)
7765       return Error(Operands[3]->getStartLoc(),
7766                    "source register and base register can't be identical");
7767     return false;
7768   }
7769   case ARM::t2LDR_PRE_imm:
7770   case ARM::t2LDR_POST_imm:
7771   case ARM::t2STR_PRE_imm:
7772   case ARM::t2STR_POST_imm: {
7773     // Rt must be different from Rn.
7774     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
7775     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(1).getReg());
7776 
7777     if (Rt == Rn)
7778       return Error(Operands[3]->getStartLoc(),
7779                    "destination register and base register can't be identical");
7780     if (Inst.getOpcode() == ARM::t2LDR_POST_imm ||
7781         Inst.getOpcode() == ARM::t2STR_POST_imm) {
7782       int Imm = Inst.getOperand(2).getImm();
7783       if (Imm > 255 || Imm < -255)
7784         return Error(Operands[5]->getStartLoc(),
7785                      "operand must be in range [-255, 255]");
7786     }
7787     if (Inst.getOpcode() == ARM::t2STR_PRE_imm ||
7788         Inst.getOpcode() == ARM::t2STR_POST_imm) {
7789       if (Inst.getOperand(0).getReg() == ARM::PC) {
7790         return Error(Operands[3]->getStartLoc(),
7791                      "operand must be a register in range [r0, r14]");
7792       }
7793     }
7794     return false;
7795   }
7796   case ARM::LDR_PRE_IMM:
7797   case ARM::LDR_PRE_REG:
7798   case ARM::t2LDR_PRE:
7799   case ARM::LDR_POST_IMM:
7800   case ARM::LDR_POST_REG:
7801   case ARM::t2LDR_POST:
7802   case ARM::LDRH_PRE:
7803   case ARM::t2LDRH_PRE:
7804   case ARM::LDRH_POST:
7805   case ARM::t2LDRH_POST:
7806   case ARM::LDRSH_PRE:
7807   case ARM::t2LDRSH_PRE:
7808   case ARM::LDRSH_POST:
7809   case ARM::t2LDRSH_POST:
7810   case ARM::LDRB_PRE_IMM:
7811   case ARM::LDRB_PRE_REG:
7812   case ARM::t2LDRB_PRE:
7813   case ARM::LDRB_POST_IMM:
7814   case ARM::LDRB_POST_REG:
7815   case ARM::t2LDRB_POST:
7816   case ARM::LDRSB_PRE:
7817   case ARM::t2LDRSB_PRE:
7818   case ARM::LDRSB_POST:
7819   case ARM::t2LDRSB_POST: {
7820     // Rt must be different from Rn.
7821     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
7822     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
7823 
7824     if (Rt == Rn)
7825       return Error(Operands[3]->getStartLoc(),
7826                    "destination register and base register can't be identical");
7827     return false;
7828   }
7829 
7830   case ARM::MVE_VLDRBU8_rq:
7831   case ARM::MVE_VLDRBU16_rq:
7832   case ARM::MVE_VLDRBS16_rq:
7833   case ARM::MVE_VLDRBU32_rq:
7834   case ARM::MVE_VLDRBS32_rq:
7835   case ARM::MVE_VLDRHU16_rq:
7836   case ARM::MVE_VLDRHU16_rq_u:
7837   case ARM::MVE_VLDRHU32_rq:
7838   case ARM::MVE_VLDRHU32_rq_u:
7839   case ARM::MVE_VLDRHS32_rq:
7840   case ARM::MVE_VLDRHS32_rq_u:
7841   case ARM::MVE_VLDRWU32_rq:
7842   case ARM::MVE_VLDRWU32_rq_u:
7843   case ARM::MVE_VLDRDU64_rq:
7844   case ARM::MVE_VLDRDU64_rq_u:
7845   case ARM::MVE_VLDRWU32_qi:
7846   case ARM::MVE_VLDRWU32_qi_pre:
7847   case ARM::MVE_VLDRDU64_qi:
7848   case ARM::MVE_VLDRDU64_qi_pre: {
7849     // Qd must be different from Qm.
7850     unsigned QdIdx = 0, QmIdx = 2;
7851     bool QmIsPointer = false;
7852     switch (Opcode) {
7853     case ARM::MVE_VLDRWU32_qi:
7854     case ARM::MVE_VLDRDU64_qi:
7855       QmIdx = 1;
7856       QmIsPointer = true;
7857       break;
7858     case ARM::MVE_VLDRWU32_qi_pre:
7859     case ARM::MVE_VLDRDU64_qi_pre:
7860       QdIdx = 1;
7861       QmIsPointer = true;
7862       break;
7863     }
7864 
7865     const unsigned Qd = MRI->getEncodingValue(Inst.getOperand(QdIdx).getReg());
7866     const unsigned Qm = MRI->getEncodingValue(Inst.getOperand(QmIdx).getReg());
7867 
7868     if (Qd == Qm) {
7869       return Error(Operands[3]->getStartLoc(),
7870                    Twine("destination vector register and vector ") +
7871                    (QmIsPointer ? "pointer" : "offset") +
7872                    " register can't be identical");
7873     }
7874     return false;
7875   }
7876 
7877   case ARM::SBFX:
7878   case ARM::t2SBFX:
7879   case ARM::UBFX:
7880   case ARM::t2UBFX: {
7881     // Width must be in range [1, 32-lsb].
7882     unsigned LSB = Inst.getOperand(2).getImm();
7883     unsigned Widthm1 = Inst.getOperand(3).getImm();
7884     if (Widthm1 >= 32 - LSB)
7885       return Error(Operands[5]->getStartLoc(),
7886                    "bitfield width must be in range [1,32-lsb]");
7887     return false;
7888   }
7889   // Notionally handles ARM::tLDMIA_UPD too.
7890   case ARM::tLDMIA: {
7891     // If we're parsing Thumb2, the .w variant is available and handles
7892     // most cases that are normally illegal for a Thumb1 LDM instruction.
7893     // We'll make the transformation in processInstruction() if necessary.
7894     //
7895     // Thumb LDM instructions are writeback iff the base register is not
7896     // in the register list.
7897     unsigned Rn = Inst.getOperand(0).getReg();
7898     bool HasWritebackToken =
7899         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
7900          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
7901     bool ListContainsBase;
7902     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
7903       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
7904                    "registers must be in range r0-r7");
7905     // If we should have writeback, then there should be a '!' token.
7906     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
7907       return Error(Operands[2]->getStartLoc(),
7908                    "writeback operator '!' expected");
7909     // If we should not have writeback, there must not be a '!'. This is
7910     // true even for the 32-bit wide encodings.
7911     if (ListContainsBase && HasWritebackToken)
7912       return Error(Operands[3]->getStartLoc(),
7913                    "writeback operator '!' not allowed when base register "
7914                    "in register list");
7915 
7916     if (validatetLDMRegList(Inst, Operands, 3))
7917       return true;
7918     break;
7919   }
7920   case ARM::LDMIA_UPD:
7921   case ARM::LDMDB_UPD:
7922   case ARM::LDMIB_UPD:
7923   case ARM::LDMDA_UPD:
7924     // ARM variants loading and updating the same register are only officially
7925     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
7926     if (!hasV7Ops())
7927       break;
7928     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
7929       return Error(Operands.back()->getStartLoc(),
7930                    "writeback register not allowed in register list");
7931     break;
7932   case ARM::t2LDMIA:
7933   case ARM::t2LDMDB:
7934     if (validatetLDMRegList(Inst, Operands, 3))
7935       return true;
7936     break;
7937   case ARM::t2STMIA:
7938   case ARM::t2STMDB:
7939     if (validatetSTMRegList(Inst, Operands, 3))
7940       return true;
7941     break;
7942   case ARM::t2LDMIA_UPD:
7943   case ARM::t2LDMDB_UPD:
7944   case ARM::t2STMIA_UPD:
7945   case ARM::t2STMDB_UPD:
7946     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
7947       return Error(Operands.back()->getStartLoc(),
7948                    "writeback register not allowed in register list");
7949 
7950     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
7951       if (validatetLDMRegList(Inst, Operands, 3))
7952         return true;
7953     } else {
7954       if (validatetSTMRegList(Inst, Operands, 3))
7955         return true;
7956     }
7957     break;
7958 
7959   case ARM::sysLDMIA_UPD:
7960   case ARM::sysLDMDA_UPD:
7961   case ARM::sysLDMDB_UPD:
7962   case ARM::sysLDMIB_UPD:
7963     if (!listContainsReg(Inst, 3, ARM::PC))
7964       return Error(Operands[4]->getStartLoc(),
7965                    "writeback register only allowed on system LDM "
7966                    "if PC in register-list");
7967     break;
7968   case ARM::sysSTMIA_UPD:
7969   case ARM::sysSTMDA_UPD:
7970   case ARM::sysSTMDB_UPD:
7971   case ARM::sysSTMIB_UPD:
7972     return Error(Operands[2]->getStartLoc(),
7973                  "system STM cannot have writeback register");
7974   case ARM::tMUL:
7975     // The second source operand must be the same register as the destination
7976     // operand.
7977     //
7978     // In this case, we must directly check the parsed operands because the
7979     // cvtThumbMultiply() function is written in such a way that it guarantees
7980     // this first statement is always true for the new Inst.  Essentially, the
7981     // destination is unconditionally copied into the second source operand
7982     // without checking to see if it matches what we actually parsed.
7983     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
7984                                  ((ARMOperand &)*Operands[5]).getReg()) &&
7985         (((ARMOperand &)*Operands[3]).getReg() !=
7986          ((ARMOperand &)*Operands[4]).getReg())) {
7987       return Error(Operands[3]->getStartLoc(),
7988                    "destination register must match source register");
7989     }
7990     break;
7991 
7992   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
7993   // so only issue a diagnostic for thumb1. The instructions will be
7994   // switched to the t2 encodings in processInstruction() if necessary.
7995   case ARM::tPOP: {
7996     bool ListContainsBase;
7997     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
7998         !isThumbTwo())
7999       return Error(Operands[2]->getStartLoc(),
8000                    "registers must be in range r0-r7 or pc");
8001     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
8002       return true;
8003     break;
8004   }
8005   case ARM::tPUSH: {
8006     bool ListContainsBase;
8007     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
8008         !isThumbTwo())
8009       return Error(Operands[2]->getStartLoc(),
8010                    "registers must be in range r0-r7 or lr");
8011     if (validatetSTMRegList(Inst, Operands, 2))
8012       return true;
8013     break;
8014   }
8015   case ARM::tSTMIA_UPD: {
8016     bool ListContainsBase, InvalidLowList;
8017     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
8018                                           0, ListContainsBase);
8019     if (InvalidLowList && !isThumbTwo())
8020       return Error(Operands[4]->getStartLoc(),
8021                    "registers must be in range r0-r7");
8022 
8023     // This would be converted to a 32-bit stm, but that's not valid if the
8024     // writeback register is in the list.
8025     if (InvalidLowList && ListContainsBase)
8026       return Error(Operands[4]->getStartLoc(),
8027                    "writeback operator '!' not allowed when base register "
8028                    "in register list");
8029 
8030     if (validatetSTMRegList(Inst, Operands, 4))
8031       return true;
8032     break;
8033   }
8034   case ARM::tADDrSP:
8035     // If the non-SP source operand and the destination operand are not the
8036     // same, we need thumb2 (for the wide encoding), or we have an error.
8037     if (!isThumbTwo() &&
8038         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
8039       return Error(Operands[4]->getStartLoc(),
8040                    "source register must be the same as destination");
8041     }
8042     break;
8043 
8044   case ARM::t2ADDrr:
8045   case ARM::t2ADDrs:
8046   case ARM::t2SUBrr:
8047   case ARM::t2SUBrs:
8048     if (Inst.getOperand(0).getReg() == ARM::SP &&
8049         Inst.getOperand(1).getReg() != ARM::SP)
8050       return Error(Operands[4]->getStartLoc(),
8051                    "source register must be sp if destination is sp");
8052     break;
8053 
8054   // Final range checking for Thumb unconditional branch instructions.
8055   case ARM::tB:
8056     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
8057       return Error(Operands[2]->getStartLoc(), "branch target out of range");
8058     break;
8059   case ARM::t2B: {
8060     int op = (Operands[2]->isImm()) ? 2 : 3;
8061     ARMOperand &Operand = static_cast<ARMOperand &>(*Operands[op]);
8062     // Delay the checks of symbolic expressions until they are resolved.
8063     if (!isa<MCBinaryExpr>(Operand.getImm()) &&
8064         !Operand.isSignedOffset<24, 1>())
8065       return Error(Operands[op]->getStartLoc(), "branch target out of range");
8066     break;
8067   }
8068   // Final range checking for Thumb conditional branch instructions.
8069   case ARM::tBcc:
8070     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
8071       return Error(Operands[2]->getStartLoc(), "branch target out of range");
8072     break;
8073   case ARM::t2Bcc: {
8074     int Op = (Operands[2]->isImm()) ? 2 : 3;
8075     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
8076       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
8077     break;
8078   }
8079   case ARM::tCBZ:
8080   case ARM::tCBNZ: {
8081     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<6, 1>())
8082       return Error(Operands[2]->getStartLoc(), "branch target out of range");
8083     break;
8084   }
8085   case ARM::MOVi16:
8086   case ARM::MOVTi16:
8087   case ARM::t2MOVi16:
8088   case ARM::t2MOVTi16:
8089     {
8090     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
8091     // especially when we turn it into a movw and the expression <symbol> does
8092     // not have a :lower16: or :upper16 as part of the expression.  We don't
8093     // want the behavior of silently truncating, which can be unexpected and
8094     // lead to bugs that are difficult to find since this is an easy mistake
8095     // to make.
8096     int i = (Operands[3]->isImm()) ? 3 : 4;
8097     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
8098     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
8099     if (CE) break;
8100     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
8101     if (!E) break;
8102     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
8103     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
8104                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
8105       return Error(
8106           Op.getStartLoc(),
8107           "immediate expression for mov requires :lower16: or :upper16");
8108     break;
8109   }
8110   case ARM::HINT:
8111   case ARM::t2HINT: {
8112     unsigned Imm8 = Inst.getOperand(0).getImm();
8113     unsigned Pred = Inst.getOperand(1).getImm();
8114     // ESB is not predicable (pred must be AL). Without the RAS extension, this
8115     // behaves as any other unallocated hint.
8116     if (Imm8 == 0x10 && Pred != ARMCC::AL && hasRAS())
8117       return Error(Operands[1]->getStartLoc(), "instruction 'esb' is not "
8118                                                "predicable, but condition "
8119                                                "code specified");
8120     if (Imm8 == 0x14 && Pred != ARMCC::AL)
8121       return Error(Operands[1]->getStartLoc(), "instruction 'csdb' is not "
8122                                                "predicable, but condition "
8123                                                "code specified");
8124     break;
8125   }
8126   case ARM::t2BFi:
8127   case ARM::t2BFr:
8128   case ARM::t2BFLi:
8129   case ARM::t2BFLr: {
8130     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<4, 1>() ||
8131         (Inst.getOperand(0).isImm() && Inst.getOperand(0).getImm() == 0))
8132       return Error(Operands[2]->getStartLoc(),
8133                    "branch location out of range or not a multiple of 2");
8134 
8135     if (Opcode == ARM::t2BFi) {
8136       if (!static_cast<ARMOperand &>(*Operands[3]).isSignedOffset<16, 1>())
8137         return Error(Operands[3]->getStartLoc(),
8138                      "branch target out of range or not a multiple of 2");
8139     } else if (Opcode == ARM::t2BFLi) {
8140       if (!static_cast<ARMOperand &>(*Operands[3]).isSignedOffset<18, 1>())
8141         return Error(Operands[3]->getStartLoc(),
8142                      "branch target out of range or not a multiple of 2");
8143     }
8144     break;
8145   }
8146   case ARM::t2BFic: {
8147     if (!static_cast<ARMOperand &>(*Operands[1]).isUnsignedOffset<4, 1>() ||
8148         (Inst.getOperand(0).isImm() && Inst.getOperand(0).getImm() == 0))
8149       return Error(Operands[1]->getStartLoc(),
8150                    "branch location out of range or not a multiple of 2");
8151 
8152     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<16, 1>())
8153       return Error(Operands[2]->getStartLoc(),
8154                    "branch target out of range or not a multiple of 2");
8155 
8156     assert(Inst.getOperand(0).isImm() == Inst.getOperand(2).isImm() &&
8157            "branch location and else branch target should either both be "
8158            "immediates or both labels");
8159 
8160     if (Inst.getOperand(0).isImm() && Inst.getOperand(2).isImm()) {
8161       int Diff = Inst.getOperand(2).getImm() - Inst.getOperand(0).getImm();
8162       if (Diff != 4 && Diff != 2)
8163         return Error(
8164             Operands[3]->getStartLoc(),
8165             "else branch target must be 2 or 4 greater than the branch location");
8166     }
8167     break;
8168   }
8169   case ARM::t2CLRM: {
8170     for (unsigned i = 2; i < Inst.getNumOperands(); i++) {
8171       if (Inst.getOperand(i).isReg() &&
8172           !ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(
8173               Inst.getOperand(i).getReg())) {
8174         return Error(Operands[2]->getStartLoc(),
8175                      "invalid register in register list. Valid registers are "
8176                      "r0-r12, lr/r14 and APSR.");
8177       }
8178     }
8179     break;
8180   }
8181   case ARM::DSB:
8182   case ARM::t2DSB: {
8183 
8184     if (Inst.getNumOperands() < 2)
8185       break;
8186 
8187     unsigned Option = Inst.getOperand(0).getImm();
8188     unsigned Pred = Inst.getOperand(1).getImm();
8189 
8190     // SSBB and PSSBB (DSB #0|#4) are not predicable (pred must be AL).
8191     if (Option == 0 && Pred != ARMCC::AL)
8192       return Error(Operands[1]->getStartLoc(),
8193                    "instruction 'ssbb' is not predicable, but condition code "
8194                    "specified");
8195     if (Option == 4 && Pred != ARMCC::AL)
8196       return Error(Operands[1]->getStartLoc(),
8197                    "instruction 'pssbb' is not predicable, but condition code "
8198                    "specified");
8199     break;
8200   }
8201   case ARM::VMOVRRS: {
8202     // Source registers must be sequential.
8203     const unsigned Sm = MRI->getEncodingValue(Inst.getOperand(2).getReg());
8204     const unsigned Sm1 = MRI->getEncodingValue(Inst.getOperand(3).getReg());
8205     if (Sm1 != Sm + 1)
8206       return Error(Operands[5]->getStartLoc(),
8207                    "source operands must be sequential");
8208     break;
8209   }
8210   case ARM::VMOVSRR: {
8211     // Destination registers must be sequential.
8212     const unsigned Sm = MRI->getEncodingValue(Inst.getOperand(0).getReg());
8213     const unsigned Sm1 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
8214     if (Sm1 != Sm + 1)
8215       return Error(Operands[3]->getStartLoc(),
8216                    "destination operands must be sequential");
8217     break;
8218   }
8219   case ARM::VLDMDIA:
8220   case ARM::VSTMDIA: {
8221     ARMOperand &Op = static_cast<ARMOperand&>(*Operands[3]);
8222     auto &RegList = Op.getRegList();
8223     if (RegList.size() < 1 || RegList.size() > 16)
8224       return Error(Operands[3]->getStartLoc(),
8225                    "list of registers must be at least 1 and at most 16");
8226     break;
8227   }
8228   case ARM::MVE_VQDMULLs32bh:
8229   case ARM::MVE_VQDMULLs32th:
8230   case ARM::MVE_VCMULf32:
8231   case ARM::MVE_VMULLBs32:
8232   case ARM::MVE_VMULLTs32:
8233   case ARM::MVE_VMULLBu32:
8234   case ARM::MVE_VMULLTu32: {
8235     if (Operands[3]->getReg() == Operands[4]->getReg()) {
8236       return Error (Operands[3]->getStartLoc(),
8237                     "Qd register and Qn register can't be identical");
8238     }
8239     if (Operands[3]->getReg() == Operands[5]->getReg()) {
8240       return Error (Operands[3]->getStartLoc(),
8241                     "Qd register and Qm register can't be identical");
8242     }
8243     break;
8244   }
8245   case ARM::MVE_VMOV_rr_q: {
8246     if (Operands[4]->getReg() != Operands[6]->getReg())
8247       return Error (Operands[4]->getStartLoc(), "Q-registers must be the same");
8248     if (static_cast<ARMOperand &>(*Operands[5]).getVectorIndex() !=
8249         static_cast<ARMOperand &>(*Operands[7]).getVectorIndex() + 2)
8250       return Error (Operands[5]->getStartLoc(), "Q-register indexes must be 2 and 0 or 3 and 1");
8251     break;
8252   }
8253   case ARM::MVE_VMOV_q_rr: {
8254     if (Operands[2]->getReg() != Operands[4]->getReg())
8255       return Error (Operands[2]->getStartLoc(), "Q-registers must be the same");
8256     if (static_cast<ARMOperand &>(*Operands[3]).getVectorIndex() !=
8257         static_cast<ARMOperand &>(*Operands[5]).getVectorIndex() + 2)
8258       return Error (Operands[3]->getStartLoc(), "Q-register indexes must be 2 and 0 or 3 and 1");
8259     break;
8260   }
8261   case ARM::UMAAL:
8262   case ARM::UMLAL:
8263   case ARM::UMULL:
8264   case ARM::t2UMAAL:
8265   case ARM::t2UMLAL:
8266   case ARM::t2UMULL:
8267   case ARM::SMLAL:
8268   case ARM::SMLALBB:
8269   case ARM::SMLALBT:
8270   case ARM::SMLALD:
8271   case ARM::SMLALDX:
8272   case ARM::SMLALTB:
8273   case ARM::SMLALTT:
8274   case ARM::SMLSLD:
8275   case ARM::SMLSLDX:
8276   case ARM::SMULL:
8277   case ARM::t2SMLAL:
8278   case ARM::t2SMLALBB:
8279   case ARM::t2SMLALBT:
8280   case ARM::t2SMLALD:
8281   case ARM::t2SMLALDX:
8282   case ARM::t2SMLALTB:
8283   case ARM::t2SMLALTT:
8284   case ARM::t2SMLSLD:
8285   case ARM::t2SMLSLDX:
8286   case ARM::t2SMULL: {
8287     unsigned RdHi = Inst.getOperand(0).getReg();
8288     unsigned RdLo = Inst.getOperand(1).getReg();
8289     if(RdHi == RdLo) {
8290       return Error(Loc,
8291                    "unpredictable instruction, RdHi and RdLo must be different");
8292     }
8293     break;
8294   }
8295 
8296   case ARM::CDE_CX1:
8297   case ARM::CDE_CX1A:
8298   case ARM::CDE_CX1D:
8299   case ARM::CDE_CX1DA:
8300   case ARM::CDE_CX2:
8301   case ARM::CDE_CX2A:
8302   case ARM::CDE_CX2D:
8303   case ARM::CDE_CX2DA:
8304   case ARM::CDE_CX3:
8305   case ARM::CDE_CX3A:
8306   case ARM::CDE_CX3D:
8307   case ARM::CDE_CX3DA:
8308   case ARM::CDE_VCX1_vec:
8309   case ARM::CDE_VCX1_fpsp:
8310   case ARM::CDE_VCX1_fpdp:
8311   case ARM::CDE_VCX1A_vec:
8312   case ARM::CDE_VCX1A_fpsp:
8313   case ARM::CDE_VCX1A_fpdp:
8314   case ARM::CDE_VCX2_vec:
8315   case ARM::CDE_VCX2_fpsp:
8316   case ARM::CDE_VCX2_fpdp:
8317   case ARM::CDE_VCX2A_vec:
8318   case ARM::CDE_VCX2A_fpsp:
8319   case ARM::CDE_VCX2A_fpdp:
8320   case ARM::CDE_VCX3_vec:
8321   case ARM::CDE_VCX3_fpsp:
8322   case ARM::CDE_VCX3_fpdp:
8323   case ARM::CDE_VCX3A_vec:
8324   case ARM::CDE_VCX3A_fpsp:
8325   case ARM::CDE_VCX3A_fpdp: {
8326     assert(Inst.getOperand(1).isImm() &&
8327            "CDE operand 1 must be a coprocessor ID");
8328     int64_t Coproc = Inst.getOperand(1).getImm();
8329     if (Coproc < 8 && !ARM::isCDECoproc(Coproc, *STI))
8330       return Error(Operands[1]->getStartLoc(),
8331                    "coprocessor must be configured as CDE");
8332     else if (Coproc >= 8)
8333       return Error(Operands[1]->getStartLoc(),
8334                    "coprocessor must be in the range [p0, p7]");
8335     break;
8336   }
8337 
8338   case ARM::t2CDP:
8339   case ARM::t2CDP2:
8340   case ARM::t2LDC2L_OFFSET:
8341   case ARM::t2LDC2L_OPTION:
8342   case ARM::t2LDC2L_POST:
8343   case ARM::t2LDC2L_PRE:
8344   case ARM::t2LDC2_OFFSET:
8345   case ARM::t2LDC2_OPTION:
8346   case ARM::t2LDC2_POST:
8347   case ARM::t2LDC2_PRE:
8348   case ARM::t2LDCL_OFFSET:
8349   case ARM::t2LDCL_OPTION:
8350   case ARM::t2LDCL_POST:
8351   case ARM::t2LDCL_PRE:
8352   case ARM::t2LDC_OFFSET:
8353   case ARM::t2LDC_OPTION:
8354   case ARM::t2LDC_POST:
8355   case ARM::t2LDC_PRE:
8356   case ARM::t2MCR:
8357   case ARM::t2MCR2:
8358   case ARM::t2MCRR:
8359   case ARM::t2MCRR2:
8360   case ARM::t2MRC:
8361   case ARM::t2MRC2:
8362   case ARM::t2MRRC:
8363   case ARM::t2MRRC2:
8364   case ARM::t2STC2L_OFFSET:
8365   case ARM::t2STC2L_OPTION:
8366   case ARM::t2STC2L_POST:
8367   case ARM::t2STC2L_PRE:
8368   case ARM::t2STC2_OFFSET:
8369   case ARM::t2STC2_OPTION:
8370   case ARM::t2STC2_POST:
8371   case ARM::t2STC2_PRE:
8372   case ARM::t2STCL_OFFSET:
8373   case ARM::t2STCL_OPTION:
8374   case ARM::t2STCL_POST:
8375   case ARM::t2STCL_PRE:
8376   case ARM::t2STC_OFFSET:
8377   case ARM::t2STC_OPTION:
8378   case ARM::t2STC_POST:
8379   case ARM::t2STC_PRE: {
8380     unsigned Opcode = Inst.getOpcode();
8381     // Inst.getOperand indexes operands in the (oops ...) and (iops ...) dags,
8382     // CopInd is the index of the coprocessor operand.
8383     size_t CopInd = 0;
8384     if (Opcode == ARM::t2MRRC || Opcode == ARM::t2MRRC2)
8385       CopInd = 2;
8386     else if (Opcode == ARM::t2MRC || Opcode == ARM::t2MRC2)
8387       CopInd = 1;
8388     assert(Inst.getOperand(CopInd).isImm() &&
8389            "Operand must be a coprocessor ID");
8390     int64_t Coproc = Inst.getOperand(CopInd).getImm();
8391     // Operands[2] is the coprocessor operand at syntactic level
8392     if (ARM::isCDECoproc(Coproc, *STI))
8393       return Error(Operands[2]->getStartLoc(),
8394                    "coprocessor must be configured as GCP");
8395     break;
8396   }
8397   }
8398 
8399   return false;
8400 }
8401 
getRealVSTOpcode(unsigned Opc,unsigned & Spacing)8402 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
8403   switch(Opc) {
8404   default: llvm_unreachable("unexpected opcode!");
8405   // VST1LN
8406   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
8407   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
8408   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
8409   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
8410   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
8411   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
8412   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
8413   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
8414   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
8415 
8416   // VST2LN
8417   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
8418   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
8419   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
8420   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
8421   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
8422 
8423   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
8424   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
8425   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
8426   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
8427   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
8428 
8429   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
8430   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
8431   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
8432   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
8433   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
8434 
8435   // VST3LN
8436   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
8437   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
8438   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
8439   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
8440   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
8441   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
8442   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
8443   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
8444   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
8445   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
8446   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
8447   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
8448   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
8449   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
8450   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
8451 
8452   // VST3
8453   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
8454   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
8455   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
8456   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
8457   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
8458   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
8459   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
8460   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
8461   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
8462   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
8463   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
8464   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
8465   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
8466   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
8467   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
8468   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
8469   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
8470   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
8471 
8472   // VST4LN
8473   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
8474   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
8475   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
8476   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
8477   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
8478   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
8479   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
8480   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
8481   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
8482   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
8483   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
8484   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
8485   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
8486   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
8487   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
8488 
8489   // VST4
8490   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
8491   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
8492   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
8493   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
8494   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
8495   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
8496   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
8497   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
8498   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
8499   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
8500   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
8501   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
8502   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
8503   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
8504   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
8505   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
8506   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
8507   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
8508   }
8509 }
8510 
getRealVLDOpcode(unsigned Opc,unsigned & Spacing)8511 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
8512   switch(Opc) {
8513   default: llvm_unreachable("unexpected opcode!");
8514   // VLD1LN
8515   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
8516   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
8517   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
8518   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
8519   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
8520   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
8521   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
8522   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
8523   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
8524 
8525   // VLD2LN
8526   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
8527   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
8528   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
8529   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
8530   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
8531   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
8532   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
8533   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
8534   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
8535   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
8536   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
8537   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
8538   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
8539   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
8540   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
8541 
8542   // VLD3DUP
8543   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
8544   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
8545   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
8546   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
8547   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
8548   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
8549   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
8550   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
8551   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
8552   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
8553   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
8554   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
8555   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
8556   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
8557   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
8558   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
8559   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
8560   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
8561 
8562   // VLD3LN
8563   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
8564   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
8565   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
8566   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
8567   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
8568   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
8569   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
8570   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
8571   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
8572   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
8573   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
8574   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
8575   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
8576   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
8577   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
8578 
8579   // VLD3
8580   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
8581   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
8582   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
8583   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
8584   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
8585   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
8586   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
8587   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
8588   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
8589   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
8590   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
8591   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
8592   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
8593   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
8594   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
8595   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
8596   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
8597   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
8598 
8599   // VLD4LN
8600   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
8601   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
8602   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
8603   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
8604   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
8605   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
8606   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
8607   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
8608   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
8609   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
8610   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
8611   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
8612   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
8613   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
8614   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
8615 
8616   // VLD4DUP
8617   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
8618   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
8619   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
8620   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
8621   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
8622   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
8623   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
8624   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
8625   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
8626   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
8627   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
8628   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
8629   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
8630   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
8631   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
8632   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
8633   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
8634   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
8635 
8636   // VLD4
8637   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
8638   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
8639   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
8640   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
8641   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
8642   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
8643   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
8644   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
8645   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
8646   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
8647   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
8648   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
8649   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
8650   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
8651   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
8652   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
8653   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
8654   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
8655   }
8656 }
8657 
processInstruction(MCInst & Inst,const OperandVector & Operands,MCStreamer & Out)8658 bool ARMAsmParser::processInstruction(MCInst &Inst,
8659                                       const OperandVector &Operands,
8660                                       MCStreamer &Out) {
8661   // Check if we have the wide qualifier, because if it's present we
8662   // must avoid selecting a 16-bit thumb instruction.
8663   bool HasWideQualifier = false;
8664   for (auto &Op : Operands) {
8665     ARMOperand &ARMOp = static_cast<ARMOperand&>(*Op);
8666     if (ARMOp.isToken() && ARMOp.getToken() == ".w") {
8667       HasWideQualifier = true;
8668       break;
8669     }
8670   }
8671 
8672   switch (Inst.getOpcode()) {
8673   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
8674   case ARM::LDRT_POST:
8675   case ARM::LDRBT_POST: {
8676     const unsigned Opcode =
8677       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
8678                                            : ARM::LDRBT_POST_IMM;
8679     MCInst TmpInst;
8680     TmpInst.setOpcode(Opcode);
8681     TmpInst.addOperand(Inst.getOperand(0));
8682     TmpInst.addOperand(Inst.getOperand(1));
8683     TmpInst.addOperand(Inst.getOperand(1));
8684     TmpInst.addOperand(MCOperand::createReg(0));
8685     TmpInst.addOperand(MCOperand::createImm(0));
8686     TmpInst.addOperand(Inst.getOperand(2));
8687     TmpInst.addOperand(Inst.getOperand(3));
8688     Inst = TmpInst;
8689     return true;
8690   }
8691   // Alias for 'ldr{sb,h,sh}t Rt, [Rn] {, #imm}' for ommitted immediate.
8692   case ARM::LDRSBTii:
8693   case ARM::LDRHTii:
8694   case ARM::LDRSHTii: {
8695     MCInst TmpInst;
8696 
8697     if (Inst.getOpcode() == ARM::LDRSBTii)
8698       TmpInst.setOpcode(ARM::LDRSBTi);
8699     else if (Inst.getOpcode() == ARM::LDRHTii)
8700       TmpInst.setOpcode(ARM::LDRHTi);
8701     else if (Inst.getOpcode() == ARM::LDRSHTii)
8702       TmpInst.setOpcode(ARM::LDRSHTi);
8703     TmpInst.addOperand(Inst.getOperand(0));
8704     TmpInst.addOperand(Inst.getOperand(1));
8705     TmpInst.addOperand(Inst.getOperand(1));
8706     TmpInst.addOperand(MCOperand::createImm(256));
8707     TmpInst.addOperand(Inst.getOperand(2));
8708     Inst = TmpInst;
8709     return true;
8710   }
8711   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
8712   case ARM::STRT_POST:
8713   case ARM::STRBT_POST: {
8714     const unsigned Opcode =
8715       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
8716                                            : ARM::STRBT_POST_IMM;
8717     MCInst TmpInst;
8718     TmpInst.setOpcode(Opcode);
8719     TmpInst.addOperand(Inst.getOperand(1));
8720     TmpInst.addOperand(Inst.getOperand(0));
8721     TmpInst.addOperand(Inst.getOperand(1));
8722     TmpInst.addOperand(MCOperand::createReg(0));
8723     TmpInst.addOperand(MCOperand::createImm(0));
8724     TmpInst.addOperand(Inst.getOperand(2));
8725     TmpInst.addOperand(Inst.getOperand(3));
8726     Inst = TmpInst;
8727     return true;
8728   }
8729   // Alias for alternate form of 'ADR Rd, #imm' instruction.
8730   case ARM::ADDri: {
8731     if (Inst.getOperand(1).getReg() != ARM::PC ||
8732         Inst.getOperand(5).getReg() != 0 ||
8733         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
8734       return false;
8735     MCInst TmpInst;
8736     TmpInst.setOpcode(ARM::ADR);
8737     TmpInst.addOperand(Inst.getOperand(0));
8738     if (Inst.getOperand(2).isImm()) {
8739       // Immediate (mod_imm) will be in its encoded form, we must unencode it
8740       // before passing it to the ADR instruction.
8741       unsigned Enc = Inst.getOperand(2).getImm();
8742       TmpInst.addOperand(MCOperand::createImm(
8743         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
8744     } else {
8745       // Turn PC-relative expression into absolute expression.
8746       // Reading PC provides the start of the current instruction + 8 and
8747       // the transform to adr is biased by that.
8748       MCSymbol *Dot = getContext().createTempSymbol();
8749       Out.emitLabel(Dot);
8750       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
8751       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
8752                                                      MCSymbolRefExpr::VK_None,
8753                                                      getContext());
8754       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
8755       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
8756                                                      getContext());
8757       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
8758                                                         getContext());
8759       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
8760     }
8761     TmpInst.addOperand(Inst.getOperand(3));
8762     TmpInst.addOperand(Inst.getOperand(4));
8763     Inst = TmpInst;
8764     return true;
8765   }
8766   // Aliases for imm syntax of LDR instructions.
8767   case ARM::t2LDR_PRE_imm:
8768   case ARM::t2LDR_POST_imm: {
8769     MCInst TmpInst;
8770     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2LDR_PRE_imm ? ARM::t2LDR_PRE
8771                                                              : ARM::t2LDR_POST);
8772     TmpInst.addOperand(Inst.getOperand(0)); // Rt
8773     TmpInst.addOperand(Inst.getOperand(4)); // Rt_wb
8774     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8775     TmpInst.addOperand(Inst.getOperand(2)); // imm
8776     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8777     Inst = TmpInst;
8778     return true;
8779   }
8780   // Aliases for imm syntax of STR instructions.
8781   case ARM::t2STR_PRE_imm:
8782   case ARM::t2STR_POST_imm: {
8783     MCInst TmpInst;
8784     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2STR_PRE_imm ? ARM::t2STR_PRE
8785                                                              : ARM::t2STR_POST);
8786     TmpInst.addOperand(Inst.getOperand(4)); // Rt_wb
8787     TmpInst.addOperand(Inst.getOperand(0)); // Rt
8788     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8789     TmpInst.addOperand(Inst.getOperand(2)); // imm
8790     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8791     Inst = TmpInst;
8792     return true;
8793   }
8794   // Aliases for alternate PC+imm syntax of LDR instructions.
8795   case ARM::t2LDRpcrel:
8796     // Select the narrow version if the immediate will fit.
8797     if (Inst.getOperand(1).getImm() > 0 &&
8798         Inst.getOperand(1).getImm() <= 0xff &&
8799         !HasWideQualifier)
8800       Inst.setOpcode(ARM::tLDRpci);
8801     else
8802       Inst.setOpcode(ARM::t2LDRpci);
8803     return true;
8804   case ARM::t2LDRBpcrel:
8805     Inst.setOpcode(ARM::t2LDRBpci);
8806     return true;
8807   case ARM::t2LDRHpcrel:
8808     Inst.setOpcode(ARM::t2LDRHpci);
8809     return true;
8810   case ARM::t2LDRSBpcrel:
8811     Inst.setOpcode(ARM::t2LDRSBpci);
8812     return true;
8813   case ARM::t2LDRSHpcrel:
8814     Inst.setOpcode(ARM::t2LDRSHpci);
8815     return true;
8816   case ARM::LDRConstPool:
8817   case ARM::tLDRConstPool:
8818   case ARM::t2LDRConstPool: {
8819     // Pseudo instruction ldr rt, =immediate is converted to a
8820     // MOV rt, immediate if immediate is known and representable
8821     // otherwise we create a constant pool entry that we load from.
8822     MCInst TmpInst;
8823     if (Inst.getOpcode() == ARM::LDRConstPool)
8824       TmpInst.setOpcode(ARM::LDRi12);
8825     else if (Inst.getOpcode() == ARM::tLDRConstPool)
8826       TmpInst.setOpcode(ARM::tLDRpci);
8827     else if (Inst.getOpcode() == ARM::t2LDRConstPool)
8828       TmpInst.setOpcode(ARM::t2LDRpci);
8829     const ARMOperand &PoolOperand =
8830       (HasWideQualifier ?
8831        static_cast<ARMOperand &>(*Operands[4]) :
8832        static_cast<ARMOperand &>(*Operands[3]));
8833     const MCExpr *SubExprVal = PoolOperand.getConstantPoolImm();
8834     // If SubExprVal is a constant we may be able to use a MOV
8835     if (isa<MCConstantExpr>(SubExprVal) &&
8836         Inst.getOperand(0).getReg() != ARM::PC &&
8837         Inst.getOperand(0).getReg() != ARM::SP) {
8838       int64_t Value =
8839         (int64_t) (cast<MCConstantExpr>(SubExprVal))->getValue();
8840       bool UseMov  = true;
8841       bool MovHasS = true;
8842       if (Inst.getOpcode() == ARM::LDRConstPool) {
8843         // ARM Constant
8844         if (ARM_AM::getSOImmVal(Value) != -1) {
8845           Value = ARM_AM::getSOImmVal(Value);
8846           TmpInst.setOpcode(ARM::MOVi);
8847         }
8848         else if (ARM_AM::getSOImmVal(~Value) != -1) {
8849           Value = ARM_AM::getSOImmVal(~Value);
8850           TmpInst.setOpcode(ARM::MVNi);
8851         }
8852         else if (hasV6T2Ops() &&
8853                  Value >=0 && Value < 65536) {
8854           TmpInst.setOpcode(ARM::MOVi16);
8855           MovHasS = false;
8856         }
8857         else
8858           UseMov = false;
8859       }
8860       else {
8861         // Thumb/Thumb2 Constant
8862         if (hasThumb2() &&
8863             ARM_AM::getT2SOImmVal(Value) != -1)
8864           TmpInst.setOpcode(ARM::t2MOVi);
8865         else if (hasThumb2() &&
8866                  ARM_AM::getT2SOImmVal(~Value) != -1) {
8867           TmpInst.setOpcode(ARM::t2MVNi);
8868           Value = ~Value;
8869         }
8870         else if (hasV8MBaseline() &&
8871                  Value >=0 && Value < 65536) {
8872           TmpInst.setOpcode(ARM::t2MOVi16);
8873           MovHasS = false;
8874         }
8875         else
8876           UseMov = false;
8877       }
8878       if (UseMov) {
8879         TmpInst.addOperand(Inst.getOperand(0));           // Rt
8880         TmpInst.addOperand(MCOperand::createImm(Value));  // Immediate
8881         TmpInst.addOperand(Inst.getOperand(2));           // CondCode
8882         TmpInst.addOperand(Inst.getOperand(3));           // CondCode
8883         if (MovHasS)
8884           TmpInst.addOperand(MCOperand::createReg(0));    // S
8885         Inst = TmpInst;
8886         return true;
8887       }
8888     }
8889     // No opportunity to use MOV/MVN create constant pool
8890     const MCExpr *CPLoc =
8891       getTargetStreamer().addConstantPoolEntry(SubExprVal,
8892                                                PoolOperand.getStartLoc());
8893     TmpInst.addOperand(Inst.getOperand(0));           // Rt
8894     TmpInst.addOperand(MCOperand::createExpr(CPLoc)); // offset to constpool
8895     if (TmpInst.getOpcode() == ARM::LDRi12)
8896       TmpInst.addOperand(MCOperand::createImm(0));    // unused offset
8897     TmpInst.addOperand(Inst.getOperand(2));           // CondCode
8898     TmpInst.addOperand(Inst.getOperand(3));           // CondCode
8899     Inst = TmpInst;
8900     return true;
8901   }
8902   // Handle NEON VST complex aliases.
8903   case ARM::VST1LNdWB_register_Asm_8:
8904   case ARM::VST1LNdWB_register_Asm_16:
8905   case ARM::VST1LNdWB_register_Asm_32: {
8906     MCInst TmpInst;
8907     // Shuffle the operands around so the lane index operand is in the
8908     // right place.
8909     unsigned Spacing;
8910     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8911     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8912     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8913     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8914     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8915     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8916     TmpInst.addOperand(Inst.getOperand(1)); // lane
8917     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8918     TmpInst.addOperand(Inst.getOperand(6));
8919     Inst = TmpInst;
8920     return true;
8921   }
8922 
8923   case ARM::VST2LNdWB_register_Asm_8:
8924   case ARM::VST2LNdWB_register_Asm_16:
8925   case ARM::VST2LNdWB_register_Asm_32:
8926   case ARM::VST2LNqWB_register_Asm_16:
8927   case ARM::VST2LNqWB_register_Asm_32: {
8928     MCInst TmpInst;
8929     // Shuffle the operands around so the lane index operand is in the
8930     // right place.
8931     unsigned Spacing;
8932     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8933     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8934     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8935     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8936     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8937     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8938     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8939                                             Spacing));
8940     TmpInst.addOperand(Inst.getOperand(1)); // lane
8941     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8942     TmpInst.addOperand(Inst.getOperand(6));
8943     Inst = TmpInst;
8944     return true;
8945   }
8946 
8947   case ARM::VST3LNdWB_register_Asm_8:
8948   case ARM::VST3LNdWB_register_Asm_16:
8949   case ARM::VST3LNdWB_register_Asm_32:
8950   case ARM::VST3LNqWB_register_Asm_16:
8951   case ARM::VST3LNqWB_register_Asm_32: {
8952     MCInst TmpInst;
8953     // Shuffle the operands around so the lane index operand is in the
8954     // right place.
8955     unsigned Spacing;
8956     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8957     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8958     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8959     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8960     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8961     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8962     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8963                                             Spacing));
8964     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8965                                             Spacing * 2));
8966     TmpInst.addOperand(Inst.getOperand(1)); // lane
8967     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8968     TmpInst.addOperand(Inst.getOperand(6));
8969     Inst = TmpInst;
8970     return true;
8971   }
8972 
8973   case ARM::VST4LNdWB_register_Asm_8:
8974   case ARM::VST4LNdWB_register_Asm_16:
8975   case ARM::VST4LNdWB_register_Asm_32:
8976   case ARM::VST4LNqWB_register_Asm_16:
8977   case ARM::VST4LNqWB_register_Asm_32: {
8978     MCInst TmpInst;
8979     // Shuffle the operands around so the lane index operand is in the
8980     // right place.
8981     unsigned Spacing;
8982     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8983     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8984     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8985     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8986     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8987     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8988     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8989                                             Spacing));
8990     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8991                                             Spacing * 2));
8992     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8993                                             Spacing * 3));
8994     TmpInst.addOperand(Inst.getOperand(1)); // lane
8995     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8996     TmpInst.addOperand(Inst.getOperand(6));
8997     Inst = TmpInst;
8998     return true;
8999   }
9000 
9001   case ARM::VST1LNdWB_fixed_Asm_8:
9002   case ARM::VST1LNdWB_fixed_Asm_16:
9003   case ARM::VST1LNdWB_fixed_Asm_32: {
9004     MCInst TmpInst;
9005     // Shuffle the operands around so the lane index operand is in the
9006     // right place.
9007     unsigned Spacing;
9008     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9009     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9010     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9011     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9012     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9013     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9014     TmpInst.addOperand(Inst.getOperand(1)); // lane
9015     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9016     TmpInst.addOperand(Inst.getOperand(5));
9017     Inst = TmpInst;
9018     return true;
9019   }
9020 
9021   case ARM::VST2LNdWB_fixed_Asm_8:
9022   case ARM::VST2LNdWB_fixed_Asm_16:
9023   case ARM::VST2LNdWB_fixed_Asm_32:
9024   case ARM::VST2LNqWB_fixed_Asm_16:
9025   case ARM::VST2LNqWB_fixed_Asm_32: {
9026     MCInst TmpInst;
9027     // Shuffle the operands around so the lane index operand is in the
9028     // right place.
9029     unsigned Spacing;
9030     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9031     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9032     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9033     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9034     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9035     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9036     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9037                                             Spacing));
9038     TmpInst.addOperand(Inst.getOperand(1)); // lane
9039     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9040     TmpInst.addOperand(Inst.getOperand(5));
9041     Inst = TmpInst;
9042     return true;
9043   }
9044 
9045   case ARM::VST3LNdWB_fixed_Asm_8:
9046   case ARM::VST3LNdWB_fixed_Asm_16:
9047   case ARM::VST3LNdWB_fixed_Asm_32:
9048   case ARM::VST3LNqWB_fixed_Asm_16:
9049   case ARM::VST3LNqWB_fixed_Asm_32: {
9050     MCInst TmpInst;
9051     // Shuffle the operands around so the lane index operand is in the
9052     // right place.
9053     unsigned Spacing;
9054     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9055     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9056     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9057     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9058     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9059     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9060     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9061                                             Spacing));
9062     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9063                                             Spacing * 2));
9064     TmpInst.addOperand(Inst.getOperand(1)); // lane
9065     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9066     TmpInst.addOperand(Inst.getOperand(5));
9067     Inst = TmpInst;
9068     return true;
9069   }
9070 
9071   case ARM::VST4LNdWB_fixed_Asm_8:
9072   case ARM::VST4LNdWB_fixed_Asm_16:
9073   case ARM::VST4LNdWB_fixed_Asm_32:
9074   case ARM::VST4LNqWB_fixed_Asm_16:
9075   case ARM::VST4LNqWB_fixed_Asm_32: {
9076     MCInst TmpInst;
9077     // Shuffle the operands around so the lane index operand is in the
9078     // right place.
9079     unsigned Spacing;
9080     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9081     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9082     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9083     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9084     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9085     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9086     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9087                                             Spacing));
9088     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9089                                             Spacing * 2));
9090     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9091                                             Spacing * 3));
9092     TmpInst.addOperand(Inst.getOperand(1)); // lane
9093     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9094     TmpInst.addOperand(Inst.getOperand(5));
9095     Inst = TmpInst;
9096     return true;
9097   }
9098 
9099   case ARM::VST1LNdAsm_8:
9100   case ARM::VST1LNdAsm_16:
9101   case ARM::VST1LNdAsm_32: {
9102     MCInst TmpInst;
9103     // Shuffle the operands around so the lane index operand is in the
9104     // right place.
9105     unsigned Spacing;
9106     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9107     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9108     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9109     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9110     TmpInst.addOperand(Inst.getOperand(1)); // lane
9111     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9112     TmpInst.addOperand(Inst.getOperand(5));
9113     Inst = TmpInst;
9114     return true;
9115   }
9116 
9117   case ARM::VST2LNdAsm_8:
9118   case ARM::VST2LNdAsm_16:
9119   case ARM::VST2LNdAsm_32:
9120   case ARM::VST2LNqAsm_16:
9121   case ARM::VST2LNqAsm_32: {
9122     MCInst TmpInst;
9123     // Shuffle the operands around so the lane index operand is in the
9124     // right place.
9125     unsigned Spacing;
9126     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9127     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9128     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9129     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9130     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9131                                             Spacing));
9132     TmpInst.addOperand(Inst.getOperand(1)); // lane
9133     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9134     TmpInst.addOperand(Inst.getOperand(5));
9135     Inst = TmpInst;
9136     return true;
9137   }
9138 
9139   case ARM::VST3LNdAsm_8:
9140   case ARM::VST3LNdAsm_16:
9141   case ARM::VST3LNdAsm_32:
9142   case ARM::VST3LNqAsm_16:
9143   case ARM::VST3LNqAsm_32: {
9144     MCInst TmpInst;
9145     // Shuffle the operands around so the lane index operand is in the
9146     // right place.
9147     unsigned Spacing;
9148     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9149     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9150     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9151     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9152     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9153                                             Spacing));
9154     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9155                                             Spacing * 2));
9156     TmpInst.addOperand(Inst.getOperand(1)); // lane
9157     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9158     TmpInst.addOperand(Inst.getOperand(5));
9159     Inst = TmpInst;
9160     return true;
9161   }
9162 
9163   case ARM::VST4LNdAsm_8:
9164   case ARM::VST4LNdAsm_16:
9165   case ARM::VST4LNdAsm_32:
9166   case ARM::VST4LNqAsm_16:
9167   case ARM::VST4LNqAsm_32: {
9168     MCInst TmpInst;
9169     // Shuffle the operands around so the lane index operand is in the
9170     // right place.
9171     unsigned Spacing;
9172     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9173     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9174     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9175     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9176     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9177                                             Spacing));
9178     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9179                                             Spacing * 2));
9180     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9181                                             Spacing * 3));
9182     TmpInst.addOperand(Inst.getOperand(1)); // lane
9183     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9184     TmpInst.addOperand(Inst.getOperand(5));
9185     Inst = TmpInst;
9186     return true;
9187   }
9188 
9189   // Handle NEON VLD complex aliases.
9190   case ARM::VLD1LNdWB_register_Asm_8:
9191   case ARM::VLD1LNdWB_register_Asm_16:
9192   case ARM::VLD1LNdWB_register_Asm_32: {
9193     MCInst TmpInst;
9194     // Shuffle the operands around so the lane index operand is in the
9195     // right place.
9196     unsigned Spacing;
9197     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9198     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9199     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9200     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9201     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9202     TmpInst.addOperand(Inst.getOperand(4)); // Rm
9203     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9204     TmpInst.addOperand(Inst.getOperand(1)); // lane
9205     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
9206     TmpInst.addOperand(Inst.getOperand(6));
9207     Inst = TmpInst;
9208     return true;
9209   }
9210 
9211   case ARM::VLD2LNdWB_register_Asm_8:
9212   case ARM::VLD2LNdWB_register_Asm_16:
9213   case ARM::VLD2LNdWB_register_Asm_32:
9214   case ARM::VLD2LNqWB_register_Asm_16:
9215   case ARM::VLD2LNqWB_register_Asm_32: {
9216     MCInst TmpInst;
9217     // Shuffle the operands around so the lane index operand is in the
9218     // right place.
9219     unsigned Spacing;
9220     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9221     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9222     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9223                                             Spacing));
9224     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9225     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9226     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9227     TmpInst.addOperand(Inst.getOperand(4)); // Rm
9228     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9229     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9230                                             Spacing));
9231     TmpInst.addOperand(Inst.getOperand(1)); // lane
9232     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
9233     TmpInst.addOperand(Inst.getOperand(6));
9234     Inst = TmpInst;
9235     return true;
9236   }
9237 
9238   case ARM::VLD3LNdWB_register_Asm_8:
9239   case ARM::VLD3LNdWB_register_Asm_16:
9240   case ARM::VLD3LNdWB_register_Asm_32:
9241   case ARM::VLD3LNqWB_register_Asm_16:
9242   case ARM::VLD3LNqWB_register_Asm_32: {
9243     MCInst TmpInst;
9244     // Shuffle the operands around so the lane index operand is in the
9245     // right place.
9246     unsigned Spacing;
9247     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9248     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9249     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9250                                             Spacing));
9251     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9252                                             Spacing * 2));
9253     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9254     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9255     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9256     TmpInst.addOperand(Inst.getOperand(4)); // Rm
9257     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9258     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9259                                             Spacing));
9260     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9261                                             Spacing * 2));
9262     TmpInst.addOperand(Inst.getOperand(1)); // lane
9263     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
9264     TmpInst.addOperand(Inst.getOperand(6));
9265     Inst = TmpInst;
9266     return true;
9267   }
9268 
9269   case ARM::VLD4LNdWB_register_Asm_8:
9270   case ARM::VLD4LNdWB_register_Asm_16:
9271   case ARM::VLD4LNdWB_register_Asm_32:
9272   case ARM::VLD4LNqWB_register_Asm_16:
9273   case ARM::VLD4LNqWB_register_Asm_32: {
9274     MCInst TmpInst;
9275     // Shuffle the operands around so the lane index operand is in the
9276     // right place.
9277     unsigned Spacing;
9278     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9279     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9280     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9281                                             Spacing));
9282     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9283                                             Spacing * 2));
9284     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9285                                             Spacing * 3));
9286     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9287     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9288     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9289     TmpInst.addOperand(Inst.getOperand(4)); // Rm
9290     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9291     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9292                                             Spacing));
9293     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9294                                             Spacing * 2));
9295     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9296                                             Spacing * 3));
9297     TmpInst.addOperand(Inst.getOperand(1)); // lane
9298     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
9299     TmpInst.addOperand(Inst.getOperand(6));
9300     Inst = TmpInst;
9301     return true;
9302   }
9303 
9304   case ARM::VLD1LNdWB_fixed_Asm_8:
9305   case ARM::VLD1LNdWB_fixed_Asm_16:
9306   case ARM::VLD1LNdWB_fixed_Asm_32: {
9307     MCInst TmpInst;
9308     // Shuffle the operands around so the lane index operand is in the
9309     // right place.
9310     unsigned Spacing;
9311     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9312     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9313     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9314     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9315     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9316     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9317     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9318     TmpInst.addOperand(Inst.getOperand(1)); // lane
9319     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9320     TmpInst.addOperand(Inst.getOperand(5));
9321     Inst = TmpInst;
9322     return true;
9323   }
9324 
9325   case ARM::VLD2LNdWB_fixed_Asm_8:
9326   case ARM::VLD2LNdWB_fixed_Asm_16:
9327   case ARM::VLD2LNdWB_fixed_Asm_32:
9328   case ARM::VLD2LNqWB_fixed_Asm_16:
9329   case ARM::VLD2LNqWB_fixed_Asm_32: {
9330     MCInst TmpInst;
9331     // Shuffle the operands around so the lane index operand is in the
9332     // right place.
9333     unsigned Spacing;
9334     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9335     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9336     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9337                                             Spacing));
9338     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9339     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9340     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9341     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9342     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9343     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9344                                             Spacing));
9345     TmpInst.addOperand(Inst.getOperand(1)); // lane
9346     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9347     TmpInst.addOperand(Inst.getOperand(5));
9348     Inst = TmpInst;
9349     return true;
9350   }
9351 
9352   case ARM::VLD3LNdWB_fixed_Asm_8:
9353   case ARM::VLD3LNdWB_fixed_Asm_16:
9354   case ARM::VLD3LNdWB_fixed_Asm_32:
9355   case ARM::VLD3LNqWB_fixed_Asm_16:
9356   case ARM::VLD3LNqWB_fixed_Asm_32: {
9357     MCInst TmpInst;
9358     // Shuffle the operands around so the lane index operand is in the
9359     // right place.
9360     unsigned Spacing;
9361     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9362     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9363     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9364                                             Spacing));
9365     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9366                                             Spacing * 2));
9367     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9368     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9369     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9370     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9371     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9372     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9373                                             Spacing));
9374     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9375                                             Spacing * 2));
9376     TmpInst.addOperand(Inst.getOperand(1)); // lane
9377     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9378     TmpInst.addOperand(Inst.getOperand(5));
9379     Inst = TmpInst;
9380     return true;
9381   }
9382 
9383   case ARM::VLD4LNdWB_fixed_Asm_8:
9384   case ARM::VLD4LNdWB_fixed_Asm_16:
9385   case ARM::VLD4LNdWB_fixed_Asm_32:
9386   case ARM::VLD4LNqWB_fixed_Asm_16:
9387   case ARM::VLD4LNqWB_fixed_Asm_32: {
9388     MCInst TmpInst;
9389     // Shuffle the operands around so the lane index operand is in the
9390     // right place.
9391     unsigned Spacing;
9392     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9393     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9394     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9395                                             Spacing));
9396     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9397                                             Spacing * 2));
9398     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9399                                             Spacing * 3));
9400     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9401     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9402     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9403     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9404     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9405     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9406                                             Spacing));
9407     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9408                                             Spacing * 2));
9409     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9410                                             Spacing * 3));
9411     TmpInst.addOperand(Inst.getOperand(1)); // lane
9412     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9413     TmpInst.addOperand(Inst.getOperand(5));
9414     Inst = TmpInst;
9415     return true;
9416   }
9417 
9418   case ARM::VLD1LNdAsm_8:
9419   case ARM::VLD1LNdAsm_16:
9420   case ARM::VLD1LNdAsm_32: {
9421     MCInst TmpInst;
9422     // Shuffle the operands around so the lane index operand is in the
9423     // right place.
9424     unsigned Spacing;
9425     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9426     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9427     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9428     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9429     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9430     TmpInst.addOperand(Inst.getOperand(1)); // lane
9431     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9432     TmpInst.addOperand(Inst.getOperand(5));
9433     Inst = TmpInst;
9434     return true;
9435   }
9436 
9437   case ARM::VLD2LNdAsm_8:
9438   case ARM::VLD2LNdAsm_16:
9439   case ARM::VLD2LNdAsm_32:
9440   case ARM::VLD2LNqAsm_16:
9441   case ARM::VLD2LNqAsm_32: {
9442     MCInst TmpInst;
9443     // Shuffle the operands around so the lane index operand is in the
9444     // right place.
9445     unsigned Spacing;
9446     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9447     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9448     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9449                                             Spacing));
9450     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9451     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9452     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9453     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9454                                             Spacing));
9455     TmpInst.addOperand(Inst.getOperand(1)); // lane
9456     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9457     TmpInst.addOperand(Inst.getOperand(5));
9458     Inst = TmpInst;
9459     return true;
9460   }
9461 
9462   case ARM::VLD3LNdAsm_8:
9463   case ARM::VLD3LNdAsm_16:
9464   case ARM::VLD3LNdAsm_32:
9465   case ARM::VLD3LNqAsm_16:
9466   case ARM::VLD3LNqAsm_32: {
9467     MCInst TmpInst;
9468     // Shuffle the operands around so the lane index operand is in the
9469     // right place.
9470     unsigned Spacing;
9471     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9472     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9473     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9474                                             Spacing));
9475     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9476                                             Spacing * 2));
9477     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9478     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9479     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9480     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9481                                             Spacing));
9482     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9483                                             Spacing * 2));
9484     TmpInst.addOperand(Inst.getOperand(1)); // lane
9485     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9486     TmpInst.addOperand(Inst.getOperand(5));
9487     Inst = TmpInst;
9488     return true;
9489   }
9490 
9491   case ARM::VLD4LNdAsm_8:
9492   case ARM::VLD4LNdAsm_16:
9493   case ARM::VLD4LNdAsm_32:
9494   case ARM::VLD4LNqAsm_16:
9495   case ARM::VLD4LNqAsm_32: {
9496     MCInst TmpInst;
9497     // Shuffle the operands around so the lane index operand is in the
9498     // right place.
9499     unsigned Spacing;
9500     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9501     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9502     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9503                                             Spacing));
9504     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9505                                             Spacing * 2));
9506     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9507                                             Spacing * 3));
9508     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9509     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9510     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9511     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9512                                             Spacing));
9513     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9514                                             Spacing * 2));
9515     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9516                                             Spacing * 3));
9517     TmpInst.addOperand(Inst.getOperand(1)); // lane
9518     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9519     TmpInst.addOperand(Inst.getOperand(5));
9520     Inst = TmpInst;
9521     return true;
9522   }
9523 
9524   // VLD3DUP single 3-element structure to all lanes instructions.
9525   case ARM::VLD3DUPdAsm_8:
9526   case ARM::VLD3DUPdAsm_16:
9527   case ARM::VLD3DUPdAsm_32:
9528   case ARM::VLD3DUPqAsm_8:
9529   case ARM::VLD3DUPqAsm_16:
9530   case ARM::VLD3DUPqAsm_32: {
9531     MCInst TmpInst;
9532     unsigned Spacing;
9533     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9534     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9535     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9536                                             Spacing));
9537     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9538                                             Spacing * 2));
9539     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9540     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9541     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9542     TmpInst.addOperand(Inst.getOperand(4));
9543     Inst = TmpInst;
9544     return true;
9545   }
9546 
9547   case ARM::VLD3DUPdWB_fixed_Asm_8:
9548   case ARM::VLD3DUPdWB_fixed_Asm_16:
9549   case ARM::VLD3DUPdWB_fixed_Asm_32:
9550   case ARM::VLD3DUPqWB_fixed_Asm_8:
9551   case ARM::VLD3DUPqWB_fixed_Asm_16:
9552   case ARM::VLD3DUPqWB_fixed_Asm_32: {
9553     MCInst TmpInst;
9554     unsigned Spacing;
9555     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9556     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9557     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9558                                             Spacing));
9559     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9560                                             Spacing * 2));
9561     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9562     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9563     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9564     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9565     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9566     TmpInst.addOperand(Inst.getOperand(4));
9567     Inst = TmpInst;
9568     return true;
9569   }
9570 
9571   case ARM::VLD3DUPdWB_register_Asm_8:
9572   case ARM::VLD3DUPdWB_register_Asm_16:
9573   case ARM::VLD3DUPdWB_register_Asm_32:
9574   case ARM::VLD3DUPqWB_register_Asm_8:
9575   case ARM::VLD3DUPqWB_register_Asm_16:
9576   case ARM::VLD3DUPqWB_register_Asm_32: {
9577     MCInst TmpInst;
9578     unsigned Spacing;
9579     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9580     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9581     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9582                                             Spacing));
9583     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9584                                             Spacing * 2));
9585     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9586     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9587     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9588     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9589     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9590     TmpInst.addOperand(Inst.getOperand(5));
9591     Inst = TmpInst;
9592     return true;
9593   }
9594 
9595   // VLD3 multiple 3-element structure instructions.
9596   case ARM::VLD3dAsm_8:
9597   case ARM::VLD3dAsm_16:
9598   case ARM::VLD3dAsm_32:
9599   case ARM::VLD3qAsm_8:
9600   case ARM::VLD3qAsm_16:
9601   case ARM::VLD3qAsm_32: {
9602     MCInst TmpInst;
9603     unsigned Spacing;
9604     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9605     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9606     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9607                                             Spacing));
9608     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9609                                             Spacing * 2));
9610     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9611     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9612     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9613     TmpInst.addOperand(Inst.getOperand(4));
9614     Inst = TmpInst;
9615     return true;
9616   }
9617 
9618   case ARM::VLD3dWB_fixed_Asm_8:
9619   case ARM::VLD3dWB_fixed_Asm_16:
9620   case ARM::VLD3dWB_fixed_Asm_32:
9621   case ARM::VLD3qWB_fixed_Asm_8:
9622   case ARM::VLD3qWB_fixed_Asm_16:
9623   case ARM::VLD3qWB_fixed_Asm_32: {
9624     MCInst TmpInst;
9625     unsigned Spacing;
9626     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9627     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9628     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9629                                             Spacing));
9630     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9631                                             Spacing * 2));
9632     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9633     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9634     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9635     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9636     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9637     TmpInst.addOperand(Inst.getOperand(4));
9638     Inst = TmpInst;
9639     return true;
9640   }
9641 
9642   case ARM::VLD3dWB_register_Asm_8:
9643   case ARM::VLD3dWB_register_Asm_16:
9644   case ARM::VLD3dWB_register_Asm_32:
9645   case ARM::VLD3qWB_register_Asm_8:
9646   case ARM::VLD3qWB_register_Asm_16:
9647   case ARM::VLD3qWB_register_Asm_32: {
9648     MCInst TmpInst;
9649     unsigned Spacing;
9650     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9651     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9652     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9653                                             Spacing));
9654     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9655                                             Spacing * 2));
9656     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9657     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9658     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9659     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9660     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9661     TmpInst.addOperand(Inst.getOperand(5));
9662     Inst = TmpInst;
9663     return true;
9664   }
9665 
9666   // VLD4DUP single 3-element structure to all lanes instructions.
9667   case ARM::VLD4DUPdAsm_8:
9668   case ARM::VLD4DUPdAsm_16:
9669   case ARM::VLD4DUPdAsm_32:
9670   case ARM::VLD4DUPqAsm_8:
9671   case ARM::VLD4DUPqAsm_16:
9672   case ARM::VLD4DUPqAsm_32: {
9673     MCInst TmpInst;
9674     unsigned Spacing;
9675     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9676     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9677     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9678                                             Spacing));
9679     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9680                                             Spacing * 2));
9681     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9682                                             Spacing * 3));
9683     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9684     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9685     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9686     TmpInst.addOperand(Inst.getOperand(4));
9687     Inst = TmpInst;
9688     return true;
9689   }
9690 
9691   case ARM::VLD4DUPdWB_fixed_Asm_8:
9692   case ARM::VLD4DUPdWB_fixed_Asm_16:
9693   case ARM::VLD4DUPdWB_fixed_Asm_32:
9694   case ARM::VLD4DUPqWB_fixed_Asm_8:
9695   case ARM::VLD4DUPqWB_fixed_Asm_16:
9696   case ARM::VLD4DUPqWB_fixed_Asm_32: {
9697     MCInst TmpInst;
9698     unsigned Spacing;
9699     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9700     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9701     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9702                                             Spacing));
9703     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9704                                             Spacing * 2));
9705     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9706                                             Spacing * 3));
9707     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9708     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9709     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9710     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9711     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9712     TmpInst.addOperand(Inst.getOperand(4));
9713     Inst = TmpInst;
9714     return true;
9715   }
9716 
9717   case ARM::VLD4DUPdWB_register_Asm_8:
9718   case ARM::VLD4DUPdWB_register_Asm_16:
9719   case ARM::VLD4DUPdWB_register_Asm_32:
9720   case ARM::VLD4DUPqWB_register_Asm_8:
9721   case ARM::VLD4DUPqWB_register_Asm_16:
9722   case ARM::VLD4DUPqWB_register_Asm_32: {
9723     MCInst TmpInst;
9724     unsigned Spacing;
9725     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9726     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9727     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9728                                             Spacing));
9729     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9730                                             Spacing * 2));
9731     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9732                                             Spacing * 3));
9733     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9734     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9735     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9736     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9737     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9738     TmpInst.addOperand(Inst.getOperand(5));
9739     Inst = TmpInst;
9740     return true;
9741   }
9742 
9743   // VLD4 multiple 4-element structure instructions.
9744   case ARM::VLD4dAsm_8:
9745   case ARM::VLD4dAsm_16:
9746   case ARM::VLD4dAsm_32:
9747   case ARM::VLD4qAsm_8:
9748   case ARM::VLD4qAsm_16:
9749   case ARM::VLD4qAsm_32: {
9750     MCInst TmpInst;
9751     unsigned Spacing;
9752     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9753     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9754     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9755                                             Spacing));
9756     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9757                                             Spacing * 2));
9758     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9759                                             Spacing * 3));
9760     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9761     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9762     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9763     TmpInst.addOperand(Inst.getOperand(4));
9764     Inst = TmpInst;
9765     return true;
9766   }
9767 
9768   case ARM::VLD4dWB_fixed_Asm_8:
9769   case ARM::VLD4dWB_fixed_Asm_16:
9770   case ARM::VLD4dWB_fixed_Asm_32:
9771   case ARM::VLD4qWB_fixed_Asm_8:
9772   case ARM::VLD4qWB_fixed_Asm_16:
9773   case ARM::VLD4qWB_fixed_Asm_32: {
9774     MCInst TmpInst;
9775     unsigned Spacing;
9776     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9777     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9778     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9779                                             Spacing));
9780     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9781                                             Spacing * 2));
9782     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9783                                             Spacing * 3));
9784     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9785     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9786     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9787     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9788     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9789     TmpInst.addOperand(Inst.getOperand(4));
9790     Inst = TmpInst;
9791     return true;
9792   }
9793 
9794   case ARM::VLD4dWB_register_Asm_8:
9795   case ARM::VLD4dWB_register_Asm_16:
9796   case ARM::VLD4dWB_register_Asm_32:
9797   case ARM::VLD4qWB_register_Asm_8:
9798   case ARM::VLD4qWB_register_Asm_16:
9799   case ARM::VLD4qWB_register_Asm_32: {
9800     MCInst TmpInst;
9801     unsigned Spacing;
9802     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9803     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9804     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9805                                             Spacing));
9806     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9807                                             Spacing * 2));
9808     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9809                                             Spacing * 3));
9810     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9811     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9812     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9813     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9814     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9815     TmpInst.addOperand(Inst.getOperand(5));
9816     Inst = TmpInst;
9817     return true;
9818   }
9819 
9820   // VST3 multiple 3-element structure instructions.
9821   case ARM::VST3dAsm_8:
9822   case ARM::VST3dAsm_16:
9823   case ARM::VST3dAsm_32:
9824   case ARM::VST3qAsm_8:
9825   case ARM::VST3qAsm_16:
9826   case ARM::VST3qAsm_32: {
9827     MCInst TmpInst;
9828     unsigned Spacing;
9829     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9830     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9831     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9832     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9833     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9834                                             Spacing));
9835     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9836                                             Spacing * 2));
9837     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9838     TmpInst.addOperand(Inst.getOperand(4));
9839     Inst = TmpInst;
9840     return true;
9841   }
9842 
9843   case ARM::VST3dWB_fixed_Asm_8:
9844   case ARM::VST3dWB_fixed_Asm_16:
9845   case ARM::VST3dWB_fixed_Asm_32:
9846   case ARM::VST3qWB_fixed_Asm_8:
9847   case ARM::VST3qWB_fixed_Asm_16:
9848   case ARM::VST3qWB_fixed_Asm_32: {
9849     MCInst TmpInst;
9850     unsigned Spacing;
9851     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9852     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9853     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9854     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9855     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9856     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9857     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9858                                             Spacing));
9859     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9860                                             Spacing * 2));
9861     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9862     TmpInst.addOperand(Inst.getOperand(4));
9863     Inst = TmpInst;
9864     return true;
9865   }
9866 
9867   case ARM::VST3dWB_register_Asm_8:
9868   case ARM::VST3dWB_register_Asm_16:
9869   case ARM::VST3dWB_register_Asm_32:
9870   case ARM::VST3qWB_register_Asm_8:
9871   case ARM::VST3qWB_register_Asm_16:
9872   case ARM::VST3qWB_register_Asm_32: {
9873     MCInst TmpInst;
9874     unsigned Spacing;
9875     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9876     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9877     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9878     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9879     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9880     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9881     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9882                                             Spacing));
9883     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9884                                             Spacing * 2));
9885     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9886     TmpInst.addOperand(Inst.getOperand(5));
9887     Inst = TmpInst;
9888     return true;
9889   }
9890 
9891   // VST4 multiple 3-element structure instructions.
9892   case ARM::VST4dAsm_8:
9893   case ARM::VST4dAsm_16:
9894   case ARM::VST4dAsm_32:
9895   case ARM::VST4qAsm_8:
9896   case ARM::VST4qAsm_16:
9897   case ARM::VST4qAsm_32: {
9898     MCInst TmpInst;
9899     unsigned Spacing;
9900     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9901     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9902     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9903     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9904     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9905                                             Spacing));
9906     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9907                                             Spacing * 2));
9908     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9909                                             Spacing * 3));
9910     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9911     TmpInst.addOperand(Inst.getOperand(4));
9912     Inst = TmpInst;
9913     return true;
9914   }
9915 
9916   case ARM::VST4dWB_fixed_Asm_8:
9917   case ARM::VST4dWB_fixed_Asm_16:
9918   case ARM::VST4dWB_fixed_Asm_32:
9919   case ARM::VST4qWB_fixed_Asm_8:
9920   case ARM::VST4qWB_fixed_Asm_16:
9921   case ARM::VST4qWB_fixed_Asm_32: {
9922     MCInst TmpInst;
9923     unsigned Spacing;
9924     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9925     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9926     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9927     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9928     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9929     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9930     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9931                                             Spacing));
9932     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9933                                             Spacing * 2));
9934     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9935                                             Spacing * 3));
9936     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9937     TmpInst.addOperand(Inst.getOperand(4));
9938     Inst = TmpInst;
9939     return true;
9940   }
9941 
9942   case ARM::VST4dWB_register_Asm_8:
9943   case ARM::VST4dWB_register_Asm_16:
9944   case ARM::VST4dWB_register_Asm_32:
9945   case ARM::VST4qWB_register_Asm_8:
9946   case ARM::VST4qWB_register_Asm_16:
9947   case ARM::VST4qWB_register_Asm_32: {
9948     MCInst TmpInst;
9949     unsigned Spacing;
9950     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9951     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9952     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9953     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9954     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9955     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9956     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9957                                             Spacing));
9958     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9959                                             Spacing * 2));
9960     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9961                                             Spacing * 3));
9962     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9963     TmpInst.addOperand(Inst.getOperand(5));
9964     Inst = TmpInst;
9965     return true;
9966   }
9967 
9968   // Handle encoding choice for the shift-immediate instructions.
9969   case ARM::t2LSLri:
9970   case ARM::t2LSRri:
9971   case ARM::t2ASRri:
9972     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
9973         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9974         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
9975         !HasWideQualifier) {
9976       unsigned NewOpc;
9977       switch (Inst.getOpcode()) {
9978       default: llvm_unreachable("unexpected opcode");
9979       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
9980       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
9981       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
9982       }
9983       // The Thumb1 operands aren't in the same order. Awesome, eh?
9984       MCInst TmpInst;
9985       TmpInst.setOpcode(NewOpc);
9986       TmpInst.addOperand(Inst.getOperand(0));
9987       TmpInst.addOperand(Inst.getOperand(5));
9988       TmpInst.addOperand(Inst.getOperand(1));
9989       TmpInst.addOperand(Inst.getOperand(2));
9990       TmpInst.addOperand(Inst.getOperand(3));
9991       TmpInst.addOperand(Inst.getOperand(4));
9992       Inst = TmpInst;
9993       return true;
9994     }
9995     return false;
9996 
9997   // Handle the Thumb2 mode MOV complex aliases.
9998   case ARM::t2MOVsr:
9999   case ARM::t2MOVSsr: {
10000     // Which instruction to expand to depends on the CCOut operand and
10001     // whether we're in an IT block if the register operands are low
10002     // registers.
10003     bool isNarrow = false;
10004     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
10005         isARMLowRegister(Inst.getOperand(1).getReg()) &&
10006         isARMLowRegister(Inst.getOperand(2).getReg()) &&
10007         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
10008         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr) &&
10009         !HasWideQualifier)
10010       isNarrow = true;
10011     MCInst TmpInst;
10012     unsigned newOpc;
10013     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
10014     default: llvm_unreachable("unexpected opcode!");
10015     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
10016     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
10017     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
10018     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
10019     }
10020     TmpInst.setOpcode(newOpc);
10021     TmpInst.addOperand(Inst.getOperand(0)); // Rd
10022     if (isNarrow)
10023       TmpInst.addOperand(MCOperand::createReg(
10024           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
10025     TmpInst.addOperand(Inst.getOperand(1)); // Rn
10026     TmpInst.addOperand(Inst.getOperand(2)); // Rm
10027     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
10028     TmpInst.addOperand(Inst.getOperand(5));
10029     if (!isNarrow)
10030       TmpInst.addOperand(MCOperand::createReg(
10031           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
10032     Inst = TmpInst;
10033     return true;
10034   }
10035   case ARM::t2MOVsi:
10036   case ARM::t2MOVSsi: {
10037     // Which instruction to expand to depends on the CCOut operand and
10038     // whether we're in an IT block if the register operands are low
10039     // registers.
10040     bool isNarrow = false;
10041     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
10042         isARMLowRegister(Inst.getOperand(1).getReg()) &&
10043         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi) &&
10044         !HasWideQualifier)
10045       isNarrow = true;
10046     MCInst TmpInst;
10047     unsigned newOpc;
10048     unsigned Shift = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
10049     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
10050     bool isMov = false;
10051     // MOV rd, rm, LSL #0 is actually a MOV instruction
10052     if (Shift == ARM_AM::lsl && Amount == 0) {
10053       isMov = true;
10054       // The 16-bit encoding of MOV rd, rm, LSL #N is explicitly encoding T2 of
10055       // MOV (register) in the ARMv8-A and ARMv8-M manuals, and immediate 0 is
10056       // unpredictable in an IT block so the 32-bit encoding T3 has to be used
10057       // instead.
10058       if (inITBlock()) {
10059         isNarrow = false;
10060       }
10061       newOpc = isNarrow ? ARM::tMOVSr : ARM::t2MOVr;
10062     } else {
10063       switch(Shift) {
10064       default: llvm_unreachable("unexpected opcode!");
10065       case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
10066       case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
10067       case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
10068       case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
10069       case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
10070       }
10071     }
10072     if (Amount == 32) Amount = 0;
10073     TmpInst.setOpcode(newOpc);
10074     TmpInst.addOperand(Inst.getOperand(0)); // Rd
10075     if (isNarrow && !isMov)
10076       TmpInst.addOperand(MCOperand::createReg(
10077           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
10078     TmpInst.addOperand(Inst.getOperand(1)); // Rn
10079     if (newOpc != ARM::t2RRX && !isMov)
10080       TmpInst.addOperand(MCOperand::createImm(Amount));
10081     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
10082     TmpInst.addOperand(Inst.getOperand(4));
10083     if (!isNarrow)
10084       TmpInst.addOperand(MCOperand::createReg(
10085           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
10086     Inst = TmpInst;
10087     return true;
10088   }
10089   // Handle the ARM mode MOV complex aliases.
10090   case ARM::ASRr:
10091   case ARM::LSRr:
10092   case ARM::LSLr:
10093   case ARM::RORr: {
10094     ARM_AM::ShiftOpc ShiftTy;
10095     switch(Inst.getOpcode()) {
10096     default: llvm_unreachable("unexpected opcode!");
10097     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
10098     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
10099     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
10100     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
10101     }
10102     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
10103     MCInst TmpInst;
10104     TmpInst.setOpcode(ARM::MOVsr);
10105     TmpInst.addOperand(Inst.getOperand(0)); // Rd
10106     TmpInst.addOperand(Inst.getOperand(1)); // Rn
10107     TmpInst.addOperand(Inst.getOperand(2)); // Rm
10108     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
10109     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
10110     TmpInst.addOperand(Inst.getOperand(4));
10111     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
10112     Inst = TmpInst;
10113     return true;
10114   }
10115   case ARM::ASRi:
10116   case ARM::LSRi:
10117   case ARM::LSLi:
10118   case ARM::RORi: {
10119     ARM_AM::ShiftOpc ShiftTy;
10120     switch(Inst.getOpcode()) {
10121     default: llvm_unreachable("unexpected opcode!");
10122     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
10123     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
10124     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
10125     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
10126     }
10127     // A shift by zero is a plain MOVr, not a MOVsi.
10128     unsigned Amt = Inst.getOperand(2).getImm();
10129     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
10130     // A shift by 32 should be encoded as 0 when permitted
10131     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
10132       Amt = 0;
10133     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
10134     MCInst TmpInst;
10135     TmpInst.setOpcode(Opc);
10136     TmpInst.addOperand(Inst.getOperand(0)); // Rd
10137     TmpInst.addOperand(Inst.getOperand(1)); // Rn
10138     if (Opc == ARM::MOVsi)
10139       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
10140     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
10141     TmpInst.addOperand(Inst.getOperand(4));
10142     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
10143     Inst = TmpInst;
10144     return true;
10145   }
10146   case ARM::RRXi: {
10147     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
10148     MCInst TmpInst;
10149     TmpInst.setOpcode(ARM::MOVsi);
10150     TmpInst.addOperand(Inst.getOperand(0)); // Rd
10151     TmpInst.addOperand(Inst.getOperand(1)); // Rn
10152     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
10153     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
10154     TmpInst.addOperand(Inst.getOperand(3));
10155     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
10156     Inst = TmpInst;
10157     return true;
10158   }
10159   case ARM::t2LDMIA_UPD: {
10160     // If this is a load of a single register, then we should use
10161     // a post-indexed LDR instruction instead, per the ARM ARM.
10162     if (Inst.getNumOperands() != 5)
10163       return false;
10164     MCInst TmpInst;
10165     TmpInst.setOpcode(ARM::t2LDR_POST);
10166     TmpInst.addOperand(Inst.getOperand(4)); // Rt
10167     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
10168     TmpInst.addOperand(Inst.getOperand(1)); // Rn
10169     TmpInst.addOperand(MCOperand::createImm(4));
10170     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
10171     TmpInst.addOperand(Inst.getOperand(3));
10172     Inst = TmpInst;
10173     return true;
10174   }
10175   case ARM::t2STMDB_UPD: {
10176     // If this is a store of a single register, then we should use
10177     // a pre-indexed STR instruction instead, per the ARM ARM.
10178     if (Inst.getNumOperands() != 5)
10179       return false;
10180     MCInst TmpInst;
10181     TmpInst.setOpcode(ARM::t2STR_PRE);
10182     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
10183     TmpInst.addOperand(Inst.getOperand(4)); // Rt
10184     TmpInst.addOperand(Inst.getOperand(1)); // Rn
10185     TmpInst.addOperand(MCOperand::createImm(-4));
10186     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
10187     TmpInst.addOperand(Inst.getOperand(3));
10188     Inst = TmpInst;
10189     return true;
10190   }
10191   case ARM::LDMIA_UPD:
10192     // If this is a load of a single register via a 'pop', then we should use
10193     // a post-indexed LDR instruction instead, per the ARM ARM.
10194     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
10195         Inst.getNumOperands() == 5) {
10196       MCInst TmpInst;
10197       TmpInst.setOpcode(ARM::LDR_POST_IMM);
10198       TmpInst.addOperand(Inst.getOperand(4)); // Rt
10199       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
10200       TmpInst.addOperand(Inst.getOperand(1)); // Rn
10201       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
10202       TmpInst.addOperand(MCOperand::createImm(4));
10203       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
10204       TmpInst.addOperand(Inst.getOperand(3));
10205       Inst = TmpInst;
10206       return true;
10207     }
10208     break;
10209   case ARM::STMDB_UPD:
10210     // If this is a store of a single register via a 'push', then we should use
10211     // a pre-indexed STR instruction instead, per the ARM ARM.
10212     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
10213         Inst.getNumOperands() == 5) {
10214       MCInst TmpInst;
10215       TmpInst.setOpcode(ARM::STR_PRE_IMM);
10216       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
10217       TmpInst.addOperand(Inst.getOperand(4)); // Rt
10218       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
10219       TmpInst.addOperand(MCOperand::createImm(-4));
10220       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
10221       TmpInst.addOperand(Inst.getOperand(3));
10222       Inst = TmpInst;
10223     }
10224     break;
10225   case ARM::t2ADDri12:
10226   case ARM::t2SUBri12:
10227   case ARM::t2ADDspImm12:
10228   case ARM::t2SUBspImm12: {
10229     // If the immediate fits for encoding T3 and the generic
10230     // mnemonic was used, encoding T3 is preferred.
10231     const StringRef Token = static_cast<ARMOperand &>(*Operands[0]).getToken();
10232     if ((Token != "add" && Token != "sub") ||
10233         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
10234       break;
10235     switch (Inst.getOpcode()) {
10236     case ARM::t2ADDri12:
10237       Inst.setOpcode(ARM::t2ADDri);
10238       break;
10239     case ARM::t2SUBri12:
10240       Inst.setOpcode(ARM::t2SUBri);
10241       break;
10242     case ARM::t2ADDspImm12:
10243       Inst.setOpcode(ARM::t2ADDspImm);
10244       break;
10245     case ARM::t2SUBspImm12:
10246       Inst.setOpcode(ARM::t2SUBspImm);
10247       break;
10248     }
10249 
10250     Inst.addOperand(MCOperand::createReg(0)); // cc_out
10251     return true;
10252   }
10253   case ARM::tADDi8:
10254     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
10255     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
10256     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
10257     // to encoding T1 if <Rd> is omitted."
10258     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
10259       Inst.setOpcode(ARM::tADDi3);
10260       return true;
10261     }
10262     break;
10263   case ARM::tSUBi8:
10264     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
10265     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
10266     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
10267     // to encoding T1 if <Rd> is omitted."
10268     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
10269       Inst.setOpcode(ARM::tSUBi3);
10270       return true;
10271     }
10272     break;
10273   case ARM::t2ADDri:
10274   case ARM::t2SUBri: {
10275     // If the destination and first source operand are the same, and
10276     // the flags are compatible with the current IT status, use encoding T2
10277     // instead of T3. For compatibility with the system 'as'. Make sure the
10278     // wide encoding wasn't explicit.
10279     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
10280         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
10281         (Inst.getOperand(2).isImm() &&
10282          (unsigned)Inst.getOperand(2).getImm() > 255) ||
10283         Inst.getOperand(5).getReg() != (inITBlock() ? 0 : ARM::CPSR) ||
10284         HasWideQualifier)
10285       break;
10286     MCInst TmpInst;
10287     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
10288                       ARM::tADDi8 : ARM::tSUBi8);
10289     TmpInst.addOperand(Inst.getOperand(0));
10290     TmpInst.addOperand(Inst.getOperand(5));
10291     TmpInst.addOperand(Inst.getOperand(0));
10292     TmpInst.addOperand(Inst.getOperand(2));
10293     TmpInst.addOperand(Inst.getOperand(3));
10294     TmpInst.addOperand(Inst.getOperand(4));
10295     Inst = TmpInst;
10296     return true;
10297   }
10298   case ARM::t2ADDspImm:
10299   case ARM::t2SUBspImm: {
10300     // Prefer T1 encoding if possible
10301     if (Inst.getOperand(5).getReg() != 0 || HasWideQualifier)
10302       break;
10303     unsigned V = Inst.getOperand(2).getImm();
10304     if (V & 3 || V > ((1 << 7) - 1) << 2)
10305       break;
10306     MCInst TmpInst;
10307     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDspImm ? ARM::tADDspi
10308                                                           : ARM::tSUBspi);
10309     TmpInst.addOperand(MCOperand::createReg(ARM::SP)); // destination reg
10310     TmpInst.addOperand(MCOperand::createReg(ARM::SP)); // source reg
10311     TmpInst.addOperand(MCOperand::createImm(V / 4));   // immediate
10312     TmpInst.addOperand(Inst.getOperand(3));            // pred
10313     TmpInst.addOperand(Inst.getOperand(4));
10314     Inst = TmpInst;
10315     return true;
10316   }
10317   case ARM::t2ADDrr: {
10318     // If the destination and first source operand are the same, and
10319     // there's no setting of the flags, use encoding T2 instead of T3.
10320     // Note that this is only for ADD, not SUB. This mirrors the system
10321     // 'as' behaviour.  Also take advantage of ADD being commutative.
10322     // Make sure the wide encoding wasn't explicit.
10323     bool Swap = false;
10324     auto DestReg = Inst.getOperand(0).getReg();
10325     bool Transform = DestReg == Inst.getOperand(1).getReg();
10326     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
10327       Transform = true;
10328       Swap = true;
10329     }
10330     if (!Transform ||
10331         Inst.getOperand(5).getReg() != 0 ||
10332         HasWideQualifier)
10333       break;
10334     MCInst TmpInst;
10335     TmpInst.setOpcode(ARM::tADDhirr);
10336     TmpInst.addOperand(Inst.getOperand(0));
10337     TmpInst.addOperand(Inst.getOperand(0));
10338     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
10339     TmpInst.addOperand(Inst.getOperand(3));
10340     TmpInst.addOperand(Inst.getOperand(4));
10341     Inst = TmpInst;
10342     return true;
10343   }
10344   case ARM::tADDrSP:
10345     // If the non-SP source operand and the destination operand are not the
10346     // same, we need to use the 32-bit encoding if it's available.
10347     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
10348       Inst.setOpcode(ARM::t2ADDrr);
10349       Inst.addOperand(MCOperand::createReg(0)); // cc_out
10350       return true;
10351     }
10352     break;
10353   case ARM::tB:
10354     // A Thumb conditional branch outside of an IT block is a tBcc.
10355     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
10356       Inst.setOpcode(ARM::tBcc);
10357       return true;
10358     }
10359     break;
10360   case ARM::t2B:
10361     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
10362     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
10363       Inst.setOpcode(ARM::t2Bcc);
10364       return true;
10365     }
10366     break;
10367   case ARM::t2Bcc:
10368     // If the conditional is AL or we're in an IT block, we really want t2B.
10369     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
10370       Inst.setOpcode(ARM::t2B);
10371       return true;
10372     }
10373     break;
10374   case ARM::tBcc:
10375     // If the conditional is AL, we really want tB.
10376     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
10377       Inst.setOpcode(ARM::tB);
10378       return true;
10379     }
10380     break;
10381   case ARM::tLDMIA: {
10382     // If the register list contains any high registers, or if the writeback
10383     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
10384     // instead if we're in Thumb2. Otherwise, this should have generated
10385     // an error in validateInstruction().
10386     unsigned Rn = Inst.getOperand(0).getReg();
10387     bool hasWritebackToken =
10388         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
10389          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
10390     bool listContainsBase;
10391     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
10392         (!listContainsBase && !hasWritebackToken) ||
10393         (listContainsBase && hasWritebackToken)) {
10394       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
10395       assert(isThumbTwo());
10396       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
10397       // If we're switching to the updating version, we need to insert
10398       // the writeback tied operand.
10399       if (hasWritebackToken)
10400         Inst.insert(Inst.begin(),
10401                     MCOperand::createReg(Inst.getOperand(0).getReg()));
10402       return true;
10403     }
10404     break;
10405   }
10406   case ARM::tSTMIA_UPD: {
10407     // If the register list contains any high registers, we need to use
10408     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
10409     // should have generated an error in validateInstruction().
10410     unsigned Rn = Inst.getOperand(0).getReg();
10411     bool listContainsBase;
10412     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
10413       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
10414       assert(isThumbTwo());
10415       Inst.setOpcode(ARM::t2STMIA_UPD);
10416       return true;
10417     }
10418     break;
10419   }
10420   case ARM::tPOP: {
10421     bool listContainsBase;
10422     // If the register list contains any high registers, we need to use
10423     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
10424     // should have generated an error in validateInstruction().
10425     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
10426       return false;
10427     assert(isThumbTwo());
10428     Inst.setOpcode(ARM::t2LDMIA_UPD);
10429     // Add the base register and writeback operands.
10430     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
10431     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
10432     return true;
10433   }
10434   case ARM::tPUSH: {
10435     bool listContainsBase;
10436     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
10437       return false;
10438     assert(isThumbTwo());
10439     Inst.setOpcode(ARM::t2STMDB_UPD);
10440     // Add the base register and writeback operands.
10441     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
10442     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
10443     return true;
10444   }
10445   case ARM::t2MOVi:
10446     // If we can use the 16-bit encoding and the user didn't explicitly
10447     // request the 32-bit variant, transform it here.
10448     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
10449         (Inst.getOperand(1).isImm() &&
10450          (unsigned)Inst.getOperand(1).getImm() <= 255) &&
10451         Inst.getOperand(4).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
10452         !HasWideQualifier) {
10453       // The operands aren't in the same order for tMOVi8...
10454       MCInst TmpInst;
10455       TmpInst.setOpcode(ARM::tMOVi8);
10456       TmpInst.addOperand(Inst.getOperand(0));
10457       TmpInst.addOperand(Inst.getOperand(4));
10458       TmpInst.addOperand(Inst.getOperand(1));
10459       TmpInst.addOperand(Inst.getOperand(2));
10460       TmpInst.addOperand(Inst.getOperand(3));
10461       Inst = TmpInst;
10462       return true;
10463     }
10464     break;
10465 
10466   case ARM::t2MOVr:
10467     // If we can use the 16-bit encoding and the user didn't explicitly
10468     // request the 32-bit variant, transform it here.
10469     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
10470         isARMLowRegister(Inst.getOperand(1).getReg()) &&
10471         Inst.getOperand(2).getImm() == ARMCC::AL &&
10472         Inst.getOperand(4).getReg() == ARM::CPSR &&
10473         !HasWideQualifier) {
10474       // The operands aren't the same for tMOV[S]r... (no cc_out)
10475       MCInst TmpInst;
10476       unsigned Op = Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr;
10477       TmpInst.setOpcode(Op);
10478       TmpInst.addOperand(Inst.getOperand(0));
10479       TmpInst.addOperand(Inst.getOperand(1));
10480       if (Op == ARM::tMOVr) {
10481         TmpInst.addOperand(Inst.getOperand(2));
10482         TmpInst.addOperand(Inst.getOperand(3));
10483       }
10484       Inst = TmpInst;
10485       return true;
10486     }
10487     break;
10488 
10489   case ARM::t2SXTH:
10490   case ARM::t2SXTB:
10491   case ARM::t2UXTH:
10492   case ARM::t2UXTB:
10493     // If we can use the 16-bit encoding and the user didn't explicitly
10494     // request the 32-bit variant, transform it here.
10495     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
10496         isARMLowRegister(Inst.getOperand(1).getReg()) &&
10497         Inst.getOperand(2).getImm() == 0 &&
10498         !HasWideQualifier) {
10499       unsigned NewOpc;
10500       switch (Inst.getOpcode()) {
10501       default: llvm_unreachable("Illegal opcode!");
10502       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
10503       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
10504       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
10505       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
10506       }
10507       // The operands aren't the same for thumb1 (no rotate operand).
10508       MCInst TmpInst;
10509       TmpInst.setOpcode(NewOpc);
10510       TmpInst.addOperand(Inst.getOperand(0));
10511       TmpInst.addOperand(Inst.getOperand(1));
10512       TmpInst.addOperand(Inst.getOperand(3));
10513       TmpInst.addOperand(Inst.getOperand(4));
10514       Inst = TmpInst;
10515       return true;
10516     }
10517     break;
10518 
10519   case ARM::MOVsi: {
10520     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
10521     // rrx shifts and asr/lsr of #32 is encoded as 0
10522     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr)
10523       return false;
10524     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
10525       // Shifting by zero is accepted as a vanilla 'MOVr'
10526       MCInst TmpInst;
10527       TmpInst.setOpcode(ARM::MOVr);
10528       TmpInst.addOperand(Inst.getOperand(0));
10529       TmpInst.addOperand(Inst.getOperand(1));
10530       TmpInst.addOperand(Inst.getOperand(3));
10531       TmpInst.addOperand(Inst.getOperand(4));
10532       TmpInst.addOperand(Inst.getOperand(5));
10533       Inst = TmpInst;
10534       return true;
10535     }
10536     return false;
10537   }
10538   case ARM::ANDrsi:
10539   case ARM::ORRrsi:
10540   case ARM::EORrsi:
10541   case ARM::BICrsi:
10542   case ARM::SUBrsi:
10543   case ARM::ADDrsi: {
10544     unsigned newOpc;
10545     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
10546     if (SOpc == ARM_AM::rrx) return false;
10547     switch (Inst.getOpcode()) {
10548     default: llvm_unreachable("unexpected opcode!");
10549     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
10550     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
10551     case ARM::EORrsi: newOpc = ARM::EORrr; break;
10552     case ARM::BICrsi: newOpc = ARM::BICrr; break;
10553     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
10554     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
10555     }
10556     // If the shift is by zero, use the non-shifted instruction definition.
10557     // The exception is for right shifts, where 0 == 32
10558     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
10559         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
10560       MCInst TmpInst;
10561       TmpInst.setOpcode(newOpc);
10562       TmpInst.addOperand(Inst.getOperand(0));
10563       TmpInst.addOperand(Inst.getOperand(1));
10564       TmpInst.addOperand(Inst.getOperand(2));
10565       TmpInst.addOperand(Inst.getOperand(4));
10566       TmpInst.addOperand(Inst.getOperand(5));
10567       TmpInst.addOperand(Inst.getOperand(6));
10568       Inst = TmpInst;
10569       return true;
10570     }
10571     return false;
10572   }
10573   case ARM::ITasm:
10574   case ARM::t2IT: {
10575     // Set up the IT block state according to the IT instruction we just
10576     // matched.
10577     assert(!inITBlock() && "nested IT blocks?!");
10578     startExplicitITBlock(ARMCC::CondCodes(Inst.getOperand(0).getImm()),
10579                          Inst.getOperand(1).getImm());
10580     break;
10581   }
10582   case ARM::t2LSLrr:
10583   case ARM::t2LSRrr:
10584   case ARM::t2ASRrr:
10585   case ARM::t2SBCrr:
10586   case ARM::t2RORrr:
10587   case ARM::t2BICrr:
10588     // Assemblers should use the narrow encodings of these instructions when permissible.
10589     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
10590          isARMLowRegister(Inst.getOperand(2).getReg())) &&
10591         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
10592         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
10593         !HasWideQualifier) {
10594       unsigned NewOpc;
10595       switch (Inst.getOpcode()) {
10596         default: llvm_unreachable("unexpected opcode");
10597         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
10598         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
10599         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
10600         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
10601         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
10602         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
10603       }
10604       MCInst TmpInst;
10605       TmpInst.setOpcode(NewOpc);
10606       TmpInst.addOperand(Inst.getOperand(0));
10607       TmpInst.addOperand(Inst.getOperand(5));
10608       TmpInst.addOperand(Inst.getOperand(1));
10609       TmpInst.addOperand(Inst.getOperand(2));
10610       TmpInst.addOperand(Inst.getOperand(3));
10611       TmpInst.addOperand(Inst.getOperand(4));
10612       Inst = TmpInst;
10613       return true;
10614     }
10615     return false;
10616 
10617   case ARM::t2ANDrr:
10618   case ARM::t2EORrr:
10619   case ARM::t2ADCrr:
10620   case ARM::t2ORRrr:
10621     // Assemblers should use the narrow encodings of these instructions when permissible.
10622     // These instructions are special in that they are commutable, so shorter encodings
10623     // are available more often.
10624     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
10625          isARMLowRegister(Inst.getOperand(2).getReg())) &&
10626         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
10627          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
10628         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
10629         !HasWideQualifier) {
10630       unsigned NewOpc;
10631       switch (Inst.getOpcode()) {
10632         default: llvm_unreachable("unexpected opcode");
10633         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
10634         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
10635         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
10636         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
10637       }
10638       MCInst TmpInst;
10639       TmpInst.setOpcode(NewOpc);
10640       TmpInst.addOperand(Inst.getOperand(0));
10641       TmpInst.addOperand(Inst.getOperand(5));
10642       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
10643         TmpInst.addOperand(Inst.getOperand(1));
10644         TmpInst.addOperand(Inst.getOperand(2));
10645       } else {
10646         TmpInst.addOperand(Inst.getOperand(2));
10647         TmpInst.addOperand(Inst.getOperand(1));
10648       }
10649       TmpInst.addOperand(Inst.getOperand(3));
10650       TmpInst.addOperand(Inst.getOperand(4));
10651       Inst = TmpInst;
10652       return true;
10653     }
10654     return false;
10655   case ARM::MVE_VPST:
10656   case ARM::MVE_VPTv16i8:
10657   case ARM::MVE_VPTv8i16:
10658   case ARM::MVE_VPTv4i32:
10659   case ARM::MVE_VPTv16u8:
10660   case ARM::MVE_VPTv8u16:
10661   case ARM::MVE_VPTv4u32:
10662   case ARM::MVE_VPTv16s8:
10663   case ARM::MVE_VPTv8s16:
10664   case ARM::MVE_VPTv4s32:
10665   case ARM::MVE_VPTv4f32:
10666   case ARM::MVE_VPTv8f16:
10667   case ARM::MVE_VPTv16i8r:
10668   case ARM::MVE_VPTv8i16r:
10669   case ARM::MVE_VPTv4i32r:
10670   case ARM::MVE_VPTv16u8r:
10671   case ARM::MVE_VPTv8u16r:
10672   case ARM::MVE_VPTv4u32r:
10673   case ARM::MVE_VPTv16s8r:
10674   case ARM::MVE_VPTv8s16r:
10675   case ARM::MVE_VPTv4s32r:
10676   case ARM::MVE_VPTv4f32r:
10677   case ARM::MVE_VPTv8f16r: {
10678     assert(!inVPTBlock() && "Nested VPT blocks are not allowed");
10679     MCOperand &MO = Inst.getOperand(0);
10680     VPTState.Mask = MO.getImm();
10681     VPTState.CurPosition = 0;
10682     break;
10683   }
10684   }
10685   return false;
10686 }
10687 
checkTargetMatchPredicate(MCInst & Inst)10688 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
10689   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
10690   // suffix depending on whether they're in an IT block or not.
10691   unsigned Opc = Inst.getOpcode();
10692   const MCInstrDesc &MCID = MII.get(Opc);
10693   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
10694     assert(MCID.hasOptionalDef() &&
10695            "optionally flag setting instruction missing optional def operand");
10696     assert(MCID.NumOperands == Inst.getNumOperands() &&
10697            "operand count mismatch!");
10698     // Find the optional-def operand (cc_out).
10699     unsigned OpNo;
10700     for (OpNo = 0;
10701          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
10702          ++OpNo)
10703       ;
10704     // If we're parsing Thumb1, reject it completely.
10705     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
10706       return Match_RequiresFlagSetting;
10707     // If we're parsing Thumb2, which form is legal depends on whether we're
10708     // in an IT block.
10709     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
10710         !inITBlock())
10711       return Match_RequiresITBlock;
10712     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
10713         inITBlock())
10714       return Match_RequiresNotITBlock;
10715     // LSL with zero immediate is not allowed in an IT block
10716     if (Opc == ARM::tLSLri && Inst.getOperand(3).getImm() == 0 && inITBlock())
10717       return Match_RequiresNotITBlock;
10718   } else if (isThumbOne()) {
10719     // Some high-register supporting Thumb1 encodings only allow both registers
10720     // to be from r0-r7 when in Thumb2.
10721     if (Opc == ARM::tADDhirr && !hasV6MOps() &&
10722         isARMLowRegister(Inst.getOperand(1).getReg()) &&
10723         isARMLowRegister(Inst.getOperand(2).getReg()))
10724       return Match_RequiresThumb2;
10725     // Others only require ARMv6 or later.
10726     else if (Opc == ARM::tMOVr && !hasV6Ops() &&
10727              isARMLowRegister(Inst.getOperand(0).getReg()) &&
10728              isARMLowRegister(Inst.getOperand(1).getReg()))
10729       return Match_RequiresV6;
10730   }
10731 
10732   // Before ARMv8 the rules for when SP is allowed in t2MOVr are more complex
10733   // than the loop below can handle, so it uses the GPRnopc register class and
10734   // we do SP handling here.
10735   if (Opc == ARM::t2MOVr && !hasV8Ops())
10736   {
10737     // SP as both source and destination is not allowed
10738     if (Inst.getOperand(0).getReg() == ARM::SP &&
10739         Inst.getOperand(1).getReg() == ARM::SP)
10740       return Match_RequiresV8;
10741     // When flags-setting SP as either source or destination is not allowed
10742     if (Inst.getOperand(4).getReg() == ARM::CPSR &&
10743         (Inst.getOperand(0).getReg() == ARM::SP ||
10744          Inst.getOperand(1).getReg() == ARM::SP))
10745       return Match_RequiresV8;
10746   }
10747 
10748   switch (Inst.getOpcode()) {
10749   case ARM::VMRS:
10750   case ARM::VMSR:
10751   case ARM::VMRS_FPCXTS:
10752   case ARM::VMRS_FPCXTNS:
10753   case ARM::VMSR_FPCXTS:
10754   case ARM::VMSR_FPCXTNS:
10755   case ARM::VMRS_FPSCR_NZCVQC:
10756   case ARM::VMSR_FPSCR_NZCVQC:
10757   case ARM::FMSTAT:
10758   case ARM::VMRS_VPR:
10759   case ARM::VMRS_P0:
10760   case ARM::VMSR_VPR:
10761   case ARM::VMSR_P0:
10762     // Use of SP for VMRS/VMSR is only allowed in ARM mode with the exception of
10763     // ARMv8-A.
10764     if (Inst.getOperand(0).isReg() && Inst.getOperand(0).getReg() == ARM::SP &&
10765         (isThumb() && !hasV8Ops()))
10766       return Match_InvalidOperand;
10767     break;
10768   case ARM::t2TBB:
10769   case ARM::t2TBH:
10770     // Rn = sp is only allowed with ARMv8-A
10771     if (!hasV8Ops() && (Inst.getOperand(0).getReg() == ARM::SP))
10772       return Match_RequiresV8;
10773     break;
10774   default:
10775     break;
10776   }
10777 
10778   for (unsigned I = 0; I < MCID.NumOperands; ++I)
10779     if (MCID.OpInfo[I].RegClass == ARM::rGPRRegClassID) {
10780       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
10781       const auto &Op = Inst.getOperand(I);
10782       if (!Op.isReg()) {
10783         // This can happen in awkward cases with tied operands, e.g. a
10784         // writeback load/store with a complex addressing mode in
10785         // which there's an output operand corresponding to the
10786         // updated written-back base register: the Tablegen-generated
10787         // AsmMatcher will have written a placeholder operand to that
10788         // slot in the form of an immediate 0, because it can't
10789         // generate the register part of the complex addressing-mode
10790         // operand ahead of time.
10791         continue;
10792       }
10793 
10794       unsigned Reg = Op.getReg();
10795       if ((Reg == ARM::SP) && !hasV8Ops())
10796         return Match_RequiresV8;
10797       else if (Reg == ARM::PC)
10798         return Match_InvalidOperand;
10799     }
10800 
10801   return Match_Success;
10802 }
10803 
10804 namespace llvm {
10805 
IsCPSRDead(const MCInst * Instr)10806 template <> inline bool IsCPSRDead<MCInst>(const MCInst *Instr) {
10807   return true; // In an assembly source, no need to second-guess
10808 }
10809 
10810 } // end namespace llvm
10811 
10812 // Returns true if Inst is unpredictable if it is in and IT block, but is not
10813 // the last instruction in the block.
isITBlockTerminator(MCInst & Inst) const10814 bool ARMAsmParser::isITBlockTerminator(MCInst &Inst) const {
10815   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10816 
10817   // All branch & call instructions terminate IT blocks with the exception of
10818   // SVC.
10819   if (MCID.isTerminator() || (MCID.isCall() && Inst.getOpcode() != ARM::tSVC) ||
10820       MCID.isReturn() || MCID.isBranch() || MCID.isIndirectBranch())
10821     return true;
10822 
10823   // Any arithmetic instruction which writes to the PC also terminates the IT
10824   // block.
10825   if (MCID.hasDefOfPhysReg(Inst, ARM::PC, *MRI))
10826     return true;
10827 
10828   return false;
10829 }
10830 
MatchInstruction(OperandVector & Operands,MCInst & Inst,SmallVectorImpl<NearMissInfo> & NearMisses,bool MatchingInlineAsm,bool & EmitInITBlock,MCStreamer & Out)10831 unsigned ARMAsmParser::MatchInstruction(OperandVector &Operands, MCInst &Inst,
10832                                           SmallVectorImpl<NearMissInfo> &NearMisses,
10833                                           bool MatchingInlineAsm,
10834                                           bool &EmitInITBlock,
10835                                           MCStreamer &Out) {
10836   // If we can't use an implicit IT block here, just match as normal.
10837   if (inExplicitITBlock() || !isThumbTwo() || !useImplicitITThumb())
10838     return MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
10839 
10840   // Try to match the instruction in an extension of the current IT block (if
10841   // there is one).
10842   if (inImplicitITBlock()) {
10843     extendImplicitITBlock(ITState.Cond);
10844     if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
10845             Match_Success) {
10846       // The match succeded, but we still have to check that the instruction is
10847       // valid in this implicit IT block.
10848       const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10849       if (MCID.isPredicable()) {
10850         ARMCC::CondCodes InstCond =
10851             (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
10852                 .getImm();
10853         ARMCC::CondCodes ITCond = currentITCond();
10854         if (InstCond == ITCond) {
10855           EmitInITBlock = true;
10856           return Match_Success;
10857         } else if (InstCond == ARMCC::getOppositeCondition(ITCond)) {
10858           invertCurrentITCondition();
10859           EmitInITBlock = true;
10860           return Match_Success;
10861         }
10862       }
10863     }
10864     rewindImplicitITPosition();
10865   }
10866 
10867   // Finish the current IT block, and try to match outside any IT block.
10868   flushPendingInstructions(Out);
10869   unsigned PlainMatchResult =
10870       MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
10871   if (PlainMatchResult == Match_Success) {
10872     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10873     if (MCID.isPredicable()) {
10874       ARMCC::CondCodes InstCond =
10875           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
10876               .getImm();
10877       // Some forms of the branch instruction have their own condition code
10878       // fields, so can be conditionally executed without an IT block.
10879       if (Inst.getOpcode() == ARM::tBcc || Inst.getOpcode() == ARM::t2Bcc) {
10880         EmitInITBlock = false;
10881         return Match_Success;
10882       }
10883       if (InstCond == ARMCC::AL) {
10884         EmitInITBlock = false;
10885         return Match_Success;
10886       }
10887     } else {
10888       EmitInITBlock = false;
10889       return Match_Success;
10890     }
10891   }
10892 
10893   // Try to match in a new IT block. The matcher doesn't check the actual
10894   // condition, so we create an IT block with a dummy condition, and fix it up
10895   // once we know the actual condition.
10896   startImplicitITBlock();
10897   if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
10898       Match_Success) {
10899     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10900     if (MCID.isPredicable()) {
10901       ITState.Cond =
10902           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
10903               .getImm();
10904       EmitInITBlock = true;
10905       return Match_Success;
10906     }
10907   }
10908   discardImplicitITBlock();
10909 
10910   // If none of these succeed, return the error we got when trying to match
10911   // outside any IT blocks.
10912   EmitInITBlock = false;
10913   return PlainMatchResult;
10914 }
10915 
10916 static std::string ARMMnemonicSpellCheck(StringRef S, const FeatureBitset &FBS,
10917                                          unsigned VariantID = 0);
10918 
10919 static const char *getSubtargetFeatureName(uint64_t Val);
MatchAndEmitInstruction(SMLoc IDLoc,unsigned & Opcode,OperandVector & Operands,MCStreamer & Out,uint64_t & ErrorInfo,bool MatchingInlineAsm)10920 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
10921                                            OperandVector &Operands,
10922                                            MCStreamer &Out, uint64_t &ErrorInfo,
10923                                            bool MatchingInlineAsm) {
10924   MCInst Inst;
10925   unsigned MatchResult;
10926   bool PendConditionalInstruction = false;
10927 
10928   SmallVector<NearMissInfo, 4> NearMisses;
10929   MatchResult = MatchInstruction(Operands, Inst, NearMisses, MatchingInlineAsm,
10930                                  PendConditionalInstruction, Out);
10931 
10932   switch (MatchResult) {
10933   case Match_Success:
10934     LLVM_DEBUG(dbgs() << "Parsed as: ";
10935                Inst.dump_pretty(dbgs(), MII.getName(Inst.getOpcode()));
10936                dbgs() << "\n");
10937 
10938     // Context sensitive operand constraints aren't handled by the matcher,
10939     // so check them here.
10940     if (validateInstruction(Inst, Operands)) {
10941       // Still progress the IT block, otherwise one wrong condition causes
10942       // nasty cascading errors.
10943       forwardITPosition();
10944       forwardVPTPosition();
10945       return true;
10946     }
10947 
10948     { // processInstruction() updates inITBlock state, we need to save it away
10949       bool wasInITBlock = inITBlock();
10950 
10951       // Some instructions need post-processing to, for example, tweak which
10952       // encoding is selected. Loop on it while changes happen so the
10953       // individual transformations can chain off each other. E.g.,
10954       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
10955       while (processInstruction(Inst, Operands, Out))
10956         LLVM_DEBUG(dbgs() << "Changed to: ";
10957                    Inst.dump_pretty(dbgs(), MII.getName(Inst.getOpcode()));
10958                    dbgs() << "\n");
10959 
10960       // Only after the instruction is fully processed, we can validate it
10961       if (wasInITBlock && hasV8Ops() && isThumb() &&
10962           !isV8EligibleForIT(&Inst)) {
10963         Warning(IDLoc, "deprecated instruction in IT block");
10964       }
10965     }
10966 
10967     // Only move forward at the very end so that everything in validate
10968     // and process gets a consistent answer about whether we're in an IT
10969     // block.
10970     forwardITPosition();
10971     forwardVPTPosition();
10972 
10973     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
10974     // doesn't actually encode.
10975     if (Inst.getOpcode() == ARM::ITasm)
10976       return false;
10977 
10978     Inst.setLoc(IDLoc);
10979     if (PendConditionalInstruction) {
10980       PendingConditionalInsts.push_back(Inst);
10981       if (isITBlockFull() || isITBlockTerminator(Inst))
10982         flushPendingInstructions(Out);
10983     } else {
10984       Out.emitInstruction(Inst, getSTI());
10985     }
10986     return false;
10987   case Match_NearMisses:
10988     ReportNearMisses(NearMisses, IDLoc, Operands);
10989     return true;
10990   case Match_MnemonicFail: {
10991     FeatureBitset FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
10992     std::string Suggestion = ARMMnemonicSpellCheck(
10993       ((ARMOperand &)*Operands[0]).getToken(), FBS);
10994     return Error(IDLoc, "invalid instruction" + Suggestion,
10995                  ((ARMOperand &)*Operands[0]).getLocRange());
10996   }
10997   }
10998 
10999   llvm_unreachable("Implement any new match types added!");
11000 }
11001 
11002 /// parseDirective parses the arm specific directives
ParseDirective(AsmToken DirectiveID)11003 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
11004   const MCContext::Environment Format = getContext().getObjectFileType();
11005   bool IsMachO = Format == MCContext::IsMachO;
11006   bool IsCOFF = Format == MCContext::IsCOFF;
11007 
11008   std::string IDVal = DirectiveID.getIdentifier().lower();
11009   if (IDVal == ".word")
11010     parseLiteralValues(4, DirectiveID.getLoc());
11011   else if (IDVal == ".short" || IDVal == ".hword")
11012     parseLiteralValues(2, DirectiveID.getLoc());
11013   else if (IDVal == ".thumb")
11014     parseDirectiveThumb(DirectiveID.getLoc());
11015   else if (IDVal == ".arm")
11016     parseDirectiveARM(DirectiveID.getLoc());
11017   else if (IDVal == ".thumb_func")
11018     parseDirectiveThumbFunc(DirectiveID.getLoc());
11019   else if (IDVal == ".code")
11020     parseDirectiveCode(DirectiveID.getLoc());
11021   else if (IDVal == ".syntax")
11022     parseDirectiveSyntax(DirectiveID.getLoc());
11023   else if (IDVal == ".unreq")
11024     parseDirectiveUnreq(DirectiveID.getLoc());
11025   else if (IDVal == ".fnend")
11026     parseDirectiveFnEnd(DirectiveID.getLoc());
11027   else if (IDVal == ".cantunwind")
11028     parseDirectiveCantUnwind(DirectiveID.getLoc());
11029   else if (IDVal == ".personality")
11030     parseDirectivePersonality(DirectiveID.getLoc());
11031   else if (IDVal == ".handlerdata")
11032     parseDirectiveHandlerData(DirectiveID.getLoc());
11033   else if (IDVal == ".setfp")
11034     parseDirectiveSetFP(DirectiveID.getLoc());
11035   else if (IDVal == ".pad")
11036     parseDirectivePad(DirectiveID.getLoc());
11037   else if (IDVal == ".save")
11038     parseDirectiveRegSave(DirectiveID.getLoc(), false);
11039   else if (IDVal == ".vsave")
11040     parseDirectiveRegSave(DirectiveID.getLoc(), true);
11041   else if (IDVal == ".ltorg" || IDVal == ".pool")
11042     parseDirectiveLtorg(DirectiveID.getLoc());
11043   else if (IDVal == ".even")
11044     parseDirectiveEven(DirectiveID.getLoc());
11045   else if (IDVal == ".personalityindex")
11046     parseDirectivePersonalityIndex(DirectiveID.getLoc());
11047   else if (IDVal == ".unwind_raw")
11048     parseDirectiveUnwindRaw(DirectiveID.getLoc());
11049   else if (IDVal == ".movsp")
11050     parseDirectiveMovSP(DirectiveID.getLoc());
11051   else if (IDVal == ".arch_extension")
11052     parseDirectiveArchExtension(DirectiveID.getLoc());
11053   else if (IDVal == ".align")
11054     return parseDirectiveAlign(DirectiveID.getLoc()); // Use Generic on failure.
11055   else if (IDVal == ".thumb_set")
11056     parseDirectiveThumbSet(DirectiveID.getLoc());
11057   else if (IDVal == ".inst")
11058     parseDirectiveInst(DirectiveID.getLoc());
11059   else if (IDVal == ".inst.n")
11060     parseDirectiveInst(DirectiveID.getLoc(), 'n');
11061   else if (IDVal == ".inst.w")
11062     parseDirectiveInst(DirectiveID.getLoc(), 'w');
11063   else if (!IsMachO && !IsCOFF) {
11064     if (IDVal == ".arch")
11065       parseDirectiveArch(DirectiveID.getLoc());
11066     else if (IDVal == ".cpu")
11067       parseDirectiveCPU(DirectiveID.getLoc());
11068     else if (IDVal == ".eabi_attribute")
11069       parseDirectiveEabiAttr(DirectiveID.getLoc());
11070     else if (IDVal == ".fpu")
11071       parseDirectiveFPU(DirectiveID.getLoc());
11072     else if (IDVal == ".fnstart")
11073       parseDirectiveFnStart(DirectiveID.getLoc());
11074     else if (IDVal == ".object_arch")
11075       parseDirectiveObjectArch(DirectiveID.getLoc());
11076     else if (IDVal == ".tlsdescseq")
11077       parseDirectiveTLSDescSeq(DirectiveID.getLoc());
11078     else
11079       return true;
11080   } else
11081     return true;
11082   return false;
11083 }
11084 
11085 /// parseLiteralValues
11086 ///  ::= .hword expression [, expression]*
11087 ///  ::= .short expression [, expression]*
11088 ///  ::= .word expression [, expression]*
parseLiteralValues(unsigned Size,SMLoc L)11089 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
11090   auto parseOne = [&]() -> bool {
11091     const MCExpr *Value;
11092     if (getParser().parseExpression(Value))
11093       return true;
11094     getParser().getStreamer().emitValue(Value, Size, L);
11095     return false;
11096   };
11097   return (parseMany(parseOne));
11098 }
11099 
11100 /// parseDirectiveThumb
11101 ///  ::= .thumb
parseDirectiveThumb(SMLoc L)11102 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
11103   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
11104       check(!hasThumb(), L, "target does not support Thumb mode"))
11105     return true;
11106 
11107   if (!isThumb())
11108     SwitchMode();
11109 
11110   getParser().getStreamer().emitAssemblerFlag(MCAF_Code16);
11111   return false;
11112 }
11113 
11114 /// parseDirectiveARM
11115 ///  ::= .arm
parseDirectiveARM(SMLoc L)11116 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
11117   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
11118       check(!hasARM(), L, "target does not support ARM mode"))
11119     return true;
11120 
11121   if (isThumb())
11122     SwitchMode();
11123   getParser().getStreamer().emitAssemblerFlag(MCAF_Code32);
11124   return false;
11125 }
11126 
doBeforeLabelEmit(MCSymbol * Symbol)11127 void ARMAsmParser::doBeforeLabelEmit(MCSymbol *Symbol) {
11128   // We need to flush the current implicit IT block on a label, because it is
11129   // not legal to branch into an IT block.
11130   flushPendingInstructions(getStreamer());
11131 }
11132 
onLabelParsed(MCSymbol * Symbol)11133 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
11134   if (NextSymbolIsThumb) {
11135     getParser().getStreamer().emitThumbFunc(Symbol);
11136     NextSymbolIsThumb = false;
11137   }
11138 }
11139 
11140 /// parseDirectiveThumbFunc
11141 ///  ::= .thumbfunc symbol_name
parseDirectiveThumbFunc(SMLoc L)11142 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
11143   MCAsmParser &Parser = getParser();
11144   const auto Format = getContext().getObjectFileType();
11145   bool IsMachO = Format == MCContext::IsMachO;
11146 
11147   // Darwin asm has (optionally) function name after .thumb_func direction
11148   // ELF doesn't
11149 
11150   if (IsMachO) {
11151     if (Parser.getTok().is(AsmToken::Identifier) ||
11152         Parser.getTok().is(AsmToken::String)) {
11153       MCSymbol *Func = getParser().getContext().getOrCreateSymbol(
11154           Parser.getTok().getIdentifier());
11155       getParser().getStreamer().emitThumbFunc(Func);
11156       Parser.Lex();
11157       if (parseToken(AsmToken::EndOfStatement,
11158                      "unexpected token in '.thumb_func' directive"))
11159         return true;
11160       return false;
11161     }
11162   }
11163 
11164   if (parseToken(AsmToken::EndOfStatement,
11165                  "unexpected token in '.thumb_func' directive"))
11166     return true;
11167 
11168   // .thumb_func implies .thumb
11169   if (!isThumb())
11170     SwitchMode();
11171 
11172   getParser().getStreamer().emitAssemblerFlag(MCAF_Code16);
11173 
11174   NextSymbolIsThumb = true;
11175   return false;
11176 }
11177 
11178 /// parseDirectiveSyntax
11179 ///  ::= .syntax unified | divided
parseDirectiveSyntax(SMLoc L)11180 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
11181   MCAsmParser &Parser = getParser();
11182   const AsmToken &Tok = Parser.getTok();
11183   if (Tok.isNot(AsmToken::Identifier)) {
11184     Error(L, "unexpected token in .syntax directive");
11185     return false;
11186   }
11187 
11188   StringRef Mode = Tok.getString();
11189   Parser.Lex();
11190   if (check(Mode == "divided" || Mode == "DIVIDED", L,
11191             "'.syntax divided' arm assembly not supported") ||
11192       check(Mode != "unified" && Mode != "UNIFIED", L,
11193             "unrecognized syntax mode in .syntax directive") ||
11194       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11195     return true;
11196 
11197   // TODO tell the MC streamer the mode
11198   // getParser().getStreamer().Emit???();
11199   return false;
11200 }
11201 
11202 /// parseDirectiveCode
11203 ///  ::= .code 16 | 32
parseDirectiveCode(SMLoc L)11204 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
11205   MCAsmParser &Parser = getParser();
11206   const AsmToken &Tok = Parser.getTok();
11207   if (Tok.isNot(AsmToken::Integer))
11208     return Error(L, "unexpected token in .code directive");
11209   int64_t Val = Parser.getTok().getIntVal();
11210   if (Val != 16 && Val != 32) {
11211     Error(L, "invalid operand to .code directive");
11212     return false;
11213   }
11214   Parser.Lex();
11215 
11216   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11217     return true;
11218 
11219   if (Val == 16) {
11220     if (!hasThumb())
11221       return Error(L, "target does not support Thumb mode");
11222 
11223     if (!isThumb())
11224       SwitchMode();
11225     getParser().getStreamer().emitAssemblerFlag(MCAF_Code16);
11226   } else {
11227     if (!hasARM())
11228       return Error(L, "target does not support ARM mode");
11229 
11230     if (isThumb())
11231       SwitchMode();
11232     getParser().getStreamer().emitAssemblerFlag(MCAF_Code32);
11233   }
11234 
11235   return false;
11236 }
11237 
11238 /// parseDirectiveReq
11239 ///  ::= name .req registername
parseDirectiveReq(StringRef Name,SMLoc L)11240 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
11241   MCAsmParser &Parser = getParser();
11242   Parser.Lex(); // Eat the '.req' token.
11243   unsigned Reg;
11244   SMLoc SRegLoc, ERegLoc;
11245   if (check(ParseRegister(Reg, SRegLoc, ERegLoc), SRegLoc,
11246             "register name expected") ||
11247       parseToken(AsmToken::EndOfStatement,
11248                  "unexpected input in .req directive."))
11249     return true;
11250 
11251   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg)
11252     return Error(SRegLoc,
11253                  "redefinition of '" + Name + "' does not match original.");
11254 
11255   return false;
11256 }
11257 
11258 /// parseDirectiveUneq
11259 ///  ::= .unreq registername
parseDirectiveUnreq(SMLoc L)11260 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
11261   MCAsmParser &Parser = getParser();
11262   if (Parser.getTok().isNot(AsmToken::Identifier))
11263     return Error(L, "unexpected input in .unreq directive.");
11264   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
11265   Parser.Lex(); // Eat the identifier.
11266   if (parseToken(AsmToken::EndOfStatement,
11267                  "unexpected input in '.unreq' directive"))
11268     return true;
11269   return false;
11270 }
11271 
11272 // After changing arch/CPU, try to put the ARM/Thumb mode back to what it was
11273 // before, if supported by the new target, or emit mapping symbols for the mode
11274 // switch.
FixModeAfterArchChange(bool WasThumb,SMLoc Loc)11275 void ARMAsmParser::FixModeAfterArchChange(bool WasThumb, SMLoc Loc) {
11276   if (WasThumb != isThumb()) {
11277     if (WasThumb && hasThumb()) {
11278       // Stay in Thumb mode
11279       SwitchMode();
11280     } else if (!WasThumb && hasARM()) {
11281       // Stay in ARM mode
11282       SwitchMode();
11283     } else {
11284       // Mode switch forced, because the new arch doesn't support the old mode.
11285       getParser().getStreamer().emitAssemblerFlag(isThumb() ? MCAF_Code16
11286                                                             : MCAF_Code32);
11287       // Warn about the implcit mode switch. GAS does not switch modes here,
11288       // but instead stays in the old mode, reporting an error on any following
11289       // instructions as the mode does not exist on the target.
11290       Warning(Loc, Twine("new target does not support ") +
11291                        (WasThumb ? "thumb" : "arm") + " mode, switching to " +
11292                        (!WasThumb ? "thumb" : "arm") + " mode");
11293     }
11294   }
11295 }
11296 
11297 /// parseDirectiveArch
11298 ///  ::= .arch token
parseDirectiveArch(SMLoc L)11299 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
11300   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
11301   ARM::ArchKind ID = ARM::parseArch(Arch);
11302 
11303   if (ID == ARM::ArchKind::INVALID)
11304     return Error(L, "Unknown arch name");
11305 
11306   bool WasThumb = isThumb();
11307   Triple T;
11308   MCSubtargetInfo &STI = copySTI();
11309   STI.setDefaultFeatures("", /*TuneCPU*/ "",
11310                          ("+" + ARM::getArchName(ID)).str());
11311   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
11312   FixModeAfterArchChange(WasThumb, L);
11313 
11314   getTargetStreamer().emitArch(ID);
11315   return false;
11316 }
11317 
11318 /// parseDirectiveEabiAttr
11319 ///  ::= .eabi_attribute int, int [, "str"]
11320 ///  ::= .eabi_attribute Tag_name, int [, "str"]
parseDirectiveEabiAttr(SMLoc L)11321 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
11322   MCAsmParser &Parser = getParser();
11323   int64_t Tag;
11324   SMLoc TagLoc;
11325   TagLoc = Parser.getTok().getLoc();
11326   if (Parser.getTok().is(AsmToken::Identifier)) {
11327     StringRef Name = Parser.getTok().getIdentifier();
11328     Optional<unsigned> Ret =
11329         ELFAttrs::attrTypeFromString(Name, ARMBuildAttrs::ARMAttributeTags);
11330     if (!Ret.hasValue()) {
11331       Error(TagLoc, "attribute name not recognised: " + Name);
11332       return false;
11333     }
11334     Tag = Ret.getValue();
11335     Parser.Lex();
11336   } else {
11337     const MCExpr *AttrExpr;
11338 
11339     TagLoc = Parser.getTok().getLoc();
11340     if (Parser.parseExpression(AttrExpr))
11341       return true;
11342 
11343     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
11344     if (check(!CE, TagLoc, "expected numeric constant"))
11345       return true;
11346 
11347     Tag = CE->getValue();
11348   }
11349 
11350   if (Parser.parseToken(AsmToken::Comma, "comma expected"))
11351     return true;
11352 
11353   StringRef StringValue = "";
11354   bool IsStringValue = false;
11355 
11356   int64_t IntegerValue = 0;
11357   bool IsIntegerValue = false;
11358 
11359   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
11360     IsStringValue = true;
11361   else if (Tag == ARMBuildAttrs::compatibility) {
11362     IsStringValue = true;
11363     IsIntegerValue = true;
11364   } else if (Tag < 32 || Tag % 2 == 0)
11365     IsIntegerValue = true;
11366   else if (Tag % 2 == 1)
11367     IsStringValue = true;
11368   else
11369     llvm_unreachable("invalid tag type");
11370 
11371   if (IsIntegerValue) {
11372     const MCExpr *ValueExpr;
11373     SMLoc ValueExprLoc = Parser.getTok().getLoc();
11374     if (Parser.parseExpression(ValueExpr))
11375       return true;
11376 
11377     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
11378     if (!CE)
11379       return Error(ValueExprLoc, "expected numeric constant");
11380     IntegerValue = CE->getValue();
11381   }
11382 
11383   if (Tag == ARMBuildAttrs::compatibility) {
11384     if (Parser.parseToken(AsmToken::Comma, "comma expected"))
11385       return true;
11386   }
11387 
11388   if (IsStringValue) {
11389     if (Parser.getTok().isNot(AsmToken::String))
11390       return Error(Parser.getTok().getLoc(), "bad string constant");
11391 
11392     StringValue = Parser.getTok().getStringContents();
11393     Parser.Lex();
11394   }
11395 
11396   if (Parser.parseToken(AsmToken::EndOfStatement,
11397                         "unexpected token in '.eabi_attribute' directive"))
11398     return true;
11399 
11400   if (IsIntegerValue && IsStringValue) {
11401     assert(Tag == ARMBuildAttrs::compatibility);
11402     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
11403   } else if (IsIntegerValue)
11404     getTargetStreamer().emitAttribute(Tag, IntegerValue);
11405   else if (IsStringValue)
11406     getTargetStreamer().emitTextAttribute(Tag, StringValue);
11407   return false;
11408 }
11409 
11410 /// parseDirectiveCPU
11411 ///  ::= .cpu str
parseDirectiveCPU(SMLoc L)11412 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
11413   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
11414   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
11415 
11416   // FIXME: This is using table-gen data, but should be moved to
11417   // ARMTargetParser once that is table-gen'd.
11418   if (!getSTI().isCPUStringValid(CPU))
11419     return Error(L, "Unknown CPU name");
11420 
11421   bool WasThumb = isThumb();
11422   MCSubtargetInfo &STI = copySTI();
11423   STI.setDefaultFeatures(CPU, /*TuneCPU*/ CPU, "");
11424   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
11425   FixModeAfterArchChange(WasThumb, L);
11426 
11427   return false;
11428 }
11429 
11430 /// parseDirectiveFPU
11431 ///  ::= .fpu str
parseDirectiveFPU(SMLoc L)11432 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
11433   SMLoc FPUNameLoc = getTok().getLoc();
11434   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
11435 
11436   unsigned ID = ARM::parseFPU(FPU);
11437   std::vector<StringRef> Features;
11438   if (!ARM::getFPUFeatures(ID, Features))
11439     return Error(FPUNameLoc, "Unknown FPU name");
11440 
11441   MCSubtargetInfo &STI = copySTI();
11442   for (auto Feature : Features)
11443     STI.ApplyFeatureFlag(Feature);
11444   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
11445 
11446   getTargetStreamer().emitFPU(ID);
11447   return false;
11448 }
11449 
11450 /// parseDirectiveFnStart
11451 ///  ::= .fnstart
parseDirectiveFnStart(SMLoc L)11452 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
11453   if (parseToken(AsmToken::EndOfStatement,
11454                  "unexpected token in '.fnstart' directive"))
11455     return true;
11456 
11457   if (UC.hasFnStart()) {
11458     Error(L, ".fnstart starts before the end of previous one");
11459     UC.emitFnStartLocNotes();
11460     return true;
11461   }
11462 
11463   // Reset the unwind directives parser state
11464   UC.reset();
11465 
11466   getTargetStreamer().emitFnStart();
11467 
11468   UC.recordFnStart(L);
11469   return false;
11470 }
11471 
11472 /// parseDirectiveFnEnd
11473 ///  ::= .fnend
parseDirectiveFnEnd(SMLoc L)11474 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
11475   if (parseToken(AsmToken::EndOfStatement,
11476                  "unexpected token in '.fnend' directive"))
11477     return true;
11478   // Check the ordering of unwind directives
11479   if (!UC.hasFnStart())
11480     return Error(L, ".fnstart must precede .fnend directive");
11481 
11482   // Reset the unwind directives parser state
11483   getTargetStreamer().emitFnEnd();
11484 
11485   UC.reset();
11486   return false;
11487 }
11488 
11489 /// parseDirectiveCantUnwind
11490 ///  ::= .cantunwind
parseDirectiveCantUnwind(SMLoc L)11491 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
11492   if (parseToken(AsmToken::EndOfStatement,
11493                  "unexpected token in '.cantunwind' directive"))
11494     return true;
11495 
11496   UC.recordCantUnwind(L);
11497   // Check the ordering of unwind directives
11498   if (check(!UC.hasFnStart(), L, ".fnstart must precede .cantunwind directive"))
11499     return true;
11500 
11501   if (UC.hasHandlerData()) {
11502     Error(L, ".cantunwind can't be used with .handlerdata directive");
11503     UC.emitHandlerDataLocNotes();
11504     return true;
11505   }
11506   if (UC.hasPersonality()) {
11507     Error(L, ".cantunwind can't be used with .personality directive");
11508     UC.emitPersonalityLocNotes();
11509     return true;
11510   }
11511 
11512   getTargetStreamer().emitCantUnwind();
11513   return false;
11514 }
11515 
11516 /// parseDirectivePersonality
11517 ///  ::= .personality name
parseDirectivePersonality(SMLoc L)11518 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
11519   MCAsmParser &Parser = getParser();
11520   bool HasExistingPersonality = UC.hasPersonality();
11521 
11522   // Parse the name of the personality routine
11523   if (Parser.getTok().isNot(AsmToken::Identifier))
11524     return Error(L, "unexpected input in .personality directive.");
11525   StringRef Name(Parser.getTok().getIdentifier());
11526   Parser.Lex();
11527 
11528   if (parseToken(AsmToken::EndOfStatement,
11529                  "unexpected token in '.personality' directive"))
11530     return true;
11531 
11532   UC.recordPersonality(L);
11533 
11534   // Check the ordering of unwind directives
11535   if (!UC.hasFnStart())
11536     return Error(L, ".fnstart must precede .personality directive");
11537   if (UC.cantUnwind()) {
11538     Error(L, ".personality can't be used with .cantunwind directive");
11539     UC.emitCantUnwindLocNotes();
11540     return true;
11541   }
11542   if (UC.hasHandlerData()) {
11543     Error(L, ".personality must precede .handlerdata directive");
11544     UC.emitHandlerDataLocNotes();
11545     return true;
11546   }
11547   if (HasExistingPersonality) {
11548     Error(L, "multiple personality directives");
11549     UC.emitPersonalityLocNotes();
11550     return true;
11551   }
11552 
11553   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
11554   getTargetStreamer().emitPersonality(PR);
11555   return false;
11556 }
11557 
11558 /// parseDirectiveHandlerData
11559 ///  ::= .handlerdata
parseDirectiveHandlerData(SMLoc L)11560 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
11561   if (parseToken(AsmToken::EndOfStatement,
11562                  "unexpected token in '.handlerdata' directive"))
11563     return true;
11564 
11565   UC.recordHandlerData(L);
11566   // Check the ordering of unwind directives
11567   if (!UC.hasFnStart())
11568     return Error(L, ".fnstart must precede .personality directive");
11569   if (UC.cantUnwind()) {
11570     Error(L, ".handlerdata can't be used with .cantunwind directive");
11571     UC.emitCantUnwindLocNotes();
11572     return true;
11573   }
11574 
11575   getTargetStreamer().emitHandlerData();
11576   return false;
11577 }
11578 
11579 /// parseDirectiveSetFP
11580 ///  ::= .setfp fpreg, spreg [, offset]
parseDirectiveSetFP(SMLoc L)11581 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
11582   MCAsmParser &Parser = getParser();
11583   // Check the ordering of unwind directives
11584   if (check(!UC.hasFnStart(), L, ".fnstart must precede .setfp directive") ||
11585       check(UC.hasHandlerData(), L,
11586             ".setfp must precede .handlerdata directive"))
11587     return true;
11588 
11589   // Parse fpreg
11590   SMLoc FPRegLoc = Parser.getTok().getLoc();
11591   int FPReg = tryParseRegister();
11592 
11593   if (check(FPReg == -1, FPRegLoc, "frame pointer register expected") ||
11594       Parser.parseToken(AsmToken::Comma, "comma expected"))
11595     return true;
11596 
11597   // Parse spreg
11598   SMLoc SPRegLoc = Parser.getTok().getLoc();
11599   int SPReg = tryParseRegister();
11600   if (check(SPReg == -1, SPRegLoc, "stack pointer register expected") ||
11601       check(SPReg != ARM::SP && SPReg != UC.getFPReg(), SPRegLoc,
11602             "register should be either $sp or the latest fp register"))
11603     return true;
11604 
11605   // Update the frame pointer register
11606   UC.saveFPReg(FPReg);
11607 
11608   // Parse offset
11609   int64_t Offset = 0;
11610   if (Parser.parseOptionalToken(AsmToken::Comma)) {
11611     if (Parser.getTok().isNot(AsmToken::Hash) &&
11612         Parser.getTok().isNot(AsmToken::Dollar))
11613       return Error(Parser.getTok().getLoc(), "'#' expected");
11614     Parser.Lex(); // skip hash token.
11615 
11616     const MCExpr *OffsetExpr;
11617     SMLoc ExLoc = Parser.getTok().getLoc();
11618     SMLoc EndLoc;
11619     if (getParser().parseExpression(OffsetExpr, EndLoc))
11620       return Error(ExLoc, "malformed setfp offset");
11621     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11622     if (check(!CE, ExLoc, "setfp offset must be an immediate"))
11623       return true;
11624     Offset = CE->getValue();
11625   }
11626 
11627   if (Parser.parseToken(AsmToken::EndOfStatement))
11628     return true;
11629 
11630   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
11631                                 static_cast<unsigned>(SPReg), Offset);
11632   return false;
11633 }
11634 
11635 /// parseDirective
11636 ///  ::= .pad offset
parseDirectivePad(SMLoc L)11637 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
11638   MCAsmParser &Parser = getParser();
11639   // Check the ordering of unwind directives
11640   if (!UC.hasFnStart())
11641     return Error(L, ".fnstart must precede .pad directive");
11642   if (UC.hasHandlerData())
11643     return Error(L, ".pad must precede .handlerdata directive");
11644 
11645   // Parse the offset
11646   if (Parser.getTok().isNot(AsmToken::Hash) &&
11647       Parser.getTok().isNot(AsmToken::Dollar))
11648     return Error(Parser.getTok().getLoc(), "'#' expected");
11649   Parser.Lex(); // skip hash token.
11650 
11651   const MCExpr *OffsetExpr;
11652   SMLoc ExLoc = Parser.getTok().getLoc();
11653   SMLoc EndLoc;
11654   if (getParser().parseExpression(OffsetExpr, EndLoc))
11655     return Error(ExLoc, "malformed pad offset");
11656   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11657   if (!CE)
11658     return Error(ExLoc, "pad offset must be an immediate");
11659 
11660   if (parseToken(AsmToken::EndOfStatement,
11661                  "unexpected token in '.pad' directive"))
11662     return true;
11663 
11664   getTargetStreamer().emitPad(CE->getValue());
11665   return false;
11666 }
11667 
11668 /// parseDirectiveRegSave
11669 ///  ::= .save  { registers }
11670 ///  ::= .vsave { registers }
parseDirectiveRegSave(SMLoc L,bool IsVector)11671 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
11672   // Check the ordering of unwind directives
11673   if (!UC.hasFnStart())
11674     return Error(L, ".fnstart must precede .save or .vsave directives");
11675   if (UC.hasHandlerData())
11676     return Error(L, ".save or .vsave must precede .handlerdata directive");
11677 
11678   // RAII object to make sure parsed operands are deleted.
11679   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
11680 
11681   // Parse the register list
11682   if (parseRegisterList(Operands) ||
11683       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11684     return true;
11685   ARMOperand &Op = (ARMOperand &)*Operands[0];
11686   if (!IsVector && !Op.isRegList())
11687     return Error(L, ".save expects GPR registers");
11688   if (IsVector && !Op.isDPRRegList())
11689     return Error(L, ".vsave expects DPR registers");
11690 
11691   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
11692   return false;
11693 }
11694 
11695 /// parseDirectiveInst
11696 ///  ::= .inst opcode [, ...]
11697 ///  ::= .inst.n opcode [, ...]
11698 ///  ::= .inst.w opcode [, ...]
parseDirectiveInst(SMLoc Loc,char Suffix)11699 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
11700   int Width = 4;
11701 
11702   if (isThumb()) {
11703     switch (Suffix) {
11704     case 'n':
11705       Width = 2;
11706       break;
11707     case 'w':
11708       break;
11709     default:
11710       Width = 0;
11711       break;
11712     }
11713   } else {
11714     if (Suffix)
11715       return Error(Loc, "width suffixes are invalid in ARM mode");
11716   }
11717 
11718   auto parseOne = [&]() -> bool {
11719     const MCExpr *Expr;
11720     if (getParser().parseExpression(Expr))
11721       return true;
11722     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
11723     if (!Value) {
11724       return Error(Loc, "expected constant expression");
11725     }
11726 
11727     char CurSuffix = Suffix;
11728     switch (Width) {
11729     case 2:
11730       if (Value->getValue() > 0xffff)
11731         return Error(Loc, "inst.n operand is too big, use inst.w instead");
11732       break;
11733     case 4:
11734       if (Value->getValue() > 0xffffffff)
11735         return Error(Loc, StringRef(Suffix ? "inst.w" : "inst") +
11736                               " operand is too big");
11737       break;
11738     case 0:
11739       // Thumb mode, no width indicated. Guess from the opcode, if possible.
11740       if (Value->getValue() < 0xe800)
11741         CurSuffix = 'n';
11742       else if (Value->getValue() >= 0xe8000000)
11743         CurSuffix = 'w';
11744       else
11745         return Error(Loc, "cannot determine Thumb instruction size, "
11746                           "use inst.n/inst.w instead");
11747       break;
11748     default:
11749       llvm_unreachable("only supported widths are 2 and 4");
11750     }
11751 
11752     getTargetStreamer().emitInst(Value->getValue(), CurSuffix);
11753     return false;
11754   };
11755 
11756   if (parseOptionalToken(AsmToken::EndOfStatement))
11757     return Error(Loc, "expected expression following directive");
11758   if (parseMany(parseOne))
11759     return true;
11760   return false;
11761 }
11762 
11763 /// parseDirectiveLtorg
11764 ///  ::= .ltorg | .pool
parseDirectiveLtorg(SMLoc L)11765 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
11766   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11767     return true;
11768   getTargetStreamer().emitCurrentConstantPool();
11769   return false;
11770 }
11771 
parseDirectiveEven(SMLoc L)11772 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
11773   const MCSection *Section = getStreamer().getCurrentSectionOnly();
11774 
11775   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11776     return true;
11777 
11778   if (!Section) {
11779     getStreamer().InitSections(false);
11780     Section = getStreamer().getCurrentSectionOnly();
11781   }
11782 
11783   assert(Section && "must have section to emit alignment");
11784   if (Section->UseCodeAlign())
11785     getStreamer().emitCodeAlignment(2);
11786   else
11787     getStreamer().emitValueToAlignment(2);
11788 
11789   return false;
11790 }
11791 
11792 /// parseDirectivePersonalityIndex
11793 ///   ::= .personalityindex index
parseDirectivePersonalityIndex(SMLoc L)11794 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
11795   MCAsmParser &Parser = getParser();
11796   bool HasExistingPersonality = UC.hasPersonality();
11797 
11798   const MCExpr *IndexExpression;
11799   SMLoc IndexLoc = Parser.getTok().getLoc();
11800   if (Parser.parseExpression(IndexExpression) ||
11801       parseToken(AsmToken::EndOfStatement,
11802                  "unexpected token in '.personalityindex' directive")) {
11803     return true;
11804   }
11805 
11806   UC.recordPersonalityIndex(L);
11807 
11808   if (!UC.hasFnStart()) {
11809     return Error(L, ".fnstart must precede .personalityindex directive");
11810   }
11811   if (UC.cantUnwind()) {
11812     Error(L, ".personalityindex cannot be used with .cantunwind");
11813     UC.emitCantUnwindLocNotes();
11814     return true;
11815   }
11816   if (UC.hasHandlerData()) {
11817     Error(L, ".personalityindex must precede .handlerdata directive");
11818     UC.emitHandlerDataLocNotes();
11819     return true;
11820   }
11821   if (HasExistingPersonality) {
11822     Error(L, "multiple personality directives");
11823     UC.emitPersonalityLocNotes();
11824     return true;
11825   }
11826 
11827   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
11828   if (!CE)
11829     return Error(IndexLoc, "index must be a constant number");
11830   if (CE->getValue() < 0 || CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX)
11831     return Error(IndexLoc,
11832                  "personality routine index should be in range [0-3]");
11833 
11834   getTargetStreamer().emitPersonalityIndex(CE->getValue());
11835   return false;
11836 }
11837 
11838 /// parseDirectiveUnwindRaw
11839 ///   ::= .unwind_raw offset, opcode [, opcode...]
parseDirectiveUnwindRaw(SMLoc L)11840 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
11841   MCAsmParser &Parser = getParser();
11842   int64_t StackOffset;
11843   const MCExpr *OffsetExpr;
11844   SMLoc OffsetLoc = getLexer().getLoc();
11845 
11846   if (!UC.hasFnStart())
11847     return Error(L, ".fnstart must precede .unwind_raw directives");
11848   if (getParser().parseExpression(OffsetExpr))
11849     return Error(OffsetLoc, "expected expression");
11850 
11851   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11852   if (!CE)
11853     return Error(OffsetLoc, "offset must be a constant");
11854 
11855   StackOffset = CE->getValue();
11856 
11857   if (Parser.parseToken(AsmToken::Comma, "expected comma"))
11858     return true;
11859 
11860   SmallVector<uint8_t, 16> Opcodes;
11861 
11862   auto parseOne = [&]() -> bool {
11863     const MCExpr *OE = nullptr;
11864     SMLoc OpcodeLoc = getLexer().getLoc();
11865     if (check(getLexer().is(AsmToken::EndOfStatement) ||
11866                   Parser.parseExpression(OE),
11867               OpcodeLoc, "expected opcode expression"))
11868       return true;
11869     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
11870     if (!OC)
11871       return Error(OpcodeLoc, "opcode value must be a constant");
11872     const int64_t Opcode = OC->getValue();
11873     if (Opcode & ~0xff)
11874       return Error(OpcodeLoc, "invalid opcode");
11875     Opcodes.push_back(uint8_t(Opcode));
11876     return false;
11877   };
11878 
11879   // Must have at least 1 element
11880   SMLoc OpcodeLoc = getLexer().getLoc();
11881   if (parseOptionalToken(AsmToken::EndOfStatement))
11882     return Error(OpcodeLoc, "expected opcode expression");
11883   if (parseMany(parseOne))
11884     return true;
11885 
11886   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
11887   return false;
11888 }
11889 
11890 /// parseDirectiveTLSDescSeq
11891 ///   ::= .tlsdescseq tls-variable
parseDirectiveTLSDescSeq(SMLoc L)11892 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
11893   MCAsmParser &Parser = getParser();
11894 
11895   if (getLexer().isNot(AsmToken::Identifier))
11896     return TokError("expected variable after '.tlsdescseq' directive");
11897 
11898   const MCSymbolRefExpr *SRE =
11899     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
11900                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
11901   Lex();
11902 
11903   if (parseToken(AsmToken::EndOfStatement,
11904                  "unexpected token in '.tlsdescseq' directive"))
11905     return true;
11906 
11907   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
11908   return false;
11909 }
11910 
11911 /// parseDirectiveMovSP
11912 ///  ::= .movsp reg [, #offset]
parseDirectiveMovSP(SMLoc L)11913 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
11914   MCAsmParser &Parser = getParser();
11915   if (!UC.hasFnStart())
11916     return Error(L, ".fnstart must precede .movsp directives");
11917   if (UC.getFPReg() != ARM::SP)
11918     return Error(L, "unexpected .movsp directive");
11919 
11920   SMLoc SPRegLoc = Parser.getTok().getLoc();
11921   int SPReg = tryParseRegister();
11922   if (SPReg == -1)
11923     return Error(SPRegLoc, "register expected");
11924   if (SPReg == ARM::SP || SPReg == ARM::PC)
11925     return Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
11926 
11927   int64_t Offset = 0;
11928   if (Parser.parseOptionalToken(AsmToken::Comma)) {
11929     if (Parser.parseToken(AsmToken::Hash, "expected #constant"))
11930       return true;
11931 
11932     const MCExpr *OffsetExpr;
11933     SMLoc OffsetLoc = Parser.getTok().getLoc();
11934 
11935     if (Parser.parseExpression(OffsetExpr))
11936       return Error(OffsetLoc, "malformed offset expression");
11937 
11938     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11939     if (!CE)
11940       return Error(OffsetLoc, "offset must be an immediate constant");
11941 
11942     Offset = CE->getValue();
11943   }
11944 
11945   if (parseToken(AsmToken::EndOfStatement,
11946                  "unexpected token in '.movsp' directive"))
11947     return true;
11948 
11949   getTargetStreamer().emitMovSP(SPReg, Offset);
11950   UC.saveFPReg(SPReg);
11951 
11952   return false;
11953 }
11954 
11955 /// parseDirectiveObjectArch
11956 ///   ::= .object_arch name
parseDirectiveObjectArch(SMLoc L)11957 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
11958   MCAsmParser &Parser = getParser();
11959   if (getLexer().isNot(AsmToken::Identifier))
11960     return Error(getLexer().getLoc(), "unexpected token");
11961 
11962   StringRef Arch = Parser.getTok().getString();
11963   SMLoc ArchLoc = Parser.getTok().getLoc();
11964   Lex();
11965 
11966   ARM::ArchKind ID = ARM::parseArch(Arch);
11967 
11968   if (ID == ARM::ArchKind::INVALID)
11969     return Error(ArchLoc, "unknown architecture '" + Arch + "'");
11970   if (parseToken(AsmToken::EndOfStatement))
11971     return true;
11972 
11973   getTargetStreamer().emitObjectArch(ID);
11974   return false;
11975 }
11976 
11977 /// parseDirectiveAlign
11978 ///   ::= .align
parseDirectiveAlign(SMLoc L)11979 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
11980   // NOTE: if this is not the end of the statement, fall back to the target
11981   // agnostic handling for this directive which will correctly handle this.
11982   if (parseOptionalToken(AsmToken::EndOfStatement)) {
11983     // '.align' is target specifically handled to mean 2**2 byte alignment.
11984     const MCSection *Section = getStreamer().getCurrentSectionOnly();
11985     assert(Section && "must have section to emit alignment");
11986     if (Section->UseCodeAlign())
11987       getStreamer().emitCodeAlignment(4, 0);
11988     else
11989       getStreamer().emitValueToAlignment(4, 0, 1, 0);
11990     return false;
11991   }
11992   return true;
11993 }
11994 
11995 /// parseDirectiveThumbSet
11996 ///  ::= .thumb_set name, value
parseDirectiveThumbSet(SMLoc L)11997 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
11998   MCAsmParser &Parser = getParser();
11999 
12000   StringRef Name;
12001   if (check(Parser.parseIdentifier(Name),
12002             "expected identifier after '.thumb_set'") ||
12003       parseToken(AsmToken::Comma, "expected comma after name '" + Name + "'"))
12004     return true;
12005 
12006   MCSymbol *Sym;
12007   const MCExpr *Value;
12008   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
12009                                                Parser, Sym, Value))
12010     return true;
12011 
12012   getTargetStreamer().emitThumbSet(Sym, Value);
12013   return false;
12014 }
12015 
12016 /// Force static initialization.
LLVMInitializeARMAsmParser()12017 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeARMAsmParser() {
12018   RegisterMCAsmParser<ARMAsmParser> X(getTheARMLETarget());
12019   RegisterMCAsmParser<ARMAsmParser> Y(getTheARMBETarget());
12020   RegisterMCAsmParser<ARMAsmParser> A(getTheThumbLETarget());
12021   RegisterMCAsmParser<ARMAsmParser> B(getTheThumbBETarget());
12022 }
12023 
12024 #define GET_REGISTER_MATCHER
12025 #define GET_SUBTARGET_FEATURE_NAME
12026 #define GET_MATCHER_IMPLEMENTATION
12027 #define GET_MNEMONIC_SPELL_CHECKER
12028 #include "ARMGenAsmMatcher.inc"
12029 
12030 // Some diagnostics need to vary with subtarget features, so they are handled
12031 // here. For example, the DPR class has either 16 or 32 registers, depending
12032 // on the FPU available.
12033 const char *
getCustomOperandDiag(ARMMatchResultTy MatchError)12034 ARMAsmParser::getCustomOperandDiag(ARMMatchResultTy MatchError) {
12035   switch (MatchError) {
12036   // rGPR contains sp starting with ARMv8.
12037   case Match_rGPR:
12038     return hasV8Ops() ? "operand must be a register in range [r0, r14]"
12039                       : "operand must be a register in range [r0, r12] or r14";
12040   // DPR contains 16 registers for some FPUs, and 32 for others.
12041   case Match_DPR:
12042     return hasD32() ? "operand must be a register in range [d0, d31]"
12043                     : "operand must be a register in range [d0, d15]";
12044   case Match_DPR_RegList:
12045     return hasD32() ? "operand must be a list of registers in range [d0, d31]"
12046                     : "operand must be a list of registers in range [d0, d15]";
12047 
12048   // For all other diags, use the static string from tablegen.
12049   default:
12050     return getMatchKindDiag(MatchError);
12051   }
12052 }
12053 
12054 // Process the list of near-misses, throwing away ones we don't want to report
12055 // to the user, and converting the rest to a source location and string that
12056 // should be reported.
12057 void
FilterNearMisses(SmallVectorImpl<NearMissInfo> & NearMissesIn,SmallVectorImpl<NearMissMessage> & NearMissesOut,SMLoc IDLoc,OperandVector & Operands)12058 ARMAsmParser::FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
12059                                SmallVectorImpl<NearMissMessage> &NearMissesOut,
12060                                SMLoc IDLoc, OperandVector &Operands) {
12061   // TODO: If operand didn't match, sub in a dummy one and run target
12062   // predicate, so that we can avoid reporting near-misses that are invalid?
12063   // TODO: Many operand types dont have SuperClasses set, so we report
12064   // redundant ones.
12065   // TODO: Some operands are superclasses of registers (e.g.
12066   // MCK_RegShiftedImm), we don't have any way to represent that currently.
12067   // TODO: This is not all ARM-specific, can some of it be factored out?
12068 
12069   // Record some information about near-misses that we have already seen, so
12070   // that we can avoid reporting redundant ones. For example, if there are
12071   // variants of an instruction that take 8- and 16-bit immediates, we want
12072   // to only report the widest one.
12073   std::multimap<unsigned, unsigned> OperandMissesSeen;
12074   SmallSet<FeatureBitset, 4> FeatureMissesSeen;
12075   bool ReportedTooFewOperands = false;
12076 
12077   // Process the near-misses in reverse order, so that we see more general ones
12078   // first, and so can avoid emitting more specific ones.
12079   for (NearMissInfo &I : reverse(NearMissesIn)) {
12080     switch (I.getKind()) {
12081     case NearMissInfo::NearMissOperand: {
12082       SMLoc OperandLoc =
12083           ((ARMOperand &)*Operands[I.getOperandIndex()]).getStartLoc();
12084       const char *OperandDiag =
12085           getCustomOperandDiag((ARMMatchResultTy)I.getOperandError());
12086 
12087       // If we have already emitted a message for a superclass, don't also report
12088       // the sub-class. We consider all operand classes that we don't have a
12089       // specialised diagnostic for to be equal for the propose of this check,
12090       // so that we don't report the generic error multiple times on the same
12091       // operand.
12092       unsigned DupCheckMatchClass = OperandDiag ? I.getOperandClass() : ~0U;
12093       auto PrevReports = OperandMissesSeen.equal_range(I.getOperandIndex());
12094       if (std::any_of(PrevReports.first, PrevReports.second,
12095                       [DupCheckMatchClass](
12096                           const std::pair<unsigned, unsigned> Pair) {
12097             if (DupCheckMatchClass == ~0U || Pair.second == ~0U)
12098               return Pair.second == DupCheckMatchClass;
12099             else
12100               return isSubclass((MatchClassKind)DupCheckMatchClass,
12101                                 (MatchClassKind)Pair.second);
12102           }))
12103         break;
12104       OperandMissesSeen.insert(
12105           std::make_pair(I.getOperandIndex(), DupCheckMatchClass));
12106 
12107       NearMissMessage Message;
12108       Message.Loc = OperandLoc;
12109       if (OperandDiag) {
12110         Message.Message = OperandDiag;
12111       } else if (I.getOperandClass() == InvalidMatchClass) {
12112         Message.Message = "too many operands for instruction";
12113       } else {
12114         Message.Message = "invalid operand for instruction";
12115         LLVM_DEBUG(
12116             dbgs() << "Missing diagnostic string for operand class "
12117                    << getMatchClassName((MatchClassKind)I.getOperandClass())
12118                    << I.getOperandClass() << ", error " << I.getOperandError()
12119                    << ", opcode " << MII.getName(I.getOpcode()) << "\n");
12120       }
12121       NearMissesOut.emplace_back(Message);
12122       break;
12123     }
12124     case NearMissInfo::NearMissFeature: {
12125       const FeatureBitset &MissingFeatures = I.getFeatures();
12126       // Don't report the same set of features twice.
12127       if (FeatureMissesSeen.count(MissingFeatures))
12128         break;
12129       FeatureMissesSeen.insert(MissingFeatures);
12130 
12131       // Special case: don't report a feature set which includes arm-mode for
12132       // targets that don't have ARM mode.
12133       if (MissingFeatures.test(Feature_IsARMBit) && !hasARM())
12134         break;
12135       // Don't report any near-misses that both require switching instruction
12136       // set, and adding other subtarget features.
12137       if (isThumb() && MissingFeatures.test(Feature_IsARMBit) &&
12138           MissingFeatures.count() > 1)
12139         break;
12140       if (!isThumb() && MissingFeatures.test(Feature_IsThumbBit) &&
12141           MissingFeatures.count() > 1)
12142         break;
12143       if (!isThumb() && MissingFeatures.test(Feature_IsThumb2Bit) &&
12144           (MissingFeatures & ~FeatureBitset({Feature_IsThumb2Bit,
12145                                              Feature_IsThumbBit})).any())
12146         break;
12147       if (isMClass() && MissingFeatures.test(Feature_HasNEONBit))
12148         break;
12149 
12150       NearMissMessage Message;
12151       Message.Loc = IDLoc;
12152       raw_svector_ostream OS(Message.Message);
12153 
12154       OS << "instruction requires:";
12155       for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i)
12156         if (MissingFeatures.test(i))
12157           OS << ' ' << getSubtargetFeatureName(i);
12158 
12159       NearMissesOut.emplace_back(Message);
12160 
12161       break;
12162     }
12163     case NearMissInfo::NearMissPredicate: {
12164       NearMissMessage Message;
12165       Message.Loc = IDLoc;
12166       switch (I.getPredicateError()) {
12167       case Match_RequiresNotITBlock:
12168         Message.Message = "flag setting instruction only valid outside IT block";
12169         break;
12170       case Match_RequiresITBlock:
12171         Message.Message = "instruction only valid inside IT block";
12172         break;
12173       case Match_RequiresV6:
12174         Message.Message = "instruction variant requires ARMv6 or later";
12175         break;
12176       case Match_RequiresThumb2:
12177         Message.Message = "instruction variant requires Thumb2";
12178         break;
12179       case Match_RequiresV8:
12180         Message.Message = "instruction variant requires ARMv8 or later";
12181         break;
12182       case Match_RequiresFlagSetting:
12183         Message.Message = "no flag-preserving variant of this instruction available";
12184         break;
12185       case Match_InvalidOperand:
12186         Message.Message = "invalid operand for instruction";
12187         break;
12188       default:
12189         llvm_unreachable("Unhandled target predicate error");
12190         break;
12191       }
12192       NearMissesOut.emplace_back(Message);
12193       break;
12194     }
12195     case NearMissInfo::NearMissTooFewOperands: {
12196       if (!ReportedTooFewOperands) {
12197         SMLoc EndLoc = ((ARMOperand &)*Operands.back()).getEndLoc();
12198         NearMissesOut.emplace_back(NearMissMessage{
12199             EndLoc, StringRef("too few operands for instruction")});
12200         ReportedTooFewOperands = true;
12201       }
12202       break;
12203     }
12204     case NearMissInfo::NoNearMiss:
12205       // This should never leave the matcher.
12206       llvm_unreachable("not a near-miss");
12207       break;
12208     }
12209   }
12210 }
12211 
ReportNearMisses(SmallVectorImpl<NearMissInfo> & NearMisses,SMLoc IDLoc,OperandVector & Operands)12212 void ARMAsmParser::ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses,
12213                                     SMLoc IDLoc, OperandVector &Operands) {
12214   SmallVector<NearMissMessage, 4> Messages;
12215   FilterNearMisses(NearMisses, Messages, IDLoc, Operands);
12216 
12217   if (Messages.size() == 0) {
12218     // No near-misses were found, so the best we can do is "invalid
12219     // instruction".
12220     Error(IDLoc, "invalid instruction");
12221   } else if (Messages.size() == 1) {
12222     // One near miss was found, report it as the sole error.
12223     Error(Messages[0].Loc, Messages[0].Message);
12224   } else {
12225     // More than one near miss, so report a generic "invalid instruction"
12226     // error, followed by notes for each of the near-misses.
12227     Error(IDLoc, "invalid instruction, any one of the following would fix this:");
12228     for (auto &M : Messages) {
12229       Note(M.Loc, M.Message);
12230     }
12231   }
12232 }
12233 
enableArchExtFeature(StringRef Name,SMLoc & ExtLoc)12234 bool ARMAsmParser::enableArchExtFeature(StringRef Name, SMLoc &ExtLoc) {
12235   // FIXME: This structure should be moved inside ARMTargetParser
12236   // when we start to table-generate them, and we can use the ARM
12237   // flags below, that were generated by table-gen.
12238   static const struct {
12239     const uint64_t Kind;
12240     const FeatureBitset ArchCheck;
12241     const FeatureBitset Features;
12242   } Extensions[] = {
12243       {ARM::AEK_CRC, {Feature_HasV8Bit}, {ARM::FeatureCRC}},
12244       {ARM::AEK_AES,
12245        {Feature_HasV8Bit},
12246        {ARM::FeatureAES, ARM::FeatureNEON, ARM::FeatureFPARMv8}},
12247       {ARM::AEK_SHA2,
12248        {Feature_HasV8Bit},
12249        {ARM::FeatureSHA2, ARM::FeatureNEON, ARM::FeatureFPARMv8}},
12250       {ARM::AEK_CRYPTO,
12251        {Feature_HasV8Bit},
12252        {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8}},
12253       {ARM::AEK_FP,
12254        {Feature_HasV8Bit},
12255        {ARM::FeatureVFP2_SP, ARM::FeatureFPARMv8}},
12256       {(ARM::AEK_HWDIVTHUMB | ARM::AEK_HWDIVARM),
12257        {Feature_HasV7Bit, Feature_IsNotMClassBit},
12258        {ARM::FeatureHWDivThumb, ARM::FeatureHWDivARM}},
12259       {ARM::AEK_MP,
12260        {Feature_HasV7Bit, Feature_IsNotMClassBit},
12261        {ARM::FeatureMP}},
12262       {ARM::AEK_SIMD,
12263        {Feature_HasV8Bit},
12264        {ARM::FeatureNEON, ARM::FeatureVFP2_SP, ARM::FeatureFPARMv8}},
12265       {ARM::AEK_SEC, {Feature_HasV6KBit}, {ARM::FeatureTrustZone}},
12266       // FIXME: Only available in A-class, isel not predicated
12267       {ARM::AEK_VIRT, {Feature_HasV7Bit}, {ARM::FeatureVirtualization}},
12268       {ARM::AEK_FP16,
12269        {Feature_HasV8_2aBit},
12270        {ARM::FeatureFPARMv8, ARM::FeatureFullFP16}},
12271       {ARM::AEK_RAS, {Feature_HasV8Bit}, {ARM::FeatureRAS}},
12272       {ARM::AEK_LOB, {Feature_HasV8_1MMainlineBit}, {ARM::FeatureLOB}},
12273       // FIXME: Unsupported extensions.
12274       {ARM::AEK_OS, {}, {}},
12275       {ARM::AEK_IWMMXT, {}, {}},
12276       {ARM::AEK_IWMMXT2, {}, {}},
12277       {ARM::AEK_MAVERICK, {}, {}},
12278       {ARM::AEK_XSCALE, {}, {}},
12279   };
12280   bool EnableFeature = true;
12281   if (Name.startswith_lower("no")) {
12282     EnableFeature = false;
12283     Name = Name.substr(2);
12284   }
12285   uint64_t FeatureKind = ARM::parseArchExt(Name);
12286   if (FeatureKind == ARM::AEK_INVALID)
12287     return Error(ExtLoc, "unknown architectural extension: " + Name);
12288 
12289   for (const auto &Extension : Extensions) {
12290     if (Extension.Kind != FeatureKind)
12291       continue;
12292 
12293     if (Extension.Features.none())
12294       return Error(ExtLoc, "unsupported architectural extension: " + Name);
12295 
12296     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck)
12297       return Error(ExtLoc, "architectural extension '" + Name +
12298                                "' is not "
12299                                "allowed for the current base architecture");
12300 
12301     MCSubtargetInfo &STI = copySTI();
12302     if (EnableFeature) {
12303       STI.SetFeatureBitsTransitively(Extension.Features);
12304     } else {
12305       STI.ClearFeatureBitsTransitively(Extension.Features);
12306     }
12307     FeatureBitset Features = ComputeAvailableFeatures(STI.getFeatureBits());
12308     setAvailableFeatures(Features);
12309     return true;
12310   }
12311   return false;
12312 }
12313 
12314 /// parseDirectiveArchExtension
12315 ///   ::= .arch_extension [no]feature
parseDirectiveArchExtension(SMLoc L)12316 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
12317 
12318   MCAsmParser &Parser = getParser();
12319 
12320   if (getLexer().isNot(AsmToken::Identifier))
12321     return Error(getLexer().getLoc(), "expected architecture extension name");
12322 
12323   StringRef Name = Parser.getTok().getString();
12324   SMLoc ExtLoc = Parser.getTok().getLoc();
12325   Lex();
12326 
12327   if (parseToken(AsmToken::EndOfStatement,
12328                  "unexpected token in '.arch_extension' directive"))
12329     return true;
12330 
12331   if (Name == "nocrypto") {
12332     enableArchExtFeature("nosha2", ExtLoc);
12333     enableArchExtFeature("noaes", ExtLoc);
12334   }
12335 
12336   if (enableArchExtFeature(Name, ExtLoc))
12337     return false;
12338 
12339   return Error(ExtLoc, "unknown architectural extension: " + Name);
12340 }
12341 
12342 // Define this matcher function after the auto-generated include so we
12343 // have the match class enum definitions.
validateTargetOperandClass(MCParsedAsmOperand & AsmOp,unsigned Kind)12344 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
12345                                                   unsigned Kind) {
12346   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
12347   // If the kind is a token for a literal immediate, check if our asm
12348   // operand matches. This is for InstAliases which have a fixed-value
12349   // immediate in the syntax.
12350   switch (Kind) {
12351   default: break;
12352   case MCK__HASH_0:
12353     if (Op.isImm())
12354       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
12355         if (CE->getValue() == 0)
12356           return Match_Success;
12357     break;
12358   case MCK__HASH_8:
12359     if (Op.isImm())
12360       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
12361         if (CE->getValue() == 8)
12362           return Match_Success;
12363     break;
12364   case MCK__HASH_16:
12365     if (Op.isImm())
12366       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
12367         if (CE->getValue() == 16)
12368           return Match_Success;
12369     break;
12370   case MCK_ModImm:
12371     if (Op.isImm()) {
12372       const MCExpr *SOExpr = Op.getImm();
12373       int64_t Value;
12374       if (!SOExpr->evaluateAsAbsolute(Value))
12375         return Match_Success;
12376       assert((Value >= std::numeric_limits<int32_t>::min() &&
12377               Value <= std::numeric_limits<uint32_t>::max()) &&
12378              "expression value must be representable in 32 bits");
12379     }
12380     break;
12381   case MCK_rGPR:
12382     if (hasV8Ops() && Op.isReg() && Op.getReg() == ARM::SP)
12383       return Match_Success;
12384     return Match_rGPR;
12385   case MCK_GPRPair:
12386     if (Op.isReg() &&
12387         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
12388       return Match_Success;
12389     break;
12390   }
12391   return Match_InvalidOperand;
12392 }
12393 
isMnemonicVPTPredicable(StringRef Mnemonic,StringRef ExtraToken)12394 bool ARMAsmParser::isMnemonicVPTPredicable(StringRef Mnemonic,
12395                                            StringRef ExtraToken) {
12396   if (!hasMVE())
12397     return false;
12398 
12399   return Mnemonic.startswith("vabav") || Mnemonic.startswith("vaddv") ||
12400          Mnemonic.startswith("vaddlv") || Mnemonic.startswith("vminnmv") ||
12401          Mnemonic.startswith("vminnmav") || Mnemonic.startswith("vminv") ||
12402          Mnemonic.startswith("vminav") || Mnemonic.startswith("vmaxnmv") ||
12403          Mnemonic.startswith("vmaxnmav") || Mnemonic.startswith("vmaxv") ||
12404          Mnemonic.startswith("vmaxav") || Mnemonic.startswith("vmladav") ||
12405          Mnemonic.startswith("vrmlaldavh") || Mnemonic.startswith("vrmlalvh") ||
12406          Mnemonic.startswith("vmlsdav") || Mnemonic.startswith("vmlav") ||
12407          Mnemonic.startswith("vmlaldav") || Mnemonic.startswith("vmlalv") ||
12408          Mnemonic.startswith("vmaxnm") || Mnemonic.startswith("vminnm") ||
12409          Mnemonic.startswith("vmax") || Mnemonic.startswith("vmin") ||
12410          Mnemonic.startswith("vshlc") || Mnemonic.startswith("vmovlt") ||
12411          Mnemonic.startswith("vmovlb") || Mnemonic.startswith("vshll") ||
12412          Mnemonic.startswith("vrshrn") || Mnemonic.startswith("vshrn") ||
12413          Mnemonic.startswith("vqrshrun") || Mnemonic.startswith("vqshrun") ||
12414          Mnemonic.startswith("vqrshrn") || Mnemonic.startswith("vqshrn") ||
12415          Mnemonic.startswith("vbic") || Mnemonic.startswith("vrev64") ||
12416          Mnemonic.startswith("vrev32") || Mnemonic.startswith("vrev16") ||
12417          Mnemonic.startswith("vmvn") || Mnemonic.startswith("veor") ||
12418          Mnemonic.startswith("vorn") || Mnemonic.startswith("vorr") ||
12419          Mnemonic.startswith("vand") || Mnemonic.startswith("vmul") ||
12420          Mnemonic.startswith("vqrdmulh") || Mnemonic.startswith("vqdmulh") ||
12421          Mnemonic.startswith("vsub") || Mnemonic.startswith("vadd") ||
12422          Mnemonic.startswith("vqsub") || Mnemonic.startswith("vqadd") ||
12423          Mnemonic.startswith("vabd") || Mnemonic.startswith("vrhadd") ||
12424          Mnemonic.startswith("vhsub") || Mnemonic.startswith("vhadd") ||
12425          Mnemonic.startswith("vdup") || Mnemonic.startswith("vcls") ||
12426          Mnemonic.startswith("vclz") || Mnemonic.startswith("vneg") ||
12427          Mnemonic.startswith("vabs") || Mnemonic.startswith("vqneg") ||
12428          Mnemonic.startswith("vqabs") ||
12429          (Mnemonic.startswith("vrint") && Mnemonic != "vrintr") ||
12430          Mnemonic.startswith("vcmla") || Mnemonic.startswith("vfma") ||
12431          Mnemonic.startswith("vfms") || Mnemonic.startswith("vcadd") ||
12432          Mnemonic.startswith("vadd") || Mnemonic.startswith("vsub") ||
12433          Mnemonic.startswith("vshl") || Mnemonic.startswith("vqshl") ||
12434          Mnemonic.startswith("vqrshl") || Mnemonic.startswith("vrshl") ||
12435          Mnemonic.startswith("vsri") || Mnemonic.startswith("vsli") ||
12436          Mnemonic.startswith("vrshr") || Mnemonic.startswith("vshr") ||
12437          Mnemonic.startswith("vpsel") || Mnemonic.startswith("vcmp") ||
12438          Mnemonic.startswith("vqdmladh") || Mnemonic.startswith("vqrdmladh") ||
12439          Mnemonic.startswith("vqdmlsdh") || Mnemonic.startswith("vqrdmlsdh") ||
12440          Mnemonic.startswith("vcmul") || Mnemonic.startswith("vrmulh") ||
12441          Mnemonic.startswith("vqmovn") || Mnemonic.startswith("vqmovun") ||
12442          Mnemonic.startswith("vmovnt") || Mnemonic.startswith("vmovnb") ||
12443          Mnemonic.startswith("vmaxa") || Mnemonic.startswith("vmaxnma") ||
12444          Mnemonic.startswith("vhcadd") || Mnemonic.startswith("vadc") ||
12445          Mnemonic.startswith("vsbc") || Mnemonic.startswith("vrshr") ||
12446          Mnemonic.startswith("vshr") || Mnemonic.startswith("vstrb") ||
12447          Mnemonic.startswith("vldrb") ||
12448          (Mnemonic.startswith("vstrh") && Mnemonic != "vstrhi") ||
12449          (Mnemonic.startswith("vldrh") && Mnemonic != "vldrhi") ||
12450          Mnemonic.startswith("vstrw") || Mnemonic.startswith("vldrw") ||
12451          Mnemonic.startswith("vldrd") || Mnemonic.startswith("vstrd") ||
12452          Mnemonic.startswith("vqdmull") || Mnemonic.startswith("vbrsr") ||
12453          Mnemonic.startswith("vfmas") || Mnemonic.startswith("vmlas") ||
12454          Mnemonic.startswith("vmla") || Mnemonic.startswith("vqdmlash") ||
12455          Mnemonic.startswith("vqdmlah") || Mnemonic.startswith("vqrdmlash") ||
12456          Mnemonic.startswith("vqrdmlah") || Mnemonic.startswith("viwdup") ||
12457          Mnemonic.startswith("vdwdup") || Mnemonic.startswith("vidup") ||
12458          Mnemonic.startswith("vddup") || Mnemonic.startswith("vctp") ||
12459          Mnemonic.startswith("vpnot") || Mnemonic.startswith("vbic") ||
12460          Mnemonic.startswith("vrmlsldavh") || Mnemonic.startswith("vmlsldav") ||
12461          Mnemonic.startswith("vcvt") ||
12462          MS.isVPTPredicableCDEInstr(Mnemonic) ||
12463          (Mnemonic.startswith("vmov") &&
12464           !(ExtraToken == ".f16" || ExtraToken == ".32" ||
12465             ExtraToken == ".16" || ExtraToken == ".8"));
12466 }
12467