xref: /llvm-project/llvm/lib/Target/Hexagon/MCTargetDesc/HexagonMCChecker.cpp (revision b17f036a99eba19194b81a6d56e7f08fa5e0e92c)
1 //===----- HexagonMCChecker.cpp - Instruction bundle checking -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements the checking of insns inside a bundle according to the
10 // packet constraint rules of the Hexagon ISA.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "MCTargetDesc/HexagonMCChecker.h"
15 #include "MCTargetDesc/HexagonBaseInfo.h"
16 #include "MCTargetDesc/HexagonMCInstrInfo.h"
17 #include "MCTargetDesc/HexagonMCShuffler.h"
18 #include "MCTargetDesc/HexagonMCTargetDesc.h"
19 
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCInst.h"
23 #include "llvm/MC/MCInstrDesc.h"
24 #include "llvm/MC/MCRegisterInfo.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include <cassert>
28 
29 using namespace llvm;
30 
31 static cl::opt<bool>
32     RelaxNVChecks("relax-nv-checks", cl::init(false), cl::ZeroOrMore,
33                   cl::Hidden, cl::desc("Relax checks of new-value validity"));
34 
35 const HexagonMCChecker::PredSense
36     HexagonMCChecker::Unconditional(Hexagon::NoRegister, false);
37 
38 void HexagonMCChecker::init() {
39   // Initialize read-only registers set.
40   ReadOnly.insert(Hexagon::PC);
41   ReadOnly.insert(Hexagon::C9_8);
42 
43   // Figure out the loop-registers definitions.
44   if (HexagonMCInstrInfo::isInnerLoop(MCB)) {
45     Defs[Hexagon::SA0].insert(Unconditional); // FIXME: define or change SA0?
46     Defs[Hexagon::LC0].insert(Unconditional);
47   }
48   if (HexagonMCInstrInfo::isOuterLoop(MCB)) {
49     Defs[Hexagon::SA1].insert(Unconditional); // FIXME: define or change SA0?
50     Defs[Hexagon::LC1].insert(Unconditional);
51   }
52 
53   if (HexagonMCInstrInfo::isBundle(MCB))
54     // Unfurl a bundle.
55     for (auto const &I : HexagonMCInstrInfo::bundleInstructions(MCB)) {
56       MCInst const &Inst = *I.getInst();
57       if (HexagonMCInstrInfo::isDuplex(MCII, Inst)) {
58         init(*Inst.getOperand(0).getInst());
59         init(*Inst.getOperand(1).getInst());
60       } else
61         init(Inst);
62     }
63   else
64     init(MCB);
65 }
66 
67 void HexagonMCChecker::initReg(MCInst const &MCI, unsigned R, unsigned &PredReg,
68                                bool &isTrue) {
69   if (HexagonMCInstrInfo::isPredicated(MCII, MCI) &&
70       HexagonMCInstrInfo::isPredReg(RI, R)) {
71     // Note an used predicate register.
72     PredReg = R;
73     isTrue = HexagonMCInstrInfo::isPredicatedTrue(MCII, MCI);
74 
75     // Note use of new predicate register.
76     if (HexagonMCInstrInfo::isPredicatedNew(MCII, MCI))
77       NewPreds.insert(PredReg);
78   } else
79     // Note register use.  Super-registers are not tracked directly,
80     // but their components.
81     for (MCRegAliasIterator SRI(R, &RI, !MCSubRegIterator(R, &RI).isValid());
82          SRI.isValid(); ++SRI)
83       if (!MCSubRegIterator(*SRI, &RI).isValid())
84         // Skip super-registers used indirectly.
85         Uses.insert(*SRI);
86 
87   if (HexagonMCInstrInfo::IsReverseVecRegPair(R))
88     ReversePairs.insert(R);
89 }
90 
91 void HexagonMCChecker::init(MCInst const &MCI) {
92   const MCInstrDesc &MCID = HexagonMCInstrInfo::getDesc(MCII, MCI);
93   unsigned PredReg = Hexagon::NoRegister;
94   bool isTrue = false;
95 
96   // Get used registers.
97   for (unsigned i = MCID.getNumDefs(); i < MCID.getNumOperands(); ++i)
98     if (MCI.getOperand(i).isReg())
99       initReg(MCI, MCI.getOperand(i).getReg(), PredReg, isTrue);
100   for (unsigned i = 0; i < MCID.getNumImplicitUses(); ++i)
101     initReg(MCI, MCID.getImplicitUses()[i], PredReg, isTrue);
102 
103   const bool IgnoreTmpDst = (HexagonMCInstrInfo::hasTmpDst(MCII, MCI) ||
104                              HexagonMCInstrInfo::hasHvxTmp(MCII, MCI)) &&
105                             STI.getFeatureBits()[Hexagon::ArchV69];
106 
107   // Get implicit register definitions.
108   if (const MCPhysReg *ImpDef = MCID.getImplicitDefs())
109     for (; *ImpDef; ++ImpDef) {
110       unsigned R = *ImpDef;
111 
112       if (Hexagon::R31 != R && MCID.isCall())
113         // Any register other than the LR and the PC are actually volatile ones
114         // as defined by the ABI, not modified implicitly by the call insn.
115         continue;
116       if (Hexagon::PC == R)
117         // Branches are the only insns that can change the PC,
118         // otherwise a read-only register.
119         continue;
120 
121       if (Hexagon::USR_OVF == R)
122         // Many insns change the USR implicitly, but only one or another flag.
123         // The instruction table models the USR.OVF flag, which can be
124         // implicitly modified more than once, but cannot be modified in the
125         // same packet with an instruction that modifies is explicitly. Deal
126         // with such situations individually.
127         SoftDefs.insert(R);
128       else if (HexagonMCInstrInfo::isPredReg(RI, R) &&
129                HexagonMCInstrInfo::isPredicateLate(MCII, MCI))
130         // Include implicit late predicates.
131         LatePreds.insert(R);
132       else if (!IgnoreTmpDst)
133         Defs[R].insert(PredSense(PredReg, isTrue));
134     }
135 
136   // Figure out explicit register definitions.
137   for (unsigned i = 0; i < MCID.getNumDefs(); ++i) {
138     unsigned R = MCI.getOperand(i).getReg(), S = Hexagon::NoRegister;
139     // USR has subregisters (while C8 does not for technical reasons), so
140     // reset R to USR, since we know how to handle multiple defs of USR,
141     // taking into account its subregisters.
142     if (R == Hexagon::C8)
143       R = Hexagon::USR;
144 
145     if (HexagonMCInstrInfo::IsReverseVecRegPair(R))
146       ReversePairs.insert(R);
147 
148     // Note register definitions, direct ones as well as indirect side-effects.
149     // Super-registers are not tracked directly, but their components.
150     for (MCRegAliasIterator SRI(R, &RI, !MCSubRegIterator(R, &RI).isValid());
151          SRI.isValid(); ++SRI) {
152       if (MCSubRegIterator(*SRI, &RI).isValid())
153         // Skip super-registers defined indirectly.
154         continue;
155 
156       if (R == *SRI) {
157         if (S == R)
158           // Avoid scoring the defined register multiple times.
159           continue;
160         else
161           // Note that the defined register has already been scored.
162           S = R;
163       }
164 
165       if (Hexagon::P3_0 != R && Hexagon::P3_0 == *SRI)
166         // P3:0 is a special case, since multiple predicate register definitions
167         // in a packet is allowed as the equivalent of their logical "and".
168         // Only an explicit definition of P3:0 is noted as such; if a
169         // side-effect, then note as a soft definition.
170         SoftDefs.insert(*SRI);
171       else if (HexagonMCInstrInfo::isPredicateLate(MCII, MCI) &&
172                HexagonMCInstrInfo::isPredReg(RI, *SRI))
173         // Some insns produce predicates too late to be used in the same packet.
174         LatePreds.insert(*SRI);
175       else if (i == 0 && HexagonMCInstrInfo::getType(MCII, MCI) ==
176                              HexagonII::TypeCVI_VM_TMP_LD)
177         // Temporary loads should be used in the same packet, but don't commit
178         // results, so it should be disregarded if another insn changes the same
179         // register.
180         // TODO: relies on the impossibility of a current and a temporary loads
181         // in the same packet.
182         TmpDefs.insert(*SRI);
183       else if (i <= 1 && HexagonMCInstrInfo::hasNewValue2(MCII, MCI))
184         // vshuff(Vx, Vy, Rx) <- Vx(0) and Vy(1) are both source and
185         // destination registers with this instruction. same for vdeal(Vx,Vy,Rx)
186         Uses.insert(*SRI);
187       else if (!IgnoreTmpDst)
188         Defs[*SRI].insert(PredSense(PredReg, isTrue));
189     }
190   }
191 
192   // Figure out definitions of new predicate registers.
193   if (HexagonMCInstrInfo::isPredicatedNew(MCII, MCI))
194     for (unsigned i = MCID.getNumDefs(); i < MCID.getNumOperands(); ++i)
195       if (MCI.getOperand(i).isReg()) {
196         unsigned P = MCI.getOperand(i).getReg();
197 
198         if (HexagonMCInstrInfo::isPredReg(RI, P))
199           NewPreds.insert(P);
200       }
201 }
202 
203 HexagonMCChecker::HexagonMCChecker(MCContext &Context, MCInstrInfo const &MCII,
204                                    MCSubtargetInfo const &STI, MCInst &mcb,
205                                    MCRegisterInfo const &ri, bool ReportErrors)
206     : Context(Context), MCB(mcb), RI(ri), MCII(MCII), STI(STI),
207       ReportErrors(ReportErrors), ReversePairs() {
208   init();
209 }
210 
211 HexagonMCChecker::HexagonMCChecker(HexagonMCChecker const &Other,
212                                    MCSubtargetInfo const &STI,
213                                    bool CopyReportErrors)
214     : Context(Other.Context), MCB(Other.MCB), RI(Other.RI), MCII(Other.MCII),
215       STI(STI), ReportErrors(CopyReportErrors ? Other.ReportErrors : false),
216       ReversePairs() {
217   init();
218 }
219 
220 bool HexagonMCChecker::check(bool FullCheck) {
221   bool chkP = checkPredicates();
222   bool chkNV = checkNewValues();
223   bool chkR = checkRegisters();
224   bool chkRRO = checkRegistersReadOnly();
225   checkRegisterCurDefs();
226   bool chkS = checkSolo();
227   bool chkSh = true;
228   if (FullCheck)
229     chkSh = checkShuffle();
230   bool chkSl = true;
231   if (FullCheck)
232     chkSl = checkSlots();
233   bool chkAXOK = checkAXOK();
234   bool chkCofMax1 = checkCOFMax1();
235   bool chkHWLoop = checkHWLoop();
236   bool chkValidTmpDst = FullCheck ? checkValidTmpDst() : true;
237   bool chkLegalVecRegPair = checkLegalVecRegPair();
238   bool chk = chkP && chkNV && chkR && chkRRO && chkS && chkSh && chkSl &&
239              chkAXOK && chkCofMax1 && chkHWLoop && chkValidTmpDst &&
240              chkLegalVecRegPair;
241 
242   return chk;
243 }
244 
245 static bool isDuplexAGroup(unsigned Opcode) {
246   switch (Opcode) {
247   case Hexagon::SA1_addi:
248   case Hexagon::SA1_addrx:
249   case Hexagon::SA1_addsp:
250   case Hexagon::SA1_and1:
251   case Hexagon::SA1_clrf:
252   case Hexagon::SA1_clrfnew:
253   case Hexagon::SA1_clrt:
254   case Hexagon::SA1_clrtnew:
255   case Hexagon::SA1_cmpeqi:
256   case Hexagon::SA1_combine0i:
257   case Hexagon::SA1_combine1i:
258   case Hexagon::SA1_combine2i:
259   case Hexagon::SA1_combine3i:
260   case Hexagon::SA1_combinerz:
261   case Hexagon::SA1_combinezr:
262   case Hexagon::SA1_dec:
263   case Hexagon::SA1_inc:
264   case Hexagon::SA1_seti:
265   case Hexagon::SA1_setin1:
266   case Hexagon::SA1_sxtb:
267   case Hexagon::SA1_sxth:
268   case Hexagon::SA1_tfr:
269   case Hexagon::SA1_zxtb:
270   case Hexagon::SA1_zxth:
271     return true;
272     break;
273   default:
274     return false;
275   }
276 }
277 
278 static bool isNeitherAnorX(MCInstrInfo const &MCII, MCInst const &ID) {
279   unsigned Result = 0;
280   unsigned Type = HexagonMCInstrInfo::getType(MCII, ID);
281   if (Type == HexagonII::TypeDUPLEX) {
282     unsigned subInst0Opcode = ID.getOperand(0).getInst()->getOpcode();
283     unsigned subInst1Opcode = ID.getOperand(1).getInst()->getOpcode();
284     Result += !isDuplexAGroup(subInst0Opcode);
285     Result += !isDuplexAGroup(subInst1Opcode);
286   } else
287     Result +=
288         Type != HexagonII::TypeALU32_2op && Type != HexagonII::TypeALU32_3op &&
289         Type != HexagonII::TypeALU32_ADDI && Type != HexagonII::TypeS_2op &&
290         Type != HexagonII::TypeS_3op &&
291         (Type != HexagonII::TypeALU64 || HexagonMCInstrInfo::isFloat(MCII, ID));
292   return Result != 0;
293 }
294 
295 bool HexagonMCChecker::checkAXOK() {
296   MCInst const *HasSoloAXInst = nullptr;
297   for (auto const &I : HexagonMCInstrInfo::bundleInstructions(MCII, MCB)) {
298     if (HexagonMCInstrInfo::isSoloAX(MCII, I)) {
299       HasSoloAXInst = &I;
300     }
301   }
302   if (!HasSoloAXInst)
303     return true;
304   for (auto const &I : HexagonMCInstrInfo::bundleInstructions(MCII, MCB)) {
305     if (&I != HasSoloAXInst && isNeitherAnorX(MCII, I)) {
306       reportError(
307           HasSoloAXInst->getLoc(),
308           Twine("Instruction can only be in a packet with ALU or non-FPU XTYPE "
309                 "instructions"));
310       reportError(I.getLoc(),
311                   Twine("Not an ALU or non-FPU XTYPE instruction"));
312       return false;
313     }
314   }
315   return true;
316 }
317 
318 void HexagonMCChecker::reportBranchErrors() {
319   for (auto const &I : HexagonMCInstrInfo::bundleInstructions(MCII, MCB)) {
320     if (HexagonMCInstrInfo::IsABranchingInst(MCII, STI, I))
321       reportNote(I.getLoc(), "Branching instruction");
322   }
323 }
324 
325 bool HexagonMCChecker::checkHWLoop() {
326   if (!HexagonMCInstrInfo::isInnerLoop(MCB) &&
327       !HexagonMCInstrInfo::isOuterLoop(MCB))
328     return true;
329   for (auto const &I : HexagonMCInstrInfo::bundleInstructions(MCII, MCB)) {
330     if (HexagonMCInstrInfo::IsABranchingInst(MCII, STI, I)) {
331       reportError(MCB.getLoc(),
332                   "Branches cannot be in a packet with hardware loops");
333       reportBranchErrors();
334       return false;
335     }
336   }
337   return true;
338 }
339 
340 bool HexagonMCChecker::checkCOFMax1() {
341   SmallVector<MCInst const *, 2> BranchLocations;
342   for (auto const &I : HexagonMCInstrInfo::bundleInstructions(MCII, MCB)) {
343     if (HexagonMCInstrInfo::IsABranchingInst(MCII, STI, I))
344       BranchLocations.push_back(&I);
345   }
346   for (unsigned J = 0, N = BranchLocations.size(); J < N; ++J) {
347     MCInst const &I = *BranchLocations[J];
348     if (HexagonMCInstrInfo::isCofMax1(MCII, I)) {
349       bool Relax1 = HexagonMCInstrInfo::isCofRelax1(MCII, I);
350       bool Relax2 = HexagonMCInstrInfo::isCofRelax2(MCII, I);
351       if (N > 1 && !Relax1 && !Relax2) {
352         reportError(I.getLoc(),
353                     "Instruction may not be in a packet with other branches");
354         reportBranchErrors();
355         return false;
356       }
357       if (N > 1 && J == 0 && !Relax1) {
358         reportError(I.getLoc(),
359                     "Instruction may not be the first branch in packet");
360         reportBranchErrors();
361         return false;
362       }
363       if (N > 1 && J == 1 && !Relax2) {
364         reportError(I.getLoc(),
365                     "Instruction may not be the second branch in packet");
366         reportBranchErrors();
367         return false;
368       }
369     }
370   }
371   return true;
372 }
373 
374 bool HexagonMCChecker::checkSlots() {
375   unsigned slotsUsed = 0;
376   for (auto HMI : HexagonMCInstrInfo::bundleInstructions(MCB)) {
377     MCInst const &MCI = *HMI.getInst();
378     if (HexagonMCInstrInfo::isImmext(MCI))
379       continue;
380     if (HexagonMCInstrInfo::isDuplex(MCII, MCI))
381       slotsUsed += 2;
382     else
383       ++slotsUsed;
384   }
385 
386   if (slotsUsed > HEXAGON_PACKET_SIZE) {
387     reportError("invalid instruction packet: out of slots");
388     return false;
389   }
390   return true;
391 }
392 
393 // Check legal use of predicate registers.
394 bool HexagonMCChecker::checkPredicates() {
395   // Check for proper use of new predicate registers.
396   for (const auto &I : NewPreds) {
397     unsigned P = I;
398 
399     if (!Defs.count(P) || LatePreds.count(P) || Defs.count(Hexagon::P3_0)) {
400       // Error out if the new predicate register is not defined,
401       // or defined "late"
402       // (e.g., "{ if (p3.new)... ; p3 = sp1loop0(#r7:2, Rs) }").
403       reportErrorNewValue(P);
404       return false;
405     }
406   }
407 
408   // Check for proper use of auto-anded of predicate registers.
409   for (const auto &I : LatePreds) {
410     unsigned P = I;
411 
412     if (LatePreds.count(P) > 1 || Defs.count(P)) {
413       // Error out if predicate register defined "late" multiple times or
414       // defined late and regularly defined
415       // (e.g., "{ p3 = sp1loop0(...); p3 = cmp.eq(...) }".
416       reportErrorRegisters(P);
417       return false;
418     }
419   }
420 
421   return true;
422 }
423 
424 // Check legal use of new values.
425 bool HexagonMCChecker::checkNewValues() {
426   for (auto const &ConsumerInst :
427        HexagonMCInstrInfo::bundleInstructions(MCII, MCB)) {
428     if (!HexagonMCInstrInfo::isNewValue(MCII, ConsumerInst))
429       continue;
430 
431     const HexagonMCInstrInfo::PredicateInfo ConsumerPredInfo =
432         HexagonMCInstrInfo::predicateInfo(MCII, ConsumerInst);
433 
434     bool Branch = HexagonMCInstrInfo::getDesc(MCII, ConsumerInst).isBranch();
435     MCOperand const &Op =
436         HexagonMCInstrInfo::getNewValueOperand(MCII, ConsumerInst);
437     assert(Op.isReg());
438 
439     auto Producer = registerProducer(Op.getReg(), ConsumerPredInfo);
440     const MCInst *const ProducerInst = std::get<0>(Producer);
441     const HexagonMCInstrInfo::PredicateInfo ProducerPredInfo =
442         std::get<2>(Producer);
443 
444     if (ProducerInst == nullptr) {
445       reportError(ConsumerInst.getLoc(),
446                   "New value register consumer has no producer");
447       return false;
448     }
449     if (!RelaxNVChecks) {
450       // Checks that statically prove correct new value consumption
451       if (ProducerPredInfo.isPredicated() &&
452           (!ConsumerPredInfo.isPredicated() ||
453            llvm::HexagonMCInstrInfo::getType(MCII, ConsumerInst) ==
454                HexagonII::TypeNCJ)) {
455         reportNote(
456             ProducerInst->getLoc(),
457             "Register producer is predicated and consumer is unconditional");
458         reportError(ConsumerInst.getLoc(),
459                     "Instruction does not have a valid new register producer");
460         return false;
461       }
462       if (ProducerPredInfo.Register != Hexagon::NoRegister &&
463           ProducerPredInfo.Register != ConsumerPredInfo.Register) {
464         reportNote(ProducerInst->getLoc(),
465                    "Register producer does not use the same predicate "
466                    "register as the consumer");
467         reportError(ConsumerInst.getLoc(),
468                     "Instruction does not have a valid new register producer");
469         return false;
470       }
471     }
472     if (ProducerPredInfo.Register == ConsumerPredInfo.Register &&
473         ConsumerPredInfo.PredicatedTrue != ProducerPredInfo.PredicatedTrue) {
474       reportNote(
475           ProducerInst->getLoc(),
476           "Register producer has the opposite predicate sense as consumer");
477       reportError(ConsumerInst.getLoc(),
478                   "Instruction does not have a valid new register producer");
479       return false;
480     }
481 
482     MCInstrDesc const &Desc = HexagonMCInstrInfo::getDesc(MCII, *ProducerInst);
483     const unsigned ProducerOpIndex = std::get<1>(Producer);
484 
485     if (Desc.OpInfo[ProducerOpIndex].RegClass ==
486         Hexagon::DoubleRegsRegClassID) {
487       reportNote(ProducerInst->getLoc(),
488                  "Double registers cannot be new-value producers");
489       reportError(ConsumerInst.getLoc(),
490                   "Instruction does not have a valid new register producer");
491       return false;
492     }
493 
494     // The ProducerOpIsMemIndex logic checks for the index of the producer
495     // register operand.  Z-reg load instructions have an implicit operand
496     // that's not encoded, so the producer won't appear as the 1-th def, it
497     // will be at the 0-th.
498     const unsigned ProducerOpSearchIndex =
499         (HexagonMCInstrInfo::getType(MCII, *ProducerInst) ==
500          HexagonII::TypeCVI_ZW)
501             ? 0
502             : 1;
503 
504     const bool ProducerOpIsMemIndex =
505         ((Desc.mayLoad() && ProducerOpIndex == ProducerOpSearchIndex) ||
506          (Desc.mayStore() && ProducerOpIndex == 0));
507 
508     if (ProducerOpIsMemIndex) {
509       unsigned Mode = HexagonMCInstrInfo::getAddrMode(MCII, *ProducerInst);
510 
511       StringRef ModeError;
512       if (Mode == HexagonII::AbsoluteSet)
513         ModeError = "Absolute-set";
514       if (Mode == HexagonII::PostInc)
515         ModeError = "Auto-increment";
516       if (!ModeError.empty()) {
517         reportNote(ProducerInst->getLoc(),
518                    ModeError + " registers cannot be a new-value "
519                                "producer");
520         reportError(ConsumerInst.getLoc(),
521                     "Instruction does not have a valid new register producer");
522         return false;
523       }
524     }
525     if (Branch && HexagonMCInstrInfo::isFloat(MCII, *ProducerInst)) {
526       reportNote(ProducerInst->getLoc(),
527                  "FPU instructions cannot be new-value producers for jumps");
528       reportError(ConsumerInst.getLoc(),
529                   "Instruction does not have a valid new register producer");
530       return false;
531     }
532   }
533   return true;
534 }
535 
536 bool HexagonMCChecker::checkRegistersReadOnly() {
537   for (auto I : HexagonMCInstrInfo::bundleInstructions(MCB)) {
538     MCInst const &Inst = *I.getInst();
539     unsigned Defs = HexagonMCInstrInfo::getDesc(MCII, Inst).getNumDefs();
540     for (unsigned j = 0; j < Defs; ++j) {
541       MCOperand const &Operand = Inst.getOperand(j);
542       assert(Operand.isReg() && "Def is not a register");
543       unsigned Register = Operand.getReg();
544       if (ReadOnly.find(Register) != ReadOnly.end()) {
545         reportError(Inst.getLoc(), "Cannot write to read-only register `" +
546                                        Twine(RI.getName(Register)) + "'");
547         return false;
548       }
549     }
550   }
551   return true;
552 }
553 
554 bool HexagonMCChecker::registerUsed(unsigned Register) {
555   for (auto const &I : HexagonMCInstrInfo::bundleInstructions(MCII, MCB))
556     for (unsigned j = HexagonMCInstrInfo::getDesc(MCII, I).getNumDefs(),
557                   n = I.getNumOperands();
558          j < n; ++j) {
559       MCOperand const &Operand = I.getOperand(j);
560       if (Operand.isReg() && Operand.getReg() == Register)
561         return true;
562     }
563   return false;
564 }
565 
566 std::tuple<MCInst const *, unsigned, HexagonMCInstrInfo::PredicateInfo>
567 HexagonMCChecker::registerProducer(
568     unsigned Register, HexagonMCInstrInfo::PredicateInfo ConsumerPredicate) {
569   std::tuple<MCInst const *, unsigned, HexagonMCInstrInfo::PredicateInfo>
570       WrongSense;
571 
572   for (auto const &I : HexagonMCInstrInfo::bundleInstructions(MCII, MCB)) {
573     MCInstrDesc const &Desc = HexagonMCInstrInfo::getDesc(MCII, I);
574     auto ProducerPredicate = HexagonMCInstrInfo::predicateInfo(MCII, I);
575 
576     for (unsigned J = 0, N = Desc.getNumDefs(); J < N; ++J)
577       for (auto K = MCRegAliasIterator(I.getOperand(J).getReg(), &RI, true);
578            K.isValid(); ++K)
579         if (*K == Register) {
580           if (RelaxNVChecks ||
581               (ProducerPredicate.Register == ConsumerPredicate.Register &&
582                (ProducerPredicate.Register == Hexagon::NoRegister ||
583                 ProducerPredicate.PredicatedTrue ==
584                     ConsumerPredicate.PredicatedTrue)))
585             return std::make_tuple(&I, J, ProducerPredicate);
586           std::get<0>(WrongSense) = &I;
587           std::get<1>(WrongSense) = J;
588           std::get<2>(WrongSense) = ProducerPredicate;
589         }
590     if (Register == Hexagon::VTMP && HexagonMCInstrInfo::hasTmpDst(MCII, I))
591       return std::make_tuple(&I, 0, HexagonMCInstrInfo::PredicateInfo());
592   }
593   return WrongSense;
594 }
595 
596 void HexagonMCChecker::checkRegisterCurDefs() {
597   for (auto const &I : HexagonMCInstrInfo::bundleInstructions(MCII, MCB)) {
598     if (HexagonMCInstrInfo::isCVINew(MCII, I) &&
599         HexagonMCInstrInfo::getDesc(MCII, I).mayLoad()) {
600       const unsigned RegDef = I.getOperand(0).getReg();
601 
602       bool HasRegDefUse = false;
603       for (MCRegAliasIterator Alias(RegDef, &RI, true); Alias.isValid();
604            ++Alias)
605         HasRegDefUse = HasRegDefUse || registerUsed(*Alias);
606 
607       if (!HasRegDefUse)
608         reportWarning("Register `" + Twine(RI.getName(RegDef)) +
609                       "' used with `.cur' "
610                       "but not used in the same packet");
611     }
612   }
613 }
614 
615 // Check for legal register uses and definitions.
616 bool HexagonMCChecker::checkRegisters() {
617   // Check for proper register definitions.
618   for (const auto &I : Defs) {
619     unsigned R = I.first;
620 
621     if (isLoopRegister(R) && Defs.count(R) > 1 &&
622         (HexagonMCInstrInfo::isInnerLoop(MCB) ||
623          HexagonMCInstrInfo::isOuterLoop(MCB))) {
624       // Error out for definitions of loop registers at the end of a loop.
625       reportError("loop-setup and some branch instructions "
626                   "cannot be in the same packet");
627       return false;
628     }
629     if (SoftDefs.count(R)) {
630       // Error out for explicit changes to registers also weakly defined
631       // (e.g., "{ usr = r0; r0 = sfadd(...) }").
632       unsigned UsrR = Hexagon::USR; // Silence warning about mixed types in ?:.
633       unsigned BadR = RI.isSubRegister(Hexagon::USR, R) ? UsrR : R;
634       reportErrorRegisters(BadR);
635       return false;
636     }
637     if (!HexagonMCInstrInfo::isPredReg(RI, R) && Defs[R].size() > 1) {
638       // Check for multiple register definitions.
639       PredSet &PM = Defs[R];
640 
641       // Check for multiple unconditional register definitions.
642       if (PM.count(Unconditional)) {
643         // Error out on an unconditional change when there are any other
644         // changes, conditional or not.
645         unsigned UsrR = Hexagon::USR;
646         unsigned BadR = RI.isSubRegister(Hexagon::USR, R) ? UsrR : R;
647         reportErrorRegisters(BadR);
648         return false;
649       }
650       // Check for multiple conditional register definitions.
651       for (const auto &J : PM) {
652         PredSense P = J;
653 
654         // Check for multiple uses of the same condition.
655         if (PM.count(P) > 1) {
656           // Error out on conditional changes based on the same predicate
657           // (e.g., "{ if (!p0) r0 =...; if (!p0) r0 =... }").
658           reportErrorRegisters(R);
659           return false;
660         }
661         // Check for the use of the complementary condition.
662         P.second = !P.second;
663         if (PM.count(P) && PM.size() > 2) {
664           // Error out on conditional changes based on the same predicate
665           // multiple times
666           // (e.g., "if (p0) r0 =...; if (!p0) r0 =... }; if (!p0) r0 =...").
667           reportErrorRegisters(R);
668           return false;
669         }
670       }
671     }
672   }
673 
674   // Check for use of temporary definitions.
675   for (const auto &I : TmpDefs) {
676     unsigned R = I;
677 
678     if (!Uses.count(R)) {
679       // special case for vhist
680       bool vHistFound = false;
681       for (auto const &HMI : HexagonMCInstrInfo::bundleInstructions(MCB)) {
682         if (HexagonMCInstrInfo::getType(MCII, *HMI.getInst()) ==
683             HexagonII::TypeCVI_HIST) {
684           vHistFound = true; // vhist() implicitly uses ALL REGxx.tmp
685           break;
686         }
687       }
688       // Warn on an unused temporary definition.
689       if (!vHistFound) {
690         reportWarning("register `" + Twine(RI.getName(R)) +
691                       "' used with `.tmp' but not used in the same packet");
692         return true;
693       }
694     }
695   }
696 
697   return true;
698 }
699 
700 // Check for legal use of solo insns.
701 bool HexagonMCChecker::checkSolo() {
702   if (HexagonMCInstrInfo::bundleSize(MCB) > 1)
703     for (auto const &I : HexagonMCInstrInfo::bundleInstructions(MCII, MCB)) {
704       if (HexagonMCInstrInfo::isSolo(MCII, I)) {
705         reportError(I.getLoc(), "Instruction is marked `isSolo' and "
706                                 "cannot have other instructions in "
707                                 "the same packet");
708         return false;
709       }
710     }
711 
712   return true;
713 }
714 
715 bool HexagonMCChecker::checkShuffle() {
716   HexagonMCShuffler MCSDX(Context, ReportErrors, MCII, STI, MCB);
717   return MCSDX.check();
718 }
719 
720 bool HexagonMCChecker::checkValidTmpDst() {
721   if (!STI.getFeatureBits()[Hexagon::ArchV69]) {
722     return true;
723   }
724   auto HasTmp = [&](MCInst const &I) {
725     return HexagonMCInstrInfo::hasTmpDst(MCII, I) ||
726            HexagonMCInstrInfo::hasHvxTmp(MCII, I);
727   };
728   unsigned HasTmpCount =
729       llvm::count_if(HexagonMCInstrInfo::bundleInstructions(MCII, MCB), HasTmp);
730 
731   if (HasTmpCount > 1) {
732     reportError(
733         MCB.getLoc(),
734         "this packet has more than one HVX vtmp/.tmp destination instruction");
735 
736     for (auto const &I : HexagonMCInstrInfo::bundleInstructions(MCII, MCB))
737       if (HasTmp(I))
738         reportNote(I.getLoc(),
739                    "this is an HVX vtmp/.tmp destination instruction");
740 
741     return false;
742   }
743   return true;
744 }
745 
746 void HexagonMCChecker::compoundRegisterMap(unsigned &Register) {
747   switch (Register) {
748   default:
749     break;
750   case Hexagon::R15:
751     Register = Hexagon::R23;
752     break;
753   case Hexagon::R14:
754     Register = Hexagon::R22;
755     break;
756   case Hexagon::R13:
757     Register = Hexagon::R21;
758     break;
759   case Hexagon::R12:
760     Register = Hexagon::R20;
761     break;
762   case Hexagon::R11:
763     Register = Hexagon::R19;
764     break;
765   case Hexagon::R10:
766     Register = Hexagon::R18;
767     break;
768   case Hexagon::R9:
769     Register = Hexagon::R17;
770     break;
771   case Hexagon::R8:
772     Register = Hexagon::R16;
773     break;
774   }
775 }
776 
777 void HexagonMCChecker::reportErrorRegisters(unsigned Register) {
778   reportError("register `" + Twine(RI.getName(Register)) +
779               "' modified more than once");
780 }
781 
782 void HexagonMCChecker::reportErrorNewValue(unsigned Register) {
783   reportError("register `" + Twine(RI.getName(Register)) +
784               "' used with `.new' "
785               "but not validly modified in the same packet");
786 }
787 
788 void HexagonMCChecker::reportError(Twine const &Msg) {
789   reportError(MCB.getLoc(), Msg);
790 }
791 
792 void HexagonMCChecker::reportError(SMLoc Loc, Twine const &Msg) {
793   if (ReportErrors)
794     Context.reportError(Loc, Msg);
795 }
796 
797 void HexagonMCChecker::reportNote(SMLoc Loc, llvm::Twine const &Msg) {
798   if (ReportErrors) {
799     auto SM = Context.getSourceManager();
800     if (SM)
801       SM->PrintMessage(Loc, SourceMgr::DK_Note, Msg);
802   }
803 }
804 
805 void HexagonMCChecker::reportWarning(Twine const &Msg) {
806   if (ReportErrors)
807     Context.reportWarning(MCB.getLoc(), Msg);
808 }
809 
810 bool HexagonMCChecker::checkLegalVecRegPair() {
811   const bool IsPermitted = STI.getFeatureBits()[Hexagon::ArchV67];
812   const bool HasReversePairs = ReversePairs.size() != 0;
813 
814   if (!IsPermitted && HasReversePairs) {
815     for (auto R : ReversePairs)
816       reportError("register pair `" + Twine(RI.getName(R)) +
817                   "' is not permitted for this architecture");
818     return false;
819   }
820   return true;
821 }
822