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