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