1 //===-- HexagonAsmParser.cpp - Parse Hexagon asm to MCInst instructions----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #define DEBUG_TYPE "mcasmparser"
11 
12 #include "Hexagon.h"
13 #include "HexagonRegisterInfo.h"
14 #include "HexagonTargetStreamer.h"
15 #include "MCTargetDesc/HexagonBaseInfo.h"
16 #include "MCTargetDesc/HexagonMCAsmInfo.h"
17 #include "MCTargetDesc/HexagonMCChecker.h"
18 #include "MCTargetDesc/HexagonMCELFStreamer.h"
19 #include "MCTargetDesc/HexagonMCExpr.h"
20 #include "MCTargetDesc/HexagonMCShuffler.h"
21 #include "MCTargetDesc/HexagonMCTargetDesc.h"
22 #include "MCTargetDesc/HexagonShuffler.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCELFStreamer.h"
29 #include "llvm/MC/MCExpr.h"
30 #include "llvm/MC/MCInst.h"
31 #include "llvm/MC/MCParser/MCAsmLexer.h"
32 #include "llvm/MC/MCParser/MCAsmParser.h"
33 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
34 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
35 #include "llvm/MC/MCSectionELF.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSubtargetInfo.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ELF.h"
41 #include "llvm/Support/Format.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/SourceMgr.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include <sstream>
47 
48 using namespace llvm;
49 
50 static cl::opt<bool> EnableFutureRegs("mfuture-regs",
51                                       cl::desc("Enable future registers"));
52 
53 static cl::opt<bool> WarnMissingParenthesis("mwarn-missing-parenthesis",
54 cl::desc("Warn for missing parenthesis around predicate registers"),
55 cl::init(true));
56 static cl::opt<bool> ErrorMissingParenthesis("merror-missing-parenthesis",
57 cl::desc("Error for missing parenthesis around predicate registers"),
58 cl::init(false));
59 static cl::opt<bool> WarnSignedMismatch("mwarn-sign-mismatch",
60 cl::desc("Warn for mismatching a signed and unsigned value"),
61 cl::init(true));
62 static cl::opt<bool> WarnNoncontigiousRegister("mwarn-noncontigious-register",
63 cl::desc("Warn for register names that arent contigious"),
64 cl::init(true));
65 static cl::opt<bool> ErrorNoncontigiousRegister("merror-noncontigious-register",
66 cl::desc("Error for register names that aren't contigious"),
67 cl::init(false));
68 
69 
70 namespace {
71 struct HexagonOperand;
72 
73 class HexagonAsmParser : public MCTargetAsmParser {
74 
75   HexagonTargetStreamer &getTargetStreamer() {
76     MCTargetStreamer &TS = *Parser.getStreamer().getTargetStreamer();
77     return static_cast<HexagonTargetStreamer &>(TS);
78   }
79 
80   MCAsmParser &Parser;
81   MCAssembler *Assembler;
82   MCInstrInfo const &MCII;
83   MCInst MCB;
84   bool InBrackets;
85 
86   MCAsmParser &getParser() const { return Parser; }
87   MCAssembler *getAssembler() const { return Assembler; }
88   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
89 
90   bool equalIsAsmAssignment() override { return false; }
91   bool isLabel(AsmToken &Token) override;
92 
93   void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
94   bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
95   bool ParseDirectiveFalign(unsigned Size, SMLoc L);
96 
97   virtual bool ParseRegister(unsigned &RegNo,
98                              SMLoc &StartLoc,
99                              SMLoc &EndLoc) override;
100   bool ParseDirectiveSubsection(SMLoc L);
101   bool ParseDirectiveValue(unsigned Size, SMLoc L);
102   bool ParseDirectiveComm(bool IsLocal, SMLoc L);
103   bool RegisterMatchesArch(unsigned MatchNum) const;
104 
105   bool matchBundleOptions();
106   bool handleNoncontigiousRegister(bool Contigious, SMLoc &Loc);
107   bool finishBundle(SMLoc IDLoc, MCStreamer &Out);
108   void canonicalizeImmediates(MCInst &MCI);
109   bool matchOneInstruction(MCInst &MCB, SMLoc IDLoc,
110                            OperandVector &InstOperands, uint64_t &ErrorInfo,
111                            bool MatchingInlineAsm, bool &MustExtend);
112 
113   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
114                                OperandVector &Operands, MCStreamer &Out,
115                                uint64_t &ErrorInfo, bool MatchingInlineAsm) override;
116 
117   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op, unsigned Kind) override;
118   void OutOfRange(SMLoc IDLoc, long long Val, long long Max);
119   int processInstruction(MCInst &Inst, OperandVector const &Operands,
120                          SMLoc IDLoc, bool &MustExtend);
121 
122   // Check if we have an assembler and, if so, set the ELF e_header flags.
123   void chksetELFHeaderEFlags(unsigned flags) {
124     if (getAssembler())
125       getAssembler()->setELFHeaderEFlags(flags);
126   }
127 
128 /// @name Auto-generated Match Functions
129 /// {
130 
131 #define GET_ASSEMBLER_HEADER
132 #include "HexagonGenAsmMatcher.inc"
133 
134   /// }
135 
136 public:
137   HexagonAsmParser(const MCSubtargetInfo &_STI, MCAsmParser &_Parser,
138                    const MCInstrInfo &MII, const MCTargetOptions &Options)
139     : MCTargetAsmParser(Options, _STI), Parser(_Parser),
140       MCII (MII), MCB(HexagonMCInstrInfo::createBundle()), InBrackets(false) {
141     setAvailableFeatures(ComputeAvailableFeatures(getSTI().getFeatureBits()));
142 
143   MCAsmParserExtension::Initialize(_Parser);
144 
145   Assembler = nullptr;
146   // FIXME: need better way to detect AsmStreamer (upstream removed getKind())
147   if (!Parser.getStreamer().hasRawTextSupport()) {
148     MCELFStreamer *MES = static_cast<MCELFStreamer *>(&Parser.getStreamer());
149     Assembler = &MES->getAssembler();
150   }
151   }
152 
153   bool mustExtend(OperandVector &Operands);
154   bool splitIdentifier(OperandVector &Operands);
155   bool parseOperand(OperandVector &Operands);
156   bool parseInstruction(OperandVector &Operands);
157   bool implicitExpressionLocation(OperandVector &Operands);
158   bool parseExpressionOrOperand(OperandVector &Operands);
159   bool parseExpression(MCExpr const *& Expr);
160   virtual bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
161                                 SMLoc NameLoc, OperandVector &Operands) override
162   {
163     llvm_unreachable("Unimplemented");
164   }
165   virtual bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
166                                 AsmToken ID, OperandVector &Operands) override;
167 
168   virtual bool ParseDirective(AsmToken DirectiveID) override;
169 };
170 
171 /// HexagonOperand - Instances of this class represent a parsed Hexagon machine
172 /// instruction.
173 struct HexagonOperand : public MCParsedAsmOperand {
174   enum KindTy { Token, Immediate, Register } Kind;
175 
176   SMLoc StartLoc, EndLoc;
177 
178   struct TokTy {
179     const char *Data;
180     unsigned Length;
181   };
182 
183   struct RegTy {
184     unsigned RegNum;
185   };
186 
187   struct ImmTy {
188     const MCExpr *Val;
189     bool MustExtend;
190   };
191 
192   struct InstTy {
193     OperandVector *SubInsts;
194   };
195 
196   union {
197     struct TokTy Tok;
198     struct RegTy Reg;
199     struct ImmTy Imm;
200   };
201 
202   HexagonOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
203 
204 public:
205   HexagonOperand(const HexagonOperand &o) : MCParsedAsmOperand() {
206     Kind = o.Kind;
207     StartLoc = o.StartLoc;
208     EndLoc = o.EndLoc;
209     switch (Kind) {
210     case Register:
211       Reg = o.Reg;
212       break;
213     case Immediate:
214       Imm = o.Imm;
215       break;
216     case Token:
217       Tok = o.Tok;
218       break;
219     }
220   }
221 
222   /// getStartLoc - Get the location of the first token of this operand.
223   SMLoc getStartLoc() const { return StartLoc; }
224 
225   /// getEndLoc - Get the location of the last token of this operand.
226   SMLoc getEndLoc() const { return EndLoc; }
227 
228   unsigned getReg() const {
229     assert(Kind == Register && "Invalid access!");
230     return Reg.RegNum;
231   }
232 
233   const MCExpr *getImm() const {
234     assert(Kind == Immediate && "Invalid access!");
235     return Imm.Val;
236   }
237 
238   bool isToken() const { return Kind == Token; }
239   bool isImm() const { return Kind == Immediate; }
240   bool isMem() const { llvm_unreachable("No isMem"); }
241   bool isReg() const { return Kind == Register; }
242 
243   bool CheckImmRange(int immBits, int zeroBits, bool isSigned,
244                      bool isRelocatable, bool Extendable) const {
245     if (Kind == Immediate) {
246       const MCExpr *myMCExpr = &HexagonMCInstrInfo::getExpr(*getImm());
247       if (Imm.MustExtend && !Extendable)
248         return false;
249       int64_t Res;
250       if (myMCExpr->evaluateAsAbsolute(Res)) {
251         int bits = immBits + zeroBits;
252         // Field bit range is zerobits + bits
253         // zeroBits must be 0
254         if (Res & ((1 << zeroBits) - 1))
255           return false;
256         if (isSigned) {
257           if (Res < (1LL << (bits - 1)) && Res >= -(1LL << (bits - 1)))
258             return true;
259         } else {
260           if (bits == 64)
261             return true;
262           if (Res >= 0)
263             return ((uint64_t)Res < (uint64_t)(1ULL << bits)) ? true : false;
264           else {
265             const int64_t high_bit_set = 1ULL << 63;
266             const uint64_t mask = (high_bit_set >> (63 - bits));
267             return (((uint64_t)Res & mask) == mask) ? true : false;
268           }
269         }
270       } else if (myMCExpr->getKind() == MCExpr::SymbolRef && isRelocatable)
271         return true;
272       else if (myMCExpr->getKind() == MCExpr::Binary ||
273                myMCExpr->getKind() == MCExpr::Unary)
274         return true;
275     }
276     return false;
277   }
278 
279   bool isf32Ext() const { return false; }
280   bool iss32Imm() const { return CheckImmRange(32, 0, true, true, false); }
281   bool iss23_2Imm() const { return CheckImmRange(23, 2, true, true, false); }
282   bool iss8Imm() const { return CheckImmRange(8, 0, true, false, false); }
283   bool iss8Imm64() const { return CheckImmRange(8, 0, true, true, false); }
284   bool iss7Imm() const { return CheckImmRange(7, 0, true, false, false); }
285   bool iss6Imm() const { return CheckImmRange(6, 0, true, false, false); }
286   bool iss4Imm() const { return CheckImmRange(4, 0, true, false, false); }
287   bool iss4_0Imm() const { return CheckImmRange(4, 0, true, false, false); }
288   bool iss4_1Imm() const { return CheckImmRange(4, 1, true, false, false); }
289   bool iss4_2Imm() const { return CheckImmRange(4, 2, true, false, false); }
290   bool iss4_3Imm() const { return CheckImmRange(4, 3, true, false, false); }
291   bool iss4_6Imm() const { return CheckImmRange(4, 0, true, false, false); }
292   bool iss3_6Imm() const { return CheckImmRange(3, 0, true, false, false); }
293   bool iss3Imm() const { return CheckImmRange(3, 0, true, false, false); }
294 
295   bool isu64Imm() const { return CheckImmRange(64, 0, false, true, true); }
296   bool isu32Imm() const { return CheckImmRange(32, 0, false, true, false); }
297   bool isu26_6Imm() const { return CheckImmRange(26, 6, false, true, false); }
298   bool isu16Imm() const { return CheckImmRange(16, 0, false, true, false); }
299   bool isu16_0Imm() const { return CheckImmRange(16, 0, false, true, false); }
300   bool isu16_1Imm() const { return CheckImmRange(16, 1, false, true, false); }
301   bool isu16_2Imm() const { return CheckImmRange(16, 2, false, true, false); }
302   bool isu16_3Imm() const { return CheckImmRange(16, 3, false, true, false); }
303   bool isu11_3Imm() const { return CheckImmRange(11, 3, false, false, false); }
304   bool isu6_0Imm() const { return CheckImmRange(6, 0, false, false, false); }
305   bool isu6_1Imm() const { return CheckImmRange(6, 1, false, false, false); }
306   bool isu6_2Imm() const { return CheckImmRange(6, 2, false, false, false); }
307   bool isu6_3Imm() const { return CheckImmRange(6, 3, false, false, false); }
308   bool isu10Imm() const { return CheckImmRange(10, 0, false, false, false); }
309   bool isu9Imm() const { return CheckImmRange(9, 0, false, false, false); }
310   bool isu8Imm() const { return CheckImmRange(8, 0, false, false, false); }
311   bool isu7Imm() const { return CheckImmRange(7, 0, false, false, false); }
312   bool isu6Imm() const { return CheckImmRange(6, 0, false, false, false); }
313   bool isu5Imm() const { return CheckImmRange(5, 0, false, false, false); }
314   bool isu4Imm() const { return CheckImmRange(4, 0, false, false, false); }
315   bool isu3Imm() const { return CheckImmRange(3, 0, false, false, false); }
316   bool isu2Imm() const { return CheckImmRange(2, 0, false, false, false); }
317   bool isu1Imm() const { return CheckImmRange(1, 0, false, false, false); }
318 
319   bool ism6Imm() const { return CheckImmRange(6, 0, false, false, false); }
320   bool isn8Imm() const { return CheckImmRange(8, 0, false, false, false); }
321 
322   bool iss16Ext() const { return CheckImmRange(16 + 26, 0, true, true, true); }
323   bool iss12Ext() const { return CheckImmRange(12 + 26, 0, true, true, true); }
324   bool iss10Ext() const { return CheckImmRange(10 + 26, 0, true, true, true); }
325   bool iss9Ext() const { return CheckImmRange(9 + 26, 0, true, true, true); }
326   bool iss8Ext() const { return CheckImmRange(8 + 26, 0, true, true, true); }
327   bool iss7Ext() const { return CheckImmRange(7 + 26, 0, true, true, true); }
328   bool iss6Ext() const { return CheckImmRange(6 + 26, 0, true, true, true); }
329   bool iss11_0Ext() const {
330     return CheckImmRange(11 + 26, 0, true, true, true);
331   }
332   bool iss11_1Ext() const {
333     return CheckImmRange(11 + 26, 1, true, true, true);
334   }
335   bool iss11_2Ext() const {
336     return CheckImmRange(11 + 26, 2, true, true, true);
337   }
338   bool iss11_3Ext() const {
339     return CheckImmRange(11 + 26, 3, true, true, true);
340   }
341 
342   bool isu6Ext() const { return CheckImmRange(6 + 26, 0, false, true, true); }
343   bool isu7Ext() const { return CheckImmRange(7 + 26, 0, false, true, true); }
344   bool isu8Ext() const { return CheckImmRange(8 + 26, 0, false, true, true); }
345   bool isu9Ext() const { return CheckImmRange(9 + 26, 0, false, true, true); }
346   bool isu10Ext() const { return CheckImmRange(10 + 26, 0, false, true, true); }
347   bool isu6_0Ext() const { return CheckImmRange(6 + 26, 0, false, true, true); }
348   bool isu6_1Ext() const { return CheckImmRange(6 + 26, 1, false, true, true); }
349   bool isu6_2Ext() const { return CheckImmRange(6 + 26, 2, false, true, true); }
350   bool isu6_3Ext() const { return CheckImmRange(6 + 26, 3, false, true, true); }
351   bool isu32MustExt() const { return isImm() && Imm.MustExtend; }
352 
353   void addRegOperands(MCInst &Inst, unsigned N) const {
354     assert(N == 1 && "Invalid number of operands!");
355     Inst.addOperand(MCOperand::createReg(getReg()));
356   }
357 
358   void addImmOperands(MCInst &Inst, unsigned N) const {
359     assert(N == 1 && "Invalid number of operands!");
360     Inst.addOperand(MCOperand::createExpr(getImm()));
361   }
362 
363   void addSignedImmOperands(MCInst &Inst, unsigned N) const {
364     assert(N == 1 && "Invalid number of operands!");
365     MCExpr const *Expr = getImm();
366     int64_t Value;
367     if (!Expr->evaluateAsAbsolute(Value)) {
368       Inst.addOperand(MCOperand::createExpr(Expr));
369       return;
370     }
371     int64_t Extended = SignExtend64 (Value, 32);
372     if ((Extended < 0) == (Value < 0)) {
373       Inst.addOperand(MCOperand::createExpr(Expr));
374       return;
375     }
376     // Flip bit 33 to signal signed unsigned mismatch
377     Extended ^= 0x100000000;
378     Inst.addOperand(MCOperand::createImm(Extended));
379   }
380 
381   void addf32ExtOperands(MCInst &Inst, unsigned N) const {
382     addImmOperands(Inst, N);
383   }
384 
385   void adds32ImmOperands(MCInst &Inst, unsigned N) const {
386     addSignedImmOperands(Inst, N);
387   }
388   void adds23_2ImmOperands(MCInst &Inst, unsigned N) const {
389     addSignedImmOperands(Inst, N);
390   }
391   void adds8ImmOperands(MCInst &Inst, unsigned N) const {
392     addSignedImmOperands(Inst, N);
393   }
394   void adds8Imm64Operands(MCInst &Inst, unsigned N) const {
395     addSignedImmOperands(Inst, N);
396   }
397   void adds6ImmOperands(MCInst &Inst, unsigned N) const {
398     addSignedImmOperands(Inst, N);
399   }
400   void adds4ImmOperands(MCInst &Inst, unsigned N) const {
401     addSignedImmOperands(Inst, N);
402   }
403   void adds4_0ImmOperands(MCInst &Inst, unsigned N) const {
404     addSignedImmOperands(Inst, N);
405   }
406   void adds4_1ImmOperands(MCInst &Inst, unsigned N) const {
407     addSignedImmOperands(Inst, N);
408   }
409   void adds4_2ImmOperands(MCInst &Inst, unsigned N) const {
410     addSignedImmOperands(Inst, N);
411   }
412   void adds4_3ImmOperands(MCInst &Inst, unsigned N) const {
413     addSignedImmOperands(Inst, N);
414   }
415   void adds3ImmOperands(MCInst &Inst, unsigned N) const {
416     addSignedImmOperands(Inst, N);
417   }
418 
419   void addu64ImmOperands(MCInst &Inst, unsigned N) const {
420     addImmOperands(Inst, N);
421   }
422   void addu32ImmOperands(MCInst &Inst, unsigned N) const {
423     addImmOperands(Inst, N);
424   }
425   void addu26_6ImmOperands(MCInst &Inst, unsigned N) const {
426     addImmOperands(Inst, N);
427   }
428   void addu16ImmOperands(MCInst &Inst, unsigned N) const {
429     addImmOperands(Inst, N);
430   }
431   void addu16_0ImmOperands(MCInst &Inst, unsigned N) const {
432     addImmOperands(Inst, N);
433   }
434   void addu16_1ImmOperands(MCInst &Inst, unsigned N) const {
435     addImmOperands(Inst, N);
436   }
437   void addu16_2ImmOperands(MCInst &Inst, unsigned N) const {
438     addImmOperands(Inst, N);
439   }
440   void addu16_3ImmOperands(MCInst &Inst, unsigned N) const {
441     addImmOperands(Inst, N);
442   }
443   void addu11_3ImmOperands(MCInst &Inst, unsigned N) const {
444     addImmOperands(Inst, N);
445   }
446   void addu10ImmOperands(MCInst &Inst, unsigned N) const {
447     addImmOperands(Inst, N);
448   }
449   void addu9ImmOperands(MCInst &Inst, unsigned N) const {
450     addImmOperands(Inst, N);
451   }
452   void addu8ImmOperands(MCInst &Inst, unsigned N) const {
453     addImmOperands(Inst, N);
454   }
455   void addu7ImmOperands(MCInst &Inst, unsigned N) const {
456     addImmOperands(Inst, N);
457   }
458   void addu6ImmOperands(MCInst &Inst, unsigned N) const {
459     addImmOperands(Inst, N);
460   }
461   void addu6_0ImmOperands(MCInst &Inst, unsigned N) const {
462     addImmOperands(Inst, N);
463   }
464   void addu6_1ImmOperands(MCInst &Inst, unsigned N) const {
465     addImmOperands(Inst, N);
466   }
467   void addu6_2ImmOperands(MCInst &Inst, unsigned N) const {
468     addImmOperands(Inst, N);
469   }
470   void addu6_3ImmOperands(MCInst &Inst, unsigned N) const {
471     addImmOperands(Inst, N);
472   }
473   void addu5ImmOperands(MCInst &Inst, unsigned N) const {
474     addImmOperands(Inst, N);
475   }
476   void addu4ImmOperands(MCInst &Inst, unsigned N) const {
477     addImmOperands(Inst, N);
478   }
479   void addu3ImmOperands(MCInst &Inst, unsigned N) const {
480     addImmOperands(Inst, N);
481   }
482   void addu2ImmOperands(MCInst &Inst, unsigned N) const {
483     addImmOperands(Inst, N);
484   }
485   void addu1ImmOperands(MCInst &Inst, unsigned N) const {
486     addImmOperands(Inst, N);
487   }
488 
489   void addm6ImmOperands(MCInst &Inst, unsigned N) const {
490     addImmOperands(Inst, N);
491   }
492   void addn8ImmOperands(MCInst &Inst, unsigned N) const {
493     addImmOperands(Inst, N);
494   }
495 
496   void adds16ExtOperands(MCInst &Inst, unsigned N) const {
497     addSignedImmOperands(Inst, N);
498   }
499   void adds12ExtOperands(MCInst &Inst, unsigned N) const {
500     addSignedImmOperands(Inst, N);
501   }
502   void adds10ExtOperands(MCInst &Inst, unsigned N) const {
503     addSignedImmOperands(Inst, N);
504   }
505   void adds9ExtOperands(MCInst &Inst, unsigned N) const {
506     addSignedImmOperands(Inst, N);
507   }
508   void adds8ExtOperands(MCInst &Inst, unsigned N) const {
509     addSignedImmOperands(Inst, N);
510   }
511   void adds6ExtOperands(MCInst &Inst, unsigned N) const {
512     addSignedImmOperands(Inst, N);
513   }
514   void adds11_0ExtOperands(MCInst &Inst, unsigned N) const {
515     addSignedImmOperands(Inst, N);
516   }
517   void adds11_1ExtOperands(MCInst &Inst, unsigned N) const {
518     addSignedImmOperands(Inst, N);
519   }
520   void adds11_2ExtOperands(MCInst &Inst, unsigned N) const {
521     addSignedImmOperands(Inst, N);
522   }
523   void adds11_3ExtOperands(MCInst &Inst, unsigned N) const {
524     addSignedImmOperands(Inst, N);
525   }
526 
527   void addu6ExtOperands(MCInst &Inst, unsigned N) const {
528     addImmOperands(Inst, N);
529   }
530   void addu7ExtOperands(MCInst &Inst, unsigned N) const {
531     addImmOperands(Inst, N);
532   }
533   void addu8ExtOperands(MCInst &Inst, unsigned N) const {
534     addImmOperands(Inst, N);
535   }
536   void addu9ExtOperands(MCInst &Inst, unsigned N) const {
537     addImmOperands(Inst, N);
538   }
539   void addu10ExtOperands(MCInst &Inst, unsigned N) const {
540     addImmOperands(Inst, N);
541   }
542   void addu6_0ExtOperands(MCInst &Inst, unsigned N) const {
543     addImmOperands(Inst, N);
544   }
545   void addu6_1ExtOperands(MCInst &Inst, unsigned N) const {
546     addImmOperands(Inst, N);
547   }
548   void addu6_2ExtOperands(MCInst &Inst, unsigned N) const {
549     addImmOperands(Inst, N);
550   }
551   void addu6_3ExtOperands(MCInst &Inst, unsigned N) const {
552     addImmOperands(Inst, N);
553   }
554   void addu32MustExtOperands(MCInst &Inst, unsigned N) const {
555     addImmOperands(Inst, N);
556   }
557 
558   void adds4_6ImmOperands(MCInst &Inst, unsigned N) const {
559     assert(N == 1 && "Invalid number of operands!");
560     const MCConstantExpr *CE =
561         dyn_cast<MCConstantExpr>(&HexagonMCInstrInfo::getExpr(*getImm()));
562     Inst.addOperand(MCOperand::createImm(CE->getValue() * 64));
563   }
564 
565   void adds3_6ImmOperands(MCInst &Inst, unsigned N) const {
566     assert(N == 1 && "Invalid number of operands!");
567     const MCConstantExpr *CE =
568         dyn_cast<MCConstantExpr>(&HexagonMCInstrInfo::getExpr(*getImm()));
569     Inst.addOperand(MCOperand::createImm(CE->getValue() * 64));
570   }
571 
572   StringRef getToken() const {
573     assert(Kind == Token && "Invalid access!");
574     return StringRef(Tok.Data, Tok.Length);
575   }
576 
577   virtual void print(raw_ostream &OS) const;
578 
579   static std::unique_ptr<HexagonOperand> CreateToken(StringRef Str, SMLoc S) {
580     HexagonOperand *Op = new HexagonOperand(Token);
581     Op->Tok.Data = Str.data();
582     Op->Tok.Length = Str.size();
583     Op->StartLoc = S;
584     Op->EndLoc = S;
585     return std::unique_ptr<HexagonOperand>(Op);
586   }
587 
588   static std::unique_ptr<HexagonOperand> CreateReg(unsigned RegNum, SMLoc S,
589                                                    SMLoc E) {
590     HexagonOperand *Op = new HexagonOperand(Register);
591     Op->Reg.RegNum = RegNum;
592     Op->StartLoc = S;
593     Op->EndLoc = E;
594     return std::unique_ptr<HexagonOperand>(Op);
595   }
596 
597   static std::unique_ptr<HexagonOperand> CreateImm(const MCExpr *Val, SMLoc S,
598                                                    SMLoc E) {
599     HexagonOperand *Op = new HexagonOperand(Immediate);
600     Op->Imm.Val = Val;
601     Op->Imm.MustExtend = false;
602     Op->StartLoc = S;
603     Op->EndLoc = E;
604     return std::unique_ptr<HexagonOperand>(Op);
605   }
606 };
607 
608 } // end anonymous namespace.
609 
610 void HexagonOperand::print(raw_ostream &OS) const {
611   switch (Kind) {
612   case Immediate:
613     getImm()->print(OS, nullptr);
614     break;
615   case Register:
616     OS << "<register R";
617     OS << getReg() << ">";
618     break;
619   case Token:
620     OS << "'" << getToken() << "'";
621     break;
622   }
623 }
624 
625 /// @name Auto-generated Match Functions
626 static unsigned MatchRegisterName(StringRef Name);
627 
628 bool HexagonAsmParser::finishBundle(SMLoc IDLoc, MCStreamer &Out) {
629   DEBUG(dbgs() << "Bundle:");
630   DEBUG(MCB.dump_pretty(dbgs()));
631   DEBUG(dbgs() << "--\n");
632 
633   // Check the bundle for errors.
634   const MCRegisterInfo *RI = getContext().getRegisterInfo();
635   HexagonMCChecker Check(MCII, getSTI(), MCB, MCB, *RI);
636 
637   bool CheckOk = HexagonMCInstrInfo::canonicalizePacket(MCII, getSTI(),
638                                                         getContext(), MCB,
639                                                         &Check);
640 
641   while (Check.getNextErrInfo() == true) {
642     unsigned Reg = Check.getErrRegister();
643     Twine R(RI->getName(Reg));
644 
645     uint64_t Err = Check.getError();
646     if (Err != HexagonMCErrInfo::CHECK_SUCCESS) {
647       if (HexagonMCErrInfo::CHECK_ERROR_BRANCHES & Err)
648         Error(IDLoc,
649               "unconditional branch cannot precede another branch in packet");
650 
651       if (HexagonMCErrInfo::CHECK_ERROR_NEWP & Err ||
652           HexagonMCErrInfo::CHECK_ERROR_NEWV & Err)
653         Error(IDLoc, "register `" + R +
654                          "' used with `.new' "
655                          "but not validly modified in the same packet");
656 
657       if (HexagonMCErrInfo::CHECK_ERROR_REGISTERS & Err)
658         Error(IDLoc, "register `" + R + "' modified more than once");
659 
660       if (HexagonMCErrInfo::CHECK_ERROR_READONLY & Err)
661         Error(IDLoc, "cannot write to read-only register `" + R + "'");
662 
663       if (HexagonMCErrInfo::CHECK_ERROR_LOOP & Err)
664         Error(IDLoc, "loop-setup and some branch instructions "
665                      "cannot be in the same packet");
666 
667       if (HexagonMCErrInfo::CHECK_ERROR_ENDLOOP & Err) {
668         Twine N(HexagonMCInstrInfo::isInnerLoop(MCB) ? '0' : '1');
669         Error(IDLoc, "packet marked with `:endloop" + N + "' " +
670                          "cannot contain instructions that modify register " +
671                          "`" + R + "'");
672       }
673 
674       if (HexagonMCErrInfo::CHECK_ERROR_SOLO & Err)
675         Error(IDLoc,
676               "instruction cannot appear in packet with other instructions");
677 
678       if (HexagonMCErrInfo::CHECK_ERROR_NOSLOTS & Err)
679         Error(IDLoc, "too many slots used in packet");
680 
681       if (Err & HexagonMCErrInfo::CHECK_ERROR_SHUFFLE) {
682         uint64_t Erm = Check.getShuffleError();
683 
684         if (HexagonShuffler::SHUFFLE_ERROR_INVALID == Erm)
685           Error(IDLoc, "invalid instruction packet");
686         else if (HexagonShuffler::SHUFFLE_ERROR_STORES == Erm)
687           Error(IDLoc, "invalid instruction packet: too many stores");
688         else if (HexagonShuffler::SHUFFLE_ERROR_LOADS == Erm)
689           Error(IDLoc, "invalid instruction packet: too many loads");
690         else if (HexagonShuffler::SHUFFLE_ERROR_BRANCHES == Erm)
691           Error(IDLoc, "too many branches in packet");
692         else if (HexagonShuffler::SHUFFLE_ERROR_NOSLOTS == Erm)
693           Error(IDLoc, "invalid instruction packet: out of slots");
694         else if (HexagonShuffler::SHUFFLE_ERROR_SLOTS == Erm)
695           Error(IDLoc, "invalid instruction packet: slot error");
696         else if (HexagonShuffler::SHUFFLE_ERROR_ERRATA2 == Erm)
697           Error(IDLoc, "v60 packet violation");
698         else if (HexagonShuffler::SHUFFLE_ERROR_STORE_LOAD_CONFLICT == Erm)
699           Error(IDLoc, "slot 0 instruction does not allow slot 1 store");
700         else
701           Error(IDLoc, "unknown error in instruction packet");
702       }
703     }
704 
705     unsigned Warn = Check.getWarning();
706     if (Warn != HexagonMCErrInfo::CHECK_SUCCESS) {
707       if (HexagonMCErrInfo::CHECK_WARN_CURRENT & Warn)
708         Warning(IDLoc, "register `" + R + "' used with `.cur' "
709                                           "but not used in the same packet");
710       else if (HexagonMCErrInfo::CHECK_WARN_TEMPORARY & Warn)
711         Warning(IDLoc, "register `" + R + "' used with `.tmp' "
712                                           "but not used in the same packet");
713     }
714   }
715 
716   if (CheckOk) {
717     MCB.setLoc(IDLoc);
718     if (HexagonMCInstrInfo::bundleSize(MCB) == 0) {
719       assert(!HexagonMCInstrInfo::isInnerLoop(MCB));
720       assert(!HexagonMCInstrInfo::isOuterLoop(MCB));
721       // Empty packets are valid yet aren't emitted
722       return false;
723     }
724     Out.EmitInstruction(MCB, getSTI());
725   } else {
726     // If compounding and duplexing didn't reduce the size below
727     // 4 or less we have a packet that is too big.
728     if (HexagonMCInstrInfo::bundleSize(MCB) > HEXAGON_PACKET_SIZE) {
729       Error(IDLoc, "invalid instruction packet: out of slots");
730       return true; // Error
731     }
732   }
733 
734   return false; // No error
735 }
736 
737 bool HexagonAsmParser::matchBundleOptions() {
738   MCAsmParser &Parser = getParser();
739   MCAsmLexer &Lexer = getLexer();
740   while (true) {
741     if (!Parser.getTok().is(AsmToken::Colon))
742       return false;
743     Lexer.Lex();
744     StringRef Option = Parser.getTok().getString();
745     if (Option.compare_lower("endloop0") == 0)
746       HexagonMCInstrInfo::setInnerLoop(MCB);
747     else if (Option.compare_lower("endloop1") == 0)
748       HexagonMCInstrInfo::setOuterLoop(MCB);
749     else if (Option.compare_lower("mem_noshuf") == 0)
750       HexagonMCInstrInfo::setMemReorderDisabled(MCB);
751     else if (Option.compare_lower("mem_shuf") == 0)
752       HexagonMCInstrInfo::setMemStoreReorderEnabled(MCB);
753     else
754       return true;
755     Lexer.Lex();
756   }
757 }
758 
759 // For instruction aliases, immediates are generated rather than
760 // MCConstantExpr.  Convert them for uniform MCExpr.
761 // Also check for signed/unsigned mismatches and warn
762 void HexagonAsmParser::canonicalizeImmediates(MCInst &MCI) {
763   MCInst NewInst;
764   NewInst.setOpcode(MCI.getOpcode());
765   for (MCOperand &I : MCI)
766     if (I.isImm()) {
767       int64_t Value (I.getImm());
768       if ((Value & 0x100000000) != (Value & 0x80000000)) {
769         // Detect flipped bit 33 wrt bit 32 and signal warning
770         Value ^= 0x100000000;
771         if (WarnSignedMismatch)
772           Warning (MCI.getLoc(), "Signed/Unsigned mismatch");
773       }
774       NewInst.addOperand(MCOperand::createExpr(HexagonMCExpr::create(
775           MCConstantExpr::create(Value, getContext()), getContext())));
776     }
777     else
778       NewInst.addOperand(I);
779   MCI = NewInst;
780 }
781 
782 bool HexagonAsmParser::matchOneInstruction(MCInst &MCI, SMLoc IDLoc,
783                                            OperandVector &InstOperands,
784                                            uint64_t &ErrorInfo,
785                                            bool MatchingInlineAsm,
786                                            bool &MustExtend) {
787   // Perform matching with tablegen asmmatcher generated function
788   int result =
789       MatchInstructionImpl(InstOperands, MCI, ErrorInfo, MatchingInlineAsm);
790   if (result == Match_Success) {
791     MCI.setLoc(IDLoc);
792     MustExtend = mustExtend(InstOperands);
793     canonicalizeImmediates(MCI);
794     result = processInstruction(MCI, InstOperands, IDLoc, MustExtend);
795 
796     DEBUG(dbgs() << "Insn:");
797     DEBUG(MCI.dump_pretty(dbgs()));
798     DEBUG(dbgs() << "\n\n");
799 
800     MCI.setLoc(IDLoc);
801   }
802 
803   // Create instruction operand for bundle instruction
804   //   Break this into a separate function Code here is less readable
805   //   Think about how to get an instruction error to report correctly.
806   //   SMLoc will return the "{"
807   switch (result) {
808   default:
809     break;
810   case Match_Success:
811     return false;
812   case Match_MissingFeature:
813     return Error(IDLoc, "invalid instruction");
814   case Match_MnemonicFail:
815     return Error(IDLoc, "unrecognized instruction");
816   case Match_InvalidOperand:
817     SMLoc ErrorLoc = IDLoc;
818     if (ErrorInfo != ~0U) {
819       if (ErrorInfo >= InstOperands.size())
820         return Error(IDLoc, "too few operands for instruction");
821 
822       ErrorLoc = (static_cast<HexagonOperand *>(InstOperands[ErrorInfo].get()))
823                      ->getStartLoc();
824       if (ErrorLoc == SMLoc())
825         ErrorLoc = IDLoc;
826     }
827     return Error(ErrorLoc, "invalid operand for instruction");
828   }
829   llvm_unreachable("Implement any new match types added!");
830 }
831 
832 bool HexagonAsmParser::mustExtend(OperandVector &Operands) {
833   unsigned Count = 0;
834   for (std::unique_ptr<MCParsedAsmOperand> &i : Operands)
835     if (i->isImm())
836       if (static_cast<HexagonOperand *>(i.get())->Imm.MustExtend)
837         ++Count;
838   // Multiple extenders should have been filtered by iss9Ext et. al.
839   assert(Count < 2 && "Multiple extenders");
840   return Count == 1;
841 }
842 
843 bool HexagonAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
844                                                OperandVector &Operands,
845                                                MCStreamer &Out,
846                                                uint64_t &ErrorInfo,
847                                                bool MatchingInlineAsm) {
848   if (!InBrackets) {
849     MCB.clear();
850     MCB.addOperand(MCOperand::createImm(0));
851   }
852   HexagonOperand &FirstOperand = static_cast<HexagonOperand &>(*Operands[0]);
853   if (FirstOperand.isToken() && FirstOperand.getToken() == "{") {
854     assert(Operands.size() == 1 && "Brackets should be by themselves");
855     if (InBrackets) {
856       getParser().Error(IDLoc, "Already in a packet");
857       return true;
858     }
859     InBrackets = true;
860     return false;
861   }
862   if (FirstOperand.isToken() && FirstOperand.getToken() == "}") {
863     assert(Operands.size() == 1 && "Brackets should be by themselves");
864     if (!InBrackets) {
865       getParser().Error(IDLoc, "Not in a packet");
866       return true;
867     }
868     InBrackets = false;
869     if (matchBundleOptions())
870       return true;
871     return finishBundle(IDLoc, Out);
872   }
873   MCInst *SubInst = new (getParser().getContext()) MCInst;
874   bool MustExtend = false;
875   if (matchOneInstruction(*SubInst, IDLoc, Operands, ErrorInfo,
876                           MatchingInlineAsm, MustExtend))
877     return true;
878   HexagonMCInstrInfo::extendIfNeeded(
879       getParser().getContext(), MCII, MCB, *SubInst,
880       HexagonMCInstrInfo::isExtended(MCII, *SubInst) || MustExtend);
881   MCB.addOperand(MCOperand::createInst(SubInst));
882   if (!InBrackets)
883     return finishBundle(IDLoc, Out);
884   return false;
885 }
886 
887 /// ParseDirective parses the Hexagon specific directives
888 bool HexagonAsmParser::ParseDirective(AsmToken DirectiveID) {
889   StringRef IDVal = DirectiveID.getIdentifier();
890   if ((IDVal.lower() == ".word") || (IDVal.lower() == ".4byte"))
891     return ParseDirectiveValue(4, DirectiveID.getLoc());
892   if (IDVal.lower() == ".short" || IDVal.lower() == ".hword" ||
893       IDVal.lower() == ".half")
894     return ParseDirectiveValue(2, DirectiveID.getLoc());
895   if (IDVal.lower() == ".falign")
896     return ParseDirectiveFalign(256, DirectiveID.getLoc());
897   if ((IDVal.lower() == ".lcomm") || (IDVal.lower() == ".lcommon"))
898     return ParseDirectiveComm(true, DirectiveID.getLoc());
899   if ((IDVal.lower() == ".comm") || (IDVal.lower() == ".common"))
900     return ParseDirectiveComm(false, DirectiveID.getLoc());
901   if (IDVal.lower() == ".subsection")
902     return ParseDirectiveSubsection(DirectiveID.getLoc());
903 
904   return true;
905 }
906 bool HexagonAsmParser::ParseDirectiveSubsection(SMLoc L) {
907   const MCExpr *Subsection = 0;
908   int64_t Res;
909 
910   assert((getLexer().isNot(AsmToken::EndOfStatement)) &&
911          "Invalid subsection directive");
912   getParser().parseExpression(Subsection);
913 
914   if (!Subsection->evaluateAsAbsolute(Res))
915     return Error(L, "Cannot evaluate subsection number");
916 
917   if (getLexer().isNot(AsmToken::EndOfStatement))
918     return TokError("unexpected token in directive");
919 
920   // 0-8192 is the hard-coded range in MCObjectStreamper.cpp, this keeps the
921   // negative subsections together and in the same order but at the opposite
922   // end of the section.  Only legacy hexagon-gcc created assembly code
923   // used negative subsections.
924   if ((Res < 0) && (Res > -8193))
925     Subsection = HexagonMCExpr::create(
926         MCConstantExpr::create(8192 + Res, getContext()), getContext());
927 
928   getStreamer().SubSection(Subsection);
929   return false;
930 }
931 
932 ///  ::= .falign [expression]
933 bool HexagonAsmParser::ParseDirectiveFalign(unsigned Size, SMLoc L) {
934 
935   int64_t MaxBytesToFill = 15;
936 
937   // if there is an arguement
938   if (getLexer().isNot(AsmToken::EndOfStatement)) {
939     const MCExpr *Value;
940     SMLoc ExprLoc = L;
941 
942     // Make sure we have a number (false is returned if expression is a number)
943     if (getParser().parseExpression(Value) == false) {
944       // Make sure this is a number that is in range
945       const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
946       uint64_t IntValue = MCE->getValue();
947       if (!isUIntN(Size, IntValue) && !isIntN(Size, IntValue))
948         return Error(ExprLoc, "literal value out of range (256) for falign");
949       MaxBytesToFill = IntValue;
950       Lex();
951     } else {
952       return Error(ExprLoc, "not a valid expression for falign directive");
953     }
954   }
955 
956   getTargetStreamer().emitFAlign(16, MaxBytesToFill);
957   Lex();
958 
959   return false;
960 }
961 
962 ///  ::= .word [ expression (, expression)* ]
963 bool HexagonAsmParser::ParseDirectiveValue(unsigned Size, SMLoc L) {
964   if (getLexer().isNot(AsmToken::EndOfStatement)) {
965 
966     for (;;) {
967       const MCExpr *Value;
968       SMLoc ExprLoc = L;
969       if (getParser().parseExpression(Value))
970         return true;
971 
972       // Special case constant expressions to match code generator.
973       if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
974         assert(Size <= 8 && "Invalid size");
975         uint64_t IntValue = MCE->getValue();
976         if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
977           return Error(ExprLoc, "literal value out of range for directive");
978         getStreamer().EmitIntValue(IntValue, Size);
979       } else
980         getStreamer().EmitValue(Value, Size);
981 
982       if (getLexer().is(AsmToken::EndOfStatement))
983         break;
984 
985       // FIXME: Improve diagnostic.
986       if (getLexer().isNot(AsmToken::Comma))
987         return TokError("unexpected token in directive");
988       Lex();
989     }
990   }
991 
992   Lex();
993   return false;
994 }
995 
996 // This is largely a copy of AsmParser's ParseDirectiveComm extended to
997 // accept a 3rd argument, AccessAlignment which indicates the smallest
998 // memory access made to the symbol, expressed in bytes.  If no
999 // AccessAlignment is specified it defaults to the Alignment Value.
1000 // Hexagon's .lcomm:
1001 //   .lcomm Symbol, Length, Alignment, AccessAlignment
1002 bool HexagonAsmParser::ParseDirectiveComm(bool IsLocal, SMLoc Loc) {
1003   // FIXME: need better way to detect if AsmStreamer (upstream removed
1004   // getKind())
1005   if (getStreamer().hasRawTextSupport())
1006     return true; // Only object file output requires special treatment.
1007 
1008   StringRef Name;
1009   if (getParser().parseIdentifier(Name))
1010     return TokError("expected identifier in directive");
1011   // Handle the identifier as the key symbol.
1012   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
1013 
1014   if (getLexer().isNot(AsmToken::Comma))
1015     return TokError("unexpected token in directive");
1016   Lex();
1017 
1018   int64_t Size;
1019   SMLoc SizeLoc = getLexer().getLoc();
1020   if (getParser().parseAbsoluteExpression(Size))
1021     return true;
1022 
1023   int64_t ByteAlignment = 1;
1024   SMLoc ByteAlignmentLoc;
1025   if (getLexer().is(AsmToken::Comma)) {
1026     Lex();
1027     ByteAlignmentLoc = getLexer().getLoc();
1028     if (getParser().parseAbsoluteExpression(ByteAlignment))
1029       return true;
1030     if (!isPowerOf2_64(ByteAlignment))
1031       return Error(ByteAlignmentLoc, "alignment must be a power of 2");
1032   }
1033 
1034   int64_t AccessAlignment = 0;
1035   if (getLexer().is(AsmToken::Comma)) {
1036     // The optional access argument specifies the size of the smallest memory
1037     //   access to be made to the symbol, expressed in bytes.
1038     SMLoc AccessAlignmentLoc;
1039     Lex();
1040     AccessAlignmentLoc = getLexer().getLoc();
1041     if (getParser().parseAbsoluteExpression(AccessAlignment))
1042       return true;
1043 
1044     if (!isPowerOf2_64(AccessAlignment))
1045       return Error(AccessAlignmentLoc, "access alignment must be a power of 2");
1046   }
1047 
1048   if (getLexer().isNot(AsmToken::EndOfStatement))
1049     return TokError("unexpected token in '.comm' or '.lcomm' directive");
1050 
1051   Lex();
1052 
1053   // NOTE: a size of zero for a .comm should create a undefined symbol
1054   // but a size of .lcomm creates a bss symbol of size zero.
1055   if (Size < 0)
1056     return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1057                           "be less than zero");
1058 
1059   // NOTE: The alignment in the directive is a power of 2 value, the assembler
1060   // may internally end up wanting an alignment in bytes.
1061   // FIXME: Diagnose overflow.
1062   if (ByteAlignment < 0)
1063     return Error(ByteAlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1064                                    "alignment, can't be less than zero");
1065 
1066   if (!Sym->isUndefined())
1067     return Error(Loc, "invalid symbol redefinition");
1068 
1069   HexagonMCELFStreamer &HexagonELFStreamer =
1070       static_cast<HexagonMCELFStreamer &>(getStreamer());
1071   if (IsLocal) {
1072     HexagonELFStreamer.HexagonMCEmitLocalCommonSymbol(Sym, Size, ByteAlignment,
1073                                                       AccessAlignment);
1074     return false;
1075   }
1076 
1077   HexagonELFStreamer.HexagonMCEmitCommonSymbol(Sym, Size, ByteAlignment,
1078                                                AccessAlignment);
1079   return false;
1080 }
1081 
1082 // validate register against architecture
1083 bool HexagonAsmParser::RegisterMatchesArch(unsigned MatchNum) const {
1084   return true;
1085 }
1086 
1087 // extern "C" void LLVMInitializeHexagonAsmLexer();
1088 
1089 /// Force static initialization.
1090 extern "C" void LLVMInitializeHexagonAsmParser() {
1091   RegisterMCAsmParser<HexagonAsmParser> X(TheHexagonTarget);
1092 }
1093 
1094 #define GET_MATCHER_IMPLEMENTATION
1095 #define GET_REGISTER_MATCHER
1096 #include "HexagonGenAsmMatcher.inc"
1097 
1098 namespace {
1099 bool previousEqual(OperandVector &Operands, size_t Index, StringRef String) {
1100   if (Index >= Operands.size())
1101     return false;
1102   MCParsedAsmOperand &Operand = *Operands[Operands.size() - Index - 1];
1103   if (!Operand.isToken())
1104     return false;
1105   return static_cast<HexagonOperand &>(Operand).getToken().equals_lower(String);
1106 }
1107 bool previousIsLoop(OperandVector &Operands, size_t Index) {
1108   return previousEqual(Operands, Index, "loop0") ||
1109          previousEqual(Operands, Index, "loop1") ||
1110          previousEqual(Operands, Index, "sp1loop0") ||
1111          previousEqual(Operands, Index, "sp2loop0") ||
1112          previousEqual(Operands, Index, "sp3loop0");
1113 }
1114 }
1115 
1116 bool HexagonAsmParser::splitIdentifier(OperandVector &Operands) {
1117   AsmToken const &Token = getParser().getTok();
1118   StringRef String = Token.getString();
1119   SMLoc Loc = Token.getLoc();
1120   getLexer().Lex();
1121   do {
1122     std::pair<StringRef, StringRef> HeadTail = String.split('.');
1123     if (!HeadTail.first.empty())
1124       Operands.push_back(HexagonOperand::CreateToken(HeadTail.first, Loc));
1125     if (!HeadTail.second.empty())
1126       Operands.push_back(HexagonOperand::CreateToken(
1127           String.substr(HeadTail.first.size(), 1), Loc));
1128     String = HeadTail.second;
1129   } while (!String.empty());
1130   return false;
1131 }
1132 
1133 bool HexagonAsmParser::parseOperand(OperandVector &Operands) {
1134   unsigned Register;
1135   SMLoc Begin;
1136   SMLoc End;
1137   MCAsmLexer &Lexer = getLexer();
1138   if (!ParseRegister(Register, Begin, End)) {
1139     if (!ErrorMissingParenthesis)
1140       switch (Register) {
1141       default:
1142         break;
1143       case Hexagon::P0:
1144       case Hexagon::P1:
1145       case Hexagon::P2:
1146       case Hexagon::P3:
1147         if (previousEqual(Operands, 0, "if")) {
1148           if (WarnMissingParenthesis)
1149             Warning (Begin, "Missing parenthesis around predicate register");
1150           static char const *LParen = "(";
1151           static char const *RParen = ")";
1152           Operands.push_back(HexagonOperand::CreateToken(LParen, Begin));
1153           Operands.push_back(HexagonOperand::CreateReg(Register, Begin, End));
1154           AsmToken MaybeDotNew = Lexer.getTok();
1155           if (MaybeDotNew.is(AsmToken::TokenKind::Identifier) &&
1156               MaybeDotNew.getString().equals_lower(".new"))
1157             splitIdentifier(Operands);
1158           Operands.push_back(HexagonOperand::CreateToken(RParen, Begin));
1159           return false;
1160         }
1161         if (previousEqual(Operands, 0, "!") &&
1162             previousEqual(Operands, 1, "if")) {
1163           if (WarnMissingParenthesis)
1164             Warning (Begin, "Missing parenthesis around predicate register");
1165           static char const *LParen = "(";
1166           static char const *RParen = ")";
1167           Operands.insert(Operands.end () - 1,
1168                           HexagonOperand::CreateToken(LParen, Begin));
1169           Operands.push_back(HexagonOperand::CreateReg(Register, Begin, End));
1170           AsmToken MaybeDotNew = Lexer.getTok();
1171           if (MaybeDotNew.is(AsmToken::TokenKind::Identifier) &&
1172               MaybeDotNew.getString().equals_lower(".new"))
1173             splitIdentifier(Operands);
1174           Operands.push_back(HexagonOperand::CreateToken(RParen, Begin));
1175           return false;
1176         }
1177         break;
1178       }
1179     Operands.push_back(HexagonOperand::CreateReg(
1180         Register, Begin, End));
1181     return false;
1182   }
1183   return splitIdentifier(Operands);
1184 }
1185 
1186 bool HexagonAsmParser::isLabel(AsmToken &Token) {
1187   MCAsmLexer &Lexer = getLexer();
1188   AsmToken const &Second = Lexer.getTok();
1189   AsmToken Third = Lexer.peekTok();
1190   StringRef String = Token.getString();
1191   if (Token.is(AsmToken::TokenKind::LCurly) ||
1192       Token.is(AsmToken::TokenKind::RCurly))
1193     return false;
1194   if (!Token.is(AsmToken::TokenKind::Identifier))
1195     return true;
1196   if (!MatchRegisterName(String.lower()))
1197     return true;
1198   (void)Second;
1199   assert(Second.is(AsmToken::Colon));
1200   StringRef Raw (String.data(), Third.getString().data() - String.data() +
1201                  Third.getString().size());
1202   std::string Collapsed = Raw;
1203   Collapsed.erase(std::remove_if(Collapsed.begin(), Collapsed.end(), isspace),
1204                   Collapsed.end());
1205   StringRef Whole = Collapsed;
1206   std::pair<StringRef, StringRef> DotSplit = Whole.split('.');
1207   if (!MatchRegisterName(DotSplit.first.lower()))
1208     return true;
1209   return false;
1210 }
1211 
1212 bool HexagonAsmParser::handleNoncontigiousRegister(bool Contigious, SMLoc &Loc) {
1213   if (!Contigious && ErrorNoncontigiousRegister) {
1214     Error(Loc, "Register name is not contigious");
1215     return true;
1216   }
1217   if (!Contigious && WarnNoncontigiousRegister)
1218     Warning(Loc, "Register name is not contigious");
1219   return false;
1220 }
1221 
1222 bool HexagonAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) {
1223   MCAsmLexer &Lexer = getLexer();
1224   StartLoc = getLexer().getLoc();
1225   SmallVector<AsmToken, 5> Lookahead;
1226   StringRef RawString(Lexer.getTok().getString().data(), 0);
1227   bool Again = Lexer.is(AsmToken::Identifier);
1228   bool NeededWorkaround = false;
1229   while (Again) {
1230     AsmToken const &Token = Lexer.getTok();
1231     RawString = StringRef(RawString.data(),
1232                           Token.getString().data() - RawString.data () +
1233                           Token.getString().size());
1234     Lookahead.push_back(Token);
1235     Lexer.Lex();
1236     bool Contigious = Lexer.getTok().getString().data() ==
1237                       Lookahead.back().getString().data() +
1238                       Lookahead.back().getString().size();
1239     bool Type = Lexer.is(AsmToken::Identifier) || Lexer.is(AsmToken::Dot) ||
1240                 Lexer.is(AsmToken::Integer) || Lexer.is(AsmToken::Real) ||
1241                 Lexer.is(AsmToken::Colon);
1242     bool Workaround = Lexer.is(AsmToken::Colon) ||
1243                       Lookahead.back().is(AsmToken::Colon);
1244     Again = (Contigious && Type) || (Workaround && Type);
1245     NeededWorkaround = NeededWorkaround || (Again && !(Contigious && Type));
1246   }
1247   std::string Collapsed = RawString;
1248   Collapsed.erase(std::remove_if(Collapsed.begin(), Collapsed.end(), isspace),
1249                   Collapsed.end());
1250   StringRef FullString = Collapsed;
1251   std::pair<StringRef, StringRef> DotSplit = FullString.split('.');
1252   unsigned DotReg = MatchRegisterName(DotSplit.first.lower());
1253   if (DotReg != Hexagon::NoRegister && RegisterMatchesArch(DotReg)) {
1254     if (DotSplit.second.empty()) {
1255       RegNo = DotReg;
1256       EndLoc = Lexer.getLoc();
1257       if (handleNoncontigiousRegister(!NeededWorkaround, StartLoc))
1258         return true;
1259       return false;
1260     } else {
1261       RegNo = DotReg;
1262       size_t First = RawString.find('.');
1263       StringRef DotString (RawString.data() + First, RawString.size() - First);
1264       Lexer.UnLex(AsmToken(AsmToken::Identifier, DotString));
1265       EndLoc = Lexer.getLoc();
1266       if (handleNoncontigiousRegister(!NeededWorkaround, StartLoc))
1267         return true;
1268       return false;
1269     }
1270   }
1271   std::pair<StringRef, StringRef> ColonSplit = StringRef(FullString).split(':');
1272   unsigned ColonReg = MatchRegisterName(ColonSplit.first.lower());
1273   if (ColonReg != Hexagon::NoRegister && RegisterMatchesArch(DotReg)) {
1274     Lexer.UnLex(Lookahead.back());
1275     Lookahead.pop_back();
1276     Lexer.UnLex(Lookahead.back());
1277     Lookahead.pop_back();
1278     RegNo = ColonReg;
1279     EndLoc = Lexer.getLoc();
1280     if (handleNoncontigiousRegister(!NeededWorkaround, StartLoc))
1281       return true;
1282     return false;
1283   }
1284   while (!Lookahead.empty()) {
1285     Lexer.UnLex(Lookahead.back());
1286     Lookahead.pop_back();
1287   }
1288   return true;
1289 }
1290 
1291 bool HexagonAsmParser::implicitExpressionLocation(OperandVector &Operands) {
1292   if (previousEqual(Operands, 0, "call"))
1293     return true;
1294   if (previousEqual(Operands, 0, "jump"))
1295     if (!getLexer().getTok().is(AsmToken::Colon))
1296       return true;
1297   if (previousEqual(Operands, 0, "(") && previousIsLoop(Operands, 1))
1298     return true;
1299   if (previousEqual(Operands, 1, ":") && previousEqual(Operands, 2, "jump") &&
1300       (previousEqual(Operands, 0, "nt") || previousEqual(Operands, 0, "t")))
1301     return true;
1302   return false;
1303 }
1304 
1305 bool HexagonAsmParser::parseExpression(MCExpr const *& Expr) {
1306   llvm::SmallVector<AsmToken, 4> Tokens;
1307   MCAsmLexer &Lexer = getLexer();
1308   bool Done = false;
1309   static char const * Comma = ",";
1310   do {
1311     Tokens.emplace_back (Lexer.getTok());
1312     Lexer.Lex();
1313     switch (Tokens.back().getKind())
1314     {
1315     case AsmToken::TokenKind::Hash:
1316       if (Tokens.size () > 1)
1317         if ((Tokens.end () - 2)->getKind() == AsmToken::TokenKind::Plus) {
1318           Tokens.insert(Tokens.end() - 2,
1319                         AsmToken(AsmToken::TokenKind::Comma, Comma));
1320           Done = true;
1321         }
1322       break;
1323     case AsmToken::TokenKind::RCurly:
1324     case AsmToken::TokenKind::EndOfStatement:
1325     case AsmToken::TokenKind::Eof:
1326       Done = true;
1327       break;
1328     default:
1329       break;
1330     }
1331   } while (!Done);
1332   while (!Tokens.empty()) {
1333     Lexer.UnLex(Tokens.back());
1334     Tokens.pop_back();
1335   }
1336   return getParser().parseExpression(Expr);
1337 }
1338 
1339 bool HexagonAsmParser::parseExpressionOrOperand(OperandVector &Operands) {
1340   if (implicitExpressionLocation(Operands)) {
1341     MCAsmParser &Parser = getParser();
1342     SMLoc Loc = Parser.getLexer().getLoc();
1343     MCExpr const *Expr = nullptr;
1344     bool Error = parseExpression(Expr);
1345     Expr = HexagonMCExpr::create(Expr, getContext());
1346     if (!Error)
1347       Operands.push_back(HexagonOperand::CreateImm(Expr, Loc, Loc));
1348     return Error;
1349   }
1350   return parseOperand(Operands);
1351 }
1352 
1353 /// Parse an instruction.
1354 bool HexagonAsmParser::parseInstruction(OperandVector &Operands) {
1355   MCAsmParser &Parser = getParser();
1356   MCAsmLexer &Lexer = getLexer();
1357   while (true) {
1358     AsmToken const &Token = Parser.getTok();
1359     switch (Token.getKind()) {
1360     case AsmToken::EndOfStatement: {
1361       Lexer.Lex();
1362       return false;
1363     }
1364     case AsmToken::LCurly: {
1365       if (!Operands.empty())
1366         return true;
1367       Operands.push_back(
1368           HexagonOperand::CreateToken(Token.getString(), Token.getLoc()));
1369       Lexer.Lex();
1370       return false;
1371     }
1372     case AsmToken::RCurly: {
1373       if (Operands.empty()) {
1374         Operands.push_back(
1375             HexagonOperand::CreateToken(Token.getString(), Token.getLoc()));
1376         Lexer.Lex();
1377       }
1378       return false;
1379     }
1380     case AsmToken::Comma: {
1381       Lexer.Lex();
1382       continue;
1383     }
1384     case AsmToken::EqualEqual:
1385     case AsmToken::ExclaimEqual:
1386     case AsmToken::GreaterEqual:
1387     case AsmToken::GreaterGreater:
1388     case AsmToken::LessEqual:
1389     case AsmToken::LessLess: {
1390       Operands.push_back(HexagonOperand::CreateToken(
1391           Token.getString().substr(0, 1), Token.getLoc()));
1392       Operands.push_back(HexagonOperand::CreateToken(
1393           Token.getString().substr(1, 1), Token.getLoc()));
1394       Lexer.Lex();
1395       continue;
1396     }
1397     case AsmToken::Hash: {
1398       bool MustNotExtend = false;
1399       bool ImplicitExpression = implicitExpressionLocation(Operands);
1400       SMLoc ExprLoc = Lexer.getLoc();
1401       if (!ImplicitExpression)
1402         Operands.push_back(
1403           HexagonOperand::CreateToken(Token.getString(), Token.getLoc()));
1404       Lexer.Lex();
1405       bool MustExtend = false;
1406       bool HiOnly = false;
1407       bool LoOnly = false;
1408       if (Lexer.is(AsmToken::Hash)) {
1409         Lexer.Lex();
1410         MustExtend = true;
1411       } else if (ImplicitExpression)
1412         MustNotExtend = true;
1413       AsmToken const &Token = Parser.getTok();
1414       if (Token.is(AsmToken::Identifier)) {
1415         StringRef String = Token.getString();
1416         AsmToken IDToken = Token;
1417         if (String.lower() == "hi") {
1418           HiOnly = true;
1419         } else if (String.lower() == "lo") {
1420           LoOnly = true;
1421         }
1422         if (HiOnly || LoOnly) {
1423           AsmToken LParen = Lexer.peekTok();
1424           if (!LParen.is(AsmToken::LParen)) {
1425             HiOnly = false;
1426             LoOnly = false;
1427           } else {
1428             Lexer.Lex();
1429           }
1430         }
1431       }
1432       MCExpr const *Expr = nullptr;
1433       if (parseExpression(Expr))
1434         return true;
1435       int64_t Value;
1436       MCContext &Context = Parser.getContext();
1437       assert(Expr != nullptr);
1438       if (Expr->evaluateAsAbsolute(Value)) {
1439         if (HiOnly)
1440           Expr = MCBinaryExpr::createLShr(
1441               Expr,  MCConstantExpr::create(16, Context), Context);
1442         if (HiOnly || LoOnly)
1443           Expr = MCBinaryExpr::createAnd(Expr,
1444               MCConstantExpr::create(0xffff, Context),
1445                                     Context);
1446       }
1447       Expr = HexagonMCExpr::create(Expr, Context);
1448       HexagonMCInstrInfo::setMustNotExtend(*Expr, MustNotExtend);
1449       std::unique_ptr<HexagonOperand> Operand =
1450           HexagonOperand::CreateImm(Expr, ExprLoc, ExprLoc);
1451       Operand->Imm.MustExtend = MustExtend;
1452       Operands.push_back(std::move(Operand));
1453       continue;
1454     }
1455     default:
1456       break;
1457     }
1458     if (parseExpressionOrOperand(Operands))
1459       return true;
1460   }
1461 }
1462 
1463 bool HexagonAsmParser::ParseInstruction(ParseInstructionInfo &Info,
1464                                         StringRef Name,
1465                                         AsmToken ID,
1466                                         OperandVector &Operands) {
1467   getLexer().UnLex(ID);
1468   return parseInstruction(Operands);
1469 }
1470 
1471 namespace {
1472 MCInst makeCombineInst(int opCode, MCOperand &Rdd,
1473                        MCOperand &MO1, MCOperand &MO2) {
1474   MCInst TmpInst;
1475   TmpInst.setOpcode(opCode);
1476   TmpInst.addOperand(Rdd);
1477   TmpInst.addOperand(MO1);
1478   TmpInst.addOperand(MO2);
1479 
1480   return TmpInst;
1481 }
1482 }
1483 
1484 // Define this matcher function after the auto-generated include so we
1485 // have the match class enum definitions.
1486 unsigned HexagonAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
1487                                                       unsigned Kind) {
1488   HexagonOperand *Op = static_cast<HexagonOperand *>(&AsmOp);
1489 
1490   switch (Kind) {
1491   case MCK_0: {
1492     int64_t Value;
1493     return Op->isImm() && Op->Imm.Val->evaluateAsAbsolute(Value) && Value == 0
1494                ? Match_Success
1495                : Match_InvalidOperand;
1496   }
1497   case MCK_1: {
1498     int64_t Value;
1499     return Op->isImm() && Op->Imm.Val->evaluateAsAbsolute(Value) && Value == 1
1500                ? Match_Success
1501                : Match_InvalidOperand;
1502   }
1503   case MCK__MINUS_1: {
1504     int64_t Value;
1505     return Op->isImm() && Op->Imm.Val->evaluateAsAbsolute(Value) && Value == -1
1506                ? Match_Success
1507                : Match_InvalidOperand;
1508   }
1509   }
1510   if (Op->Kind == HexagonOperand::Token && Kind != InvalidMatchClass) {
1511     StringRef myStringRef = StringRef(Op->Tok.Data, Op->Tok.Length);
1512     if (matchTokenString(myStringRef.lower()) == (MatchClassKind)Kind)
1513       return Match_Success;
1514     if (matchTokenString(myStringRef.upper()) == (MatchClassKind)Kind)
1515       return Match_Success;
1516   }
1517 
1518   DEBUG(dbgs() << "Unmatched Operand:");
1519   DEBUG(Op->dump());
1520   DEBUG(dbgs() << "\n");
1521 
1522   return Match_InvalidOperand;
1523 }
1524 
1525 void HexagonAsmParser::OutOfRange(SMLoc IDLoc, long long Val, long long Max) {
1526   std::string errStr;
1527   raw_string_ostream ES(errStr);
1528   ES << "value " << Val << "(" << format_hex(Val, 0) << ") out of range: ";
1529   if (Max >= 0)
1530     ES << "0-" << Max;
1531   else
1532     ES << Max << "-" << (-Max - 1);
1533   Error(IDLoc, ES.str().c_str());
1534 }
1535 
1536 int HexagonAsmParser::processInstruction(MCInst &Inst,
1537                                          OperandVector const &Operands,
1538                                          SMLoc IDLoc, bool &MustExtend) {
1539   MCContext &Context = getParser().getContext();
1540   const MCRegisterInfo *RI = getContext().getRegisterInfo();
1541   std::string r = "r";
1542   std::string v = "v";
1543   std::string Colon = ":";
1544 
1545   bool is32bit = false; // used to distinguish between CONST32 and CONST64
1546   switch (Inst.getOpcode()) {
1547   default:
1548     break;
1549 
1550   case Hexagon::A2_iconst: {
1551     Inst.setOpcode(Hexagon::A2_addi);
1552     MCOperand Reg = Inst.getOperand(0);
1553     MCOperand S16 = Inst.getOperand(1);
1554     HexagonMCInstrInfo::setMustNotExtend(*S16.getExpr());
1555     HexagonMCInstrInfo::setS23_2_reloc(*S16.getExpr());
1556     Inst.clear();
1557     Inst.addOperand(Reg);
1558     Inst.addOperand(MCOperand::createReg(Hexagon::R0));
1559     Inst.addOperand(S16);
1560     break;
1561   }
1562   case Hexagon::M4_mpyrr_addr:
1563   case Hexagon::S4_addi_asl_ri:
1564   case Hexagon::S4_addi_lsr_ri:
1565   case Hexagon::S4_andi_asl_ri:
1566   case Hexagon::S4_andi_lsr_ri:
1567   case Hexagon::S4_ori_asl_ri:
1568   case Hexagon::S4_ori_lsr_ri:
1569   case Hexagon::S4_or_andix:
1570   case Hexagon::S4_subi_asl_ri:
1571   case Hexagon::S4_subi_lsr_ri: {
1572     MCOperand &Ry = Inst.getOperand(0);
1573     MCOperand &src = Inst.getOperand(2);
1574     if (RI->getEncodingValue(Ry.getReg()) != RI->getEncodingValue(src.getReg()))
1575       return Match_InvalidOperand;
1576     break;
1577   }
1578 
1579   case Hexagon::C2_cmpgei: {
1580     MCOperand &MO = Inst.getOperand(2);
1581     MO.setExpr(HexagonMCExpr::create(MCBinaryExpr::createSub(
1582         MO.getExpr(), MCConstantExpr::create(1, Context), Context), Context));
1583     Inst.setOpcode(Hexagon::C2_cmpgti);
1584     break;
1585   }
1586 
1587   case Hexagon::C2_cmpgeui: {
1588     MCOperand &MO = Inst.getOperand(2);
1589     int64_t Value;
1590     bool Success = MO.getExpr()->evaluateAsAbsolute(Value);
1591     (void)Success;
1592     assert(Success && "Assured by matcher");
1593     if (Value == 0) {
1594       MCInst TmpInst;
1595       MCOperand &Pd = Inst.getOperand(0);
1596       MCOperand &Rt = Inst.getOperand(1);
1597       TmpInst.setOpcode(Hexagon::C2_cmpeq);
1598       TmpInst.addOperand(Pd);
1599       TmpInst.addOperand(Rt);
1600       TmpInst.addOperand(Rt);
1601       Inst = TmpInst;
1602     } else {
1603       MO.setExpr(HexagonMCExpr::create(MCBinaryExpr::createSub(
1604           MO.getExpr(), MCConstantExpr::create(1, Context), Context), Context));
1605       Inst.setOpcode(Hexagon::C2_cmpgtui);
1606     }
1607     break;
1608   }
1609 
1610   // Translate a "$Rdd = $Rss" to "$Rdd = combine($Rs, $Rt)"
1611   case Hexagon::A2_tfrp: {
1612     MCOperand &MO = Inst.getOperand(1);
1613     unsigned int RegPairNum = RI->getEncodingValue(MO.getReg());
1614     std::string R1 = r + llvm::utostr(RegPairNum + 1);
1615     StringRef Reg1(R1);
1616     MO.setReg(MatchRegisterName(Reg1));
1617     // Add a new operand for the second register in the pair.
1618     std::string R2 = r + llvm::utostr(RegPairNum);
1619     StringRef Reg2(R2);
1620     Inst.addOperand(MCOperand::createReg(MatchRegisterName(Reg2)));
1621     Inst.setOpcode(Hexagon::A2_combinew);
1622     break;
1623   }
1624 
1625   case Hexagon::A2_tfrpt:
1626   case Hexagon::A2_tfrpf: {
1627     MCOperand &MO = Inst.getOperand(2);
1628     unsigned int RegPairNum = RI->getEncodingValue(MO.getReg());
1629     std::string R1 = r + llvm::utostr(RegPairNum + 1);
1630     StringRef Reg1(R1);
1631     MO.setReg(MatchRegisterName(Reg1));
1632     // Add a new operand for the second register in the pair.
1633     std::string R2 = r + llvm::utostr(RegPairNum);
1634     StringRef Reg2(R2);
1635     Inst.addOperand(MCOperand::createReg(MatchRegisterName(Reg2)));
1636     Inst.setOpcode((Inst.getOpcode() == Hexagon::A2_tfrpt)
1637                        ? Hexagon::C2_ccombinewt
1638                        : Hexagon::C2_ccombinewf);
1639     break;
1640   }
1641   case Hexagon::A2_tfrptnew:
1642   case Hexagon::A2_tfrpfnew: {
1643     MCOperand &MO = Inst.getOperand(2);
1644     unsigned int RegPairNum = RI->getEncodingValue(MO.getReg());
1645     std::string R1 = r + llvm::utostr(RegPairNum + 1);
1646     StringRef Reg1(R1);
1647     MO.setReg(MatchRegisterName(Reg1));
1648     // Add a new operand for the second register in the pair.
1649     std::string R2 = r + llvm::utostr(RegPairNum);
1650     StringRef Reg2(R2);
1651     Inst.addOperand(MCOperand::createReg(MatchRegisterName(Reg2)));
1652     Inst.setOpcode((Inst.getOpcode() == Hexagon::A2_tfrptnew)
1653                        ? Hexagon::C2_ccombinewnewt
1654                        : Hexagon::C2_ccombinewnewf);
1655     break;
1656   }
1657 
1658   // Translate a "$Rx =  CONST32(#imm)" to "$Rx = memw(gp+#LABEL) "
1659   case Hexagon::CONST32:
1660   case Hexagon::CONST32_Float_Real:
1661   case Hexagon::CONST32_Int_Real:
1662   case Hexagon::FCONST32_nsdata:
1663     is32bit = true;
1664   // Translate a "$Rx:y =  CONST64(#imm)" to "$Rx:y = memd(gp+#LABEL) "
1665   case Hexagon::CONST64_Float_Real:
1666   case Hexagon::CONST64_Int_Real:
1667 
1668     // FIXME: need better way to detect AsmStreamer (upstream removed getKind())
1669     if (!Parser.getStreamer().hasRawTextSupport()) {
1670       MCELFStreamer *MES = static_cast<MCELFStreamer *>(&Parser.getStreamer());
1671       MCOperand &MO_1 = Inst.getOperand(1);
1672       MCOperand &MO_0 = Inst.getOperand(0);
1673 
1674       // push section onto section stack
1675       MES->PushSection();
1676 
1677       std::string myCharStr;
1678       MCSectionELF *mySection;
1679 
1680       // check if this as an immediate or a symbol
1681       int64_t Value;
1682       bool Absolute = MO_1.getExpr()->evaluateAsAbsolute(Value);
1683       if (Absolute) {
1684         // Create a new section - one for each constant
1685         // Some or all of the zeros are replaced with the given immediate.
1686         if (is32bit) {
1687           std::string myImmStr = utohexstr(static_cast<uint32_t>(Value));
1688           myCharStr = StringRef(".gnu.linkonce.l4.CONST_00000000")
1689                           .drop_back(myImmStr.size())
1690                           .str() +
1691                       myImmStr;
1692         } else {
1693           std::string myImmStr = utohexstr(Value);
1694           myCharStr = StringRef(".gnu.linkonce.l8.CONST_0000000000000000")
1695                           .drop_back(myImmStr.size())
1696                           .str() +
1697                       myImmStr;
1698         }
1699 
1700         mySection = getContext().getELFSection(myCharStr, ELF::SHT_PROGBITS,
1701                                                ELF::SHF_ALLOC | ELF::SHF_WRITE);
1702       } else if (MO_1.isExpr()) {
1703         // .lita - for expressions
1704         myCharStr = ".lita";
1705         mySection = getContext().getELFSection(myCharStr, ELF::SHT_PROGBITS,
1706                                                ELF::SHF_ALLOC | ELF::SHF_WRITE);
1707       } else
1708         llvm_unreachable("unexpected type of machine operand!");
1709 
1710       MES->SwitchSection(mySection);
1711       unsigned byteSize = is32bit ? 4 : 8;
1712       getStreamer().EmitCodeAlignment(byteSize, byteSize);
1713 
1714       MCSymbol *Sym;
1715 
1716       // for symbols, get rid of prepended ".gnu.linkonce.lx."
1717 
1718       // emit symbol if needed
1719       if (Absolute) {
1720         Sym = getContext().getOrCreateSymbol(StringRef(myCharStr.c_str() + 16));
1721         if (Sym->isUndefined()) {
1722           getStreamer().EmitLabel(Sym);
1723           getStreamer().EmitSymbolAttribute(Sym, MCSA_Global);
1724           getStreamer().EmitIntValue(Value, byteSize);
1725         }
1726       } else if (MO_1.isExpr()) {
1727         const char *StringStart = 0;
1728         const char *StringEnd = 0;
1729         if (*Operands[4]->getStartLoc().getPointer() == '#') {
1730           StringStart = Operands[5]->getStartLoc().getPointer();
1731           StringEnd = Operands[6]->getStartLoc().getPointer();
1732         } else { // no pound
1733           StringStart = Operands[4]->getStartLoc().getPointer();
1734           StringEnd = Operands[5]->getStartLoc().getPointer();
1735         }
1736 
1737         unsigned size = StringEnd - StringStart;
1738         std::string DotConst = ".CONST_";
1739         Sym = getContext().getOrCreateSymbol(DotConst +
1740                                              StringRef(StringStart, size));
1741 
1742         if (Sym->isUndefined()) {
1743           // case where symbol is not yet defined: emit symbol
1744           getStreamer().EmitLabel(Sym);
1745           getStreamer().EmitSymbolAttribute(Sym, MCSA_Local);
1746           getStreamer().EmitValue(MO_1.getExpr(), 4);
1747         }
1748       } else
1749         llvm_unreachable("unexpected type of machine operand!");
1750 
1751       MES->PopSection();
1752 
1753       if (Sym) {
1754         MCInst TmpInst;
1755         if (is32bit) // 32 bit
1756           TmpInst.setOpcode(Hexagon::L2_loadrigp);
1757         else // 64 bit
1758           TmpInst.setOpcode(Hexagon::L2_loadrdgp);
1759 
1760         TmpInst.addOperand(MO_0);
1761         TmpInst.addOperand(
1762             MCOperand::createExpr(MCSymbolRefExpr::create(Sym, getContext())));
1763         Inst = TmpInst;
1764       }
1765     }
1766     break;
1767 
1768   // Translate a "$Rdd = #-imm" to "$Rdd = combine(#[-1,0], #-imm)"
1769   case Hexagon::A2_tfrpi: {
1770     MCOperand &Rdd = Inst.getOperand(0);
1771     MCOperand &MO = Inst.getOperand(1);
1772     int64_t Value;
1773     int sVal = (MO.getExpr()->evaluateAsAbsolute(Value) && Value < 0) ? -1 : 0;
1774     MCOperand imm(MCOperand::createExpr(
1775         HexagonMCExpr::create(MCConstantExpr::create(sVal, Context), Context)));
1776     Inst = makeCombineInst(Hexagon::A2_combineii, Rdd, imm, MO);
1777     break;
1778   }
1779 
1780   // Translate a "$Rdd = [#]#imm" to "$Rdd = combine(#, [#]#imm)"
1781   case Hexagon::TFRI64_V4: {
1782     MCOperand &Rdd = Inst.getOperand(0);
1783     MCOperand &MO = Inst.getOperand(1);
1784     int64_t Value;
1785     if (MO.getExpr()->evaluateAsAbsolute(Value)) {
1786       unsigned long long u64 = Value;
1787       signed int s8 = (u64 >> 32) & 0xFFFFFFFF;
1788       if (s8 < -128 || s8 > 127)
1789         OutOfRange(IDLoc, s8, -128);
1790       MCOperand imm(MCOperand::createExpr(HexagonMCExpr::create(
1791           MCConstantExpr::create(s8, Context), Context))); // upper 32
1792       MCOperand imm2(MCOperand::createExpr(HexagonMCExpr::create(
1793           MCConstantExpr::create(u64 & 0xFFFFFFFF, Context),
1794           Context))); // lower 32
1795       Inst = makeCombineInst(Hexagon::A4_combineii, Rdd, imm, imm2);
1796     } else {
1797       MCOperand imm(MCOperand::createExpr(HexagonMCExpr::create(
1798           MCConstantExpr::create(0, Context), Context))); // upper 32
1799       Inst = makeCombineInst(Hexagon::A4_combineii, Rdd, imm, MO);
1800     }
1801     break;
1802   }
1803 
1804   // Handle $Rdd = combine(##imm, #imm)"
1805   case Hexagon::TFRI64_V2_ext: {
1806     MCOperand &Rdd = Inst.getOperand(0);
1807     MCOperand &MO1 = Inst.getOperand(1);
1808     MCOperand &MO2 = Inst.getOperand(2);
1809     int64_t Value;
1810     if (MO2.getExpr()->evaluateAsAbsolute(Value)) {
1811       int s8 = Value;
1812       if (s8 < -128 || s8 > 127)
1813         OutOfRange(IDLoc, s8, -128);
1814     }
1815     Inst = makeCombineInst(Hexagon::A2_combineii, Rdd, MO1, MO2);
1816     break;
1817   }
1818 
1819   // Handle $Rdd = combine(#imm, ##imm)"
1820   case Hexagon::A4_combineii: {
1821     MCOperand &Rdd = Inst.getOperand(0);
1822     MCOperand &MO1 = Inst.getOperand(1);
1823     int64_t Value;
1824     if (MO1.getExpr()->evaluateAsAbsolute(Value)) {
1825       int s8 = Value;
1826       if (s8 < -128 || s8 > 127)
1827         OutOfRange(IDLoc, s8, -128);
1828     }
1829     MCOperand &MO2 = Inst.getOperand(2);
1830     Inst = makeCombineInst(Hexagon::A4_combineii, Rdd, MO1, MO2);
1831     break;
1832   }
1833 
1834   case Hexagon::S2_tableidxb_goodsyntax: {
1835     Inst.setOpcode(Hexagon::S2_tableidxb);
1836     break;
1837   }
1838 
1839   case Hexagon::S2_tableidxh_goodsyntax: {
1840     MCInst TmpInst;
1841     MCOperand &Rx = Inst.getOperand(0);
1842     MCOperand &_dst_ = Inst.getOperand(1);
1843     MCOperand &Rs = Inst.getOperand(2);
1844     MCOperand &Imm4 = Inst.getOperand(3);
1845     MCOperand &Imm6 = Inst.getOperand(4);
1846     Imm6.setExpr(HexagonMCExpr::create(MCBinaryExpr::createSub(
1847         Imm6.getExpr(), MCConstantExpr::create(1, Context), Context), Context));
1848     TmpInst.setOpcode(Hexagon::S2_tableidxh);
1849     TmpInst.addOperand(Rx);
1850     TmpInst.addOperand(_dst_);
1851     TmpInst.addOperand(Rs);
1852     TmpInst.addOperand(Imm4);
1853     TmpInst.addOperand(Imm6);
1854     Inst = TmpInst;
1855     break;
1856   }
1857 
1858   case Hexagon::S2_tableidxw_goodsyntax: {
1859     MCInst TmpInst;
1860     MCOperand &Rx = Inst.getOperand(0);
1861     MCOperand &_dst_ = Inst.getOperand(1);
1862     MCOperand &Rs = Inst.getOperand(2);
1863     MCOperand &Imm4 = Inst.getOperand(3);
1864     MCOperand &Imm6 = Inst.getOperand(4);
1865     Imm6.setExpr(HexagonMCExpr::create(MCBinaryExpr::createSub(
1866         Imm6.getExpr(), MCConstantExpr::create(2, Context), Context), Context));
1867     TmpInst.setOpcode(Hexagon::S2_tableidxw);
1868     TmpInst.addOperand(Rx);
1869     TmpInst.addOperand(_dst_);
1870     TmpInst.addOperand(Rs);
1871     TmpInst.addOperand(Imm4);
1872     TmpInst.addOperand(Imm6);
1873     Inst = TmpInst;
1874     break;
1875   }
1876 
1877   case Hexagon::S2_tableidxd_goodsyntax: {
1878     MCInst TmpInst;
1879     MCOperand &Rx = Inst.getOperand(0);
1880     MCOperand &_dst_ = Inst.getOperand(1);
1881     MCOperand &Rs = Inst.getOperand(2);
1882     MCOperand &Imm4 = Inst.getOperand(3);
1883     MCOperand &Imm6 = Inst.getOperand(4);
1884     Imm6.setExpr(HexagonMCExpr::create(MCBinaryExpr::createSub(
1885         Imm6.getExpr(), MCConstantExpr::create(3, Context), Context), Context));
1886     TmpInst.setOpcode(Hexagon::S2_tableidxd);
1887     TmpInst.addOperand(Rx);
1888     TmpInst.addOperand(_dst_);
1889     TmpInst.addOperand(Rs);
1890     TmpInst.addOperand(Imm4);
1891     TmpInst.addOperand(Imm6);
1892     Inst = TmpInst;
1893     break;
1894   }
1895 
1896   case Hexagon::M2_mpyui: {
1897     Inst.setOpcode(Hexagon::M2_mpyi);
1898     break;
1899   }
1900   case Hexagon::M2_mpysmi: {
1901     MCInst TmpInst;
1902     MCOperand &Rd = Inst.getOperand(0);
1903     MCOperand &Rs = Inst.getOperand(1);
1904     MCOperand &Imm = Inst.getOperand(2);
1905     int64_t Value;
1906     bool Absolute = Imm.getExpr()->evaluateAsAbsolute(Value);
1907     assert(Absolute);
1908     (void)Absolute;
1909     if (!MustExtend) {
1910       if (Value < 0 && Value > -256) {
1911         Imm.setExpr(HexagonMCExpr::create(
1912             MCConstantExpr::create(Value * -1, Context), Context));
1913         TmpInst.setOpcode(Hexagon::M2_mpysin);
1914       } else if (Value < 256 && Value >= 0)
1915         TmpInst.setOpcode(Hexagon::M2_mpysip);
1916       else
1917         return Match_InvalidOperand;
1918     } else {
1919       if (Value >= 0)
1920         TmpInst.setOpcode(Hexagon::M2_mpysip);
1921       else
1922         return Match_InvalidOperand;
1923     }
1924     TmpInst.addOperand(Rd);
1925     TmpInst.addOperand(Rs);
1926     TmpInst.addOperand(Imm);
1927     Inst = TmpInst;
1928     break;
1929   }
1930 
1931   case Hexagon::S2_asr_i_r_rnd_goodsyntax: {
1932     MCOperand &Imm = Inst.getOperand(2);
1933     MCInst TmpInst;
1934     int64_t Value;
1935     bool Absolute = Imm.getExpr()->evaluateAsAbsolute(Value);
1936     assert(Absolute);
1937     (void)Absolute;
1938     if (Value == 0) { // convert to $Rd = $Rs
1939       TmpInst.setOpcode(Hexagon::A2_tfr);
1940       MCOperand &Rd = Inst.getOperand(0);
1941       MCOperand &Rs = Inst.getOperand(1);
1942       TmpInst.addOperand(Rd);
1943       TmpInst.addOperand(Rs);
1944     } else {
1945       Imm.setExpr(HexagonMCExpr::create(
1946           MCBinaryExpr::createSub(Imm.getExpr(),
1947                                   MCConstantExpr::create(1, Context), Context),
1948           Context));
1949       TmpInst.setOpcode(Hexagon::S2_asr_i_r_rnd);
1950       MCOperand &Rd = Inst.getOperand(0);
1951       MCOperand &Rs = Inst.getOperand(1);
1952       TmpInst.addOperand(Rd);
1953       TmpInst.addOperand(Rs);
1954       TmpInst.addOperand(Imm);
1955     }
1956     Inst = TmpInst;
1957     break;
1958   }
1959 
1960   case Hexagon::S2_asr_i_p_rnd_goodsyntax: {
1961     MCOperand &Rdd = Inst.getOperand(0);
1962     MCOperand &Rss = Inst.getOperand(1);
1963     MCOperand &Imm = Inst.getOperand(2);
1964     int64_t Value;
1965     bool Absolute = Imm.getExpr()->evaluateAsAbsolute(Value);
1966     assert(Absolute);
1967     (void)Absolute;
1968     if (Value == 0) { // convert to $Rdd = combine ($Rs[0], $Rs[1])
1969       MCInst TmpInst;
1970       unsigned int RegPairNum = RI->getEncodingValue(Rss.getReg());
1971       std::string R1 = r + llvm::utostr(RegPairNum + 1);
1972       StringRef Reg1(R1);
1973       Rss.setReg(MatchRegisterName(Reg1));
1974       // Add a new operand for the second register in the pair.
1975       std::string R2 = r + llvm::utostr(RegPairNum);
1976       StringRef Reg2(R2);
1977       TmpInst.setOpcode(Hexagon::A2_combinew);
1978       TmpInst.addOperand(Rdd);
1979       TmpInst.addOperand(Rss);
1980       TmpInst.addOperand(MCOperand::createReg(MatchRegisterName(Reg2)));
1981       Inst = TmpInst;
1982     } else {
1983       Imm.setExpr(HexagonMCExpr::create(
1984           MCBinaryExpr::createSub(Imm.getExpr(),
1985                                   MCConstantExpr::create(1, Context), Context),
1986           Context));
1987       Inst.setOpcode(Hexagon::S2_asr_i_p_rnd);
1988     }
1989     break;
1990   }
1991 
1992   case Hexagon::A4_boundscheck: {
1993     MCOperand &Rs = Inst.getOperand(1);
1994     unsigned int RegNum = RI->getEncodingValue(Rs.getReg());
1995     if (RegNum & 1) { // Odd mapped to raw:hi, regpair is rodd:odd-1, like r3:2
1996       Inst.setOpcode(Hexagon::A4_boundscheck_hi);
1997       std::string Name =
1998           r + llvm::utostr(RegNum) + Colon + llvm::utostr(RegNum - 1);
1999       StringRef RegPair = Name;
2000       Rs.setReg(MatchRegisterName(RegPair));
2001     } else { // raw:lo
2002       Inst.setOpcode(Hexagon::A4_boundscheck_lo);
2003       std::string Name =
2004           r + llvm::utostr(RegNum + 1) + Colon + llvm::utostr(RegNum);
2005       StringRef RegPair = Name;
2006       Rs.setReg(MatchRegisterName(RegPair));
2007     }
2008     break;
2009   }
2010 
2011   case Hexagon::A2_addsp: {
2012     MCOperand &Rs = Inst.getOperand(1);
2013     unsigned int RegNum = RI->getEncodingValue(Rs.getReg());
2014     if (RegNum & 1) { // Odd mapped to raw:hi
2015       Inst.setOpcode(Hexagon::A2_addsph);
2016       std::string Name =
2017           r + llvm::utostr(RegNum) + Colon + llvm::utostr(RegNum - 1);
2018       StringRef RegPair = Name;
2019       Rs.setReg(MatchRegisterName(RegPair));
2020     } else { // Even mapped raw:lo
2021       Inst.setOpcode(Hexagon::A2_addspl);
2022       std::string Name =
2023           r + llvm::utostr(RegNum + 1) + Colon + llvm::utostr(RegNum);
2024       StringRef RegPair = Name;
2025       Rs.setReg(MatchRegisterName(RegPair));
2026     }
2027     break;
2028   }
2029 
2030   case Hexagon::M2_vrcmpys_s1: {
2031     MCOperand &Rt = Inst.getOperand(2);
2032     unsigned int RegNum = RI->getEncodingValue(Rt.getReg());
2033     if (RegNum & 1) { // Odd mapped to sat:raw:hi
2034       Inst.setOpcode(Hexagon::M2_vrcmpys_s1_h);
2035       std::string Name =
2036           r + llvm::utostr(RegNum) + Colon + llvm::utostr(RegNum - 1);
2037       StringRef RegPair = Name;
2038       Rt.setReg(MatchRegisterName(RegPair));
2039     } else { // Even mapped sat:raw:lo
2040       Inst.setOpcode(Hexagon::M2_vrcmpys_s1_l);
2041       std::string Name =
2042           r + llvm::utostr(RegNum + 1) + Colon + llvm::utostr(RegNum);
2043       StringRef RegPair = Name;
2044       Rt.setReg(MatchRegisterName(RegPair));
2045     }
2046     break;
2047   }
2048 
2049   case Hexagon::M2_vrcmpys_acc_s1: {
2050     MCInst TmpInst;
2051     MCOperand &Rxx = Inst.getOperand(0);
2052     MCOperand &Rss = Inst.getOperand(2);
2053     MCOperand &Rt = Inst.getOperand(3);
2054     unsigned int RegNum = RI->getEncodingValue(Rt.getReg());
2055     if (RegNum & 1) { // Odd mapped to sat:raw:hi
2056       TmpInst.setOpcode(Hexagon::M2_vrcmpys_acc_s1_h);
2057       std::string Name =
2058           r + llvm::utostr(RegNum) + Colon + llvm::utostr(RegNum - 1);
2059       StringRef RegPair = Name;
2060       Rt.setReg(MatchRegisterName(RegPair));
2061     } else { // Even mapped sat:raw:lo
2062       TmpInst.setOpcode(Hexagon::M2_vrcmpys_acc_s1_l);
2063       std::string Name =
2064           r + llvm::utostr(RegNum + 1) + Colon + llvm::utostr(RegNum);
2065       StringRef RegPair = Name;
2066       Rt.setReg(MatchRegisterName(RegPair));
2067     }
2068     // Registers are in different positions
2069     TmpInst.addOperand(Rxx);
2070     TmpInst.addOperand(Rxx);
2071     TmpInst.addOperand(Rss);
2072     TmpInst.addOperand(Rt);
2073     Inst = TmpInst;
2074     break;
2075   }
2076 
2077   case Hexagon::M2_vrcmpys_s1rp: {
2078     MCOperand &Rt = Inst.getOperand(2);
2079     unsigned int RegNum = RI->getEncodingValue(Rt.getReg());
2080     if (RegNum & 1) { // Odd mapped to rnd:sat:raw:hi
2081       Inst.setOpcode(Hexagon::M2_vrcmpys_s1rp_h);
2082       std::string Name =
2083           r + llvm::utostr(RegNum) + Colon + llvm::utostr(RegNum - 1);
2084       StringRef RegPair = Name;
2085       Rt.setReg(MatchRegisterName(RegPair));
2086     } else { // Even mapped rnd:sat:raw:lo
2087       Inst.setOpcode(Hexagon::M2_vrcmpys_s1rp_l);
2088       std::string Name =
2089           r + llvm::utostr(RegNum + 1) + Colon + llvm::utostr(RegNum);
2090       StringRef RegPair = Name;
2091       Rt.setReg(MatchRegisterName(RegPair));
2092     }
2093     break;
2094   }
2095 
2096   case Hexagon::S5_asrhub_rnd_sat_goodsyntax: {
2097     MCOperand &Imm = Inst.getOperand(2);
2098     int64_t Value;
2099     bool Absolute = Imm.getExpr()->evaluateAsAbsolute(Value);
2100     assert(Absolute);
2101     (void)Absolute;
2102     if (Value == 0)
2103       Inst.setOpcode(Hexagon::S2_vsathub);
2104     else {
2105       Imm.setExpr(HexagonMCExpr::create(
2106           MCBinaryExpr::createSub(Imm.getExpr(),
2107                                   MCConstantExpr::create(1, Context), Context),
2108           Context));
2109       Inst.setOpcode(Hexagon::S5_asrhub_rnd_sat);
2110     }
2111     break;
2112   }
2113 
2114   case Hexagon::S5_vasrhrnd_goodsyntax: {
2115     MCOperand &Rdd = Inst.getOperand(0);
2116     MCOperand &Rss = Inst.getOperand(1);
2117     MCOperand &Imm = Inst.getOperand(2);
2118     int64_t Value;
2119     bool Absolute = Imm.getExpr()->evaluateAsAbsolute(Value);
2120     assert(Absolute);
2121     (void)Absolute;
2122     if (Value == 0) {
2123       MCInst TmpInst;
2124       unsigned int RegPairNum = RI->getEncodingValue(Rss.getReg());
2125       std::string R1 = r + llvm::utostr(RegPairNum + 1);
2126       StringRef Reg1(R1);
2127       Rss.setReg(MatchRegisterName(Reg1));
2128       // Add a new operand for the second register in the pair.
2129       std::string R2 = r + llvm::utostr(RegPairNum);
2130       StringRef Reg2(R2);
2131       TmpInst.setOpcode(Hexagon::A2_combinew);
2132       TmpInst.addOperand(Rdd);
2133       TmpInst.addOperand(Rss);
2134       TmpInst.addOperand(MCOperand::createReg(MatchRegisterName(Reg2)));
2135       Inst = TmpInst;
2136     } else {
2137       Imm.setExpr(HexagonMCExpr::create(
2138           MCBinaryExpr::createSub(Imm.getExpr(),
2139                                   MCConstantExpr::create(1, Context), Context),
2140           Context));
2141       Inst.setOpcode(Hexagon::S5_vasrhrnd);
2142     }
2143     break;
2144   }
2145 
2146   case Hexagon::A2_not: {
2147     MCInst TmpInst;
2148     MCOperand &Rd = Inst.getOperand(0);
2149     MCOperand &Rs = Inst.getOperand(1);
2150     TmpInst.setOpcode(Hexagon::A2_subri);
2151     TmpInst.addOperand(Rd);
2152     TmpInst.addOperand(MCOperand::createExpr(
2153         HexagonMCExpr::create(MCConstantExpr::create(-1, Context), Context)));
2154     TmpInst.addOperand(Rs);
2155     Inst = TmpInst;
2156     break;
2157   }
2158   } // switch
2159 
2160   return Match_Success;
2161 }
2162