1//===----- HexagonMCChecker.cpp - Instruction bundle checking -------------===//
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// This implements the checking of insns inside a bundle according to the
11// packet constraint rules of the Hexagon ISA.
12//
13//===----------------------------------------------------------------------===//
14
15#include "HexagonMCChecker.h"
16
17#include "HexagonBaseInfo.h"
18
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/MC/MCInstrDesc.h"
21#include "llvm/MC/MCInstrInfo.h"
22#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/Support/raw_ostream.h"
25
26using namespace llvm;
27
28static cl::opt<bool> RelaxNVChecks("relax-nv-checks", cl::init(false),
29  cl::ZeroOrMore, cl::Hidden, cl::desc("Relax checks of new-value validity"));
30
31const HexagonMCChecker::PredSense
32  HexagonMCChecker::Unconditional(Hexagon::NoRegister, false);
33
34void HexagonMCChecker::init() {
35  // Initialize read-only registers set.
36  ReadOnly.insert(Hexagon::PC);
37
38  // Figure out the loop-registers definitions.
39  if (HexagonMCInstrInfo::isInnerLoop(MCB)) {
40    Defs[Hexagon::SA0].insert(Unconditional); // FIXME: define or change SA0?
41    Defs[Hexagon::LC0].insert(Unconditional);
42  }
43  if (HexagonMCInstrInfo::isOuterLoop(MCB)) {
44    Defs[Hexagon::SA1].insert(Unconditional); // FIXME: define or change SA0?
45    Defs[Hexagon::LC1].insert(Unconditional);
46  }
47
48  if (HexagonMCInstrInfo::isBundle(MCB))
49    // Unfurl a bundle.
50    for (auto const&I : HexagonMCInstrInfo::bundleInstructions(MCB)) {
51      init(*I.getInst());
52    }
53  else
54    init(MCB);
55}
56
57void HexagonMCChecker::init(MCInst const& MCI) {
58  const MCInstrDesc& MCID = HexagonMCInstrInfo::getDesc(MCII, MCI);
59  unsigned PredReg = Hexagon::NoRegister;
60  bool isTrue = false;
61
62  // Get used registers.
63  for (unsigned i = MCID.getNumDefs(); i < MCID.getNumOperands(); ++i)
64    if (MCI.getOperand(i).isReg()) {
65      unsigned R = MCI.getOperand(i).getReg();
66
67      if (HexagonMCInstrInfo::isPredicated(MCII, MCI) && isPredicateRegister(R)) {
68        // Note an used predicate register.
69        PredReg = R;
70        isTrue = HexagonMCInstrInfo::isPredicatedTrue(MCII, MCI);
71
72        // Note use of new predicate register.
73        if (HexagonMCInstrInfo::isPredicatedNew(MCII, MCI))
74          NewPreds.insert(PredReg);
75      }
76      else
77        // Note register use.  Super-registers are not tracked directly,
78        // but their components.
79        for(MCRegAliasIterator SRI(R, &RI, !MCSubRegIterator(R, &RI).isValid());
80           SRI.isValid();
81           ++SRI)
82         if (!MCSubRegIterator(*SRI, &RI).isValid())
83           // Skip super-registers used indirectly.
84           Uses.insert(*SRI);
85    }
86
87  // Get implicit register definitions.
88  if (const MCPhysReg *ImpDef = MCID.getImplicitDefs())
89    for (; *ImpDef; ++ImpDef) {
90      unsigned R = *ImpDef;
91
92      if (Hexagon::R31 != R && MCID.isCall())
93        // Any register other than the LR and the PC are actually volatile ones
94        // as defined by the ABI, not modified implicitly by the call insn.
95        continue;
96      if (Hexagon::PC == R)
97        // Branches are the only insns that can change the PC,
98        // otherwise a read-only register.
99        continue;
100
101      if (Hexagon::USR_OVF == R)
102        // Many insns change the USR implicitly, but only one or another flag.
103        // The instruction table models the USR.OVF flag, which can be implicitly
104        // modified more than once, but cannot be modified in the same packet
105        // with an instruction that modifies is explicitly. Deal with such situ-
106        // ations individually.
107        SoftDefs.insert(R);
108      else if (isPredicateRegister(R) &&
109               HexagonMCInstrInfo::isPredicateLate(MCII, MCI))
110        // Include implicit late predicates.
111        LatePreds.insert(R);
112      else
113        Defs[R].insert(PredSense(PredReg, isTrue));
114    }
115
116  // Figure out explicit register definitions.
117  for (unsigned i = 0; i < MCID.getNumDefs(); ++i) {
118    unsigned R = MCI.getOperand(i).getReg(),
119             S = Hexagon::NoRegister;
120
121    // Note register definitions, direct ones as well as indirect side-effects.
122    // Super-registers are not tracked directly, but their components.
123    for(MCRegAliasIterator SRI(R, &RI, !MCSubRegIterator(R, &RI).isValid());
124        SRI.isValid();
125        ++SRI) {
126      if (MCSubRegIterator(*SRI, &RI).isValid())
127        // Skip super-registers defined indirectly.
128        continue;
129
130      if (R == *SRI) {
131        if (S == R)
132          // Avoid scoring the defined register multiple times.
133          continue;
134        else
135          // Note that the defined register has already been scored.
136          S = R;
137      }
138
139      if (Hexagon::P3_0 != R && Hexagon::P3_0 == *SRI)
140        // P3:0 is a special case, since multiple predicate register definitions
141        // in a packet is allowed as the equivalent of their logical "and".
142        // Only an explicit definition of P3:0 is noted as such; if a
143        // side-effect, then note as a soft definition.
144        SoftDefs.insert(*SRI);
145      else if (HexagonMCInstrInfo::isPredicateLate(MCII, MCI) && isPredicateRegister(*SRI))
146        // Some insns produce predicates too late to be used in the same packet.
147        LatePreds.insert(*SRI);
148      else if (i == 0 && llvm::HexagonMCInstrInfo::getType(MCII, MCI) == HexagonII::TypeCVI_VM_CUR_LD)
149        // Current loads should be used in the same packet.
150        // TODO: relies on the impossibility of a current and a temporary loads
151        // in the same packet.
152        CurDefs.insert(*SRI), Defs[*SRI].insert(PredSense(PredReg, isTrue));
153      else if (i == 0 && llvm::HexagonMCInstrInfo::getType(MCII, MCI) == HexagonII::TypeCVI_VM_TMP_LD)
154        // Temporary loads should be used in the same packet, but don't commit
155        // results, so it should be disregarded if another insn changes the same
156        // register.
157        // TODO: relies on the impossibility of a current and a temporary loads
158        // in the same packet.
159        TmpDefs.insert(*SRI);
160      else if (i <= 1 && llvm::HexagonMCInstrInfo::hasNewValue2(MCII, MCI) )
161        // vshuff(Vx, Vy, Rx) <- Vx(0) and Vy(1) are both source and
162        // destination registers with this instruction. same for vdeal(Vx,Vy,Rx)
163        Uses.insert(*SRI);
164      else
165        Defs[*SRI].insert(PredSense(PredReg, isTrue));
166    }
167  }
168
169  // Figure out register definitions that produce new values.
170  if (HexagonMCInstrInfo::hasNewValue(MCII, MCI)) {
171    unsigned R = HexagonMCInstrInfo::getNewValueOperand(MCII, MCI).getReg();
172
173    if (HexagonMCInstrInfo::isCompound(MCII, MCI))
174      compoundRegisterMap(R); // Compound insns have a limited register range.
175
176    for(MCRegAliasIterator SRI(R, &RI, !MCSubRegIterator(R, &RI).isValid());
177        SRI.isValid();
178        ++SRI)
179      if (!MCSubRegIterator(*SRI, &RI).isValid())
180        // No super-registers defined indirectly.
181        NewDefs[*SRI].push_back(NewSense::Def(PredReg, HexagonMCInstrInfo::isPredicatedTrue(MCII, MCI),
182                                              HexagonMCInstrInfo::isFloat(MCII, MCI)));
183
184    // For fairly unique 2-dot-new producers, example:
185    // vdeal(V1, V9, R0) V1.new and V9.new can be used by consumers.
186    if (HexagonMCInstrInfo::hasNewValue2(MCII, MCI)) {
187      unsigned R2 = HexagonMCInstrInfo::getNewValueOperand2(MCII, MCI).getReg();
188
189      for(MCRegAliasIterator SRI(R2, &RI, !MCSubRegIterator(R2, &RI).isValid());
190          SRI.isValid();
191          ++SRI)
192        if (!MCSubRegIterator(*SRI, &RI).isValid())
193          NewDefs[*SRI].push_back(NewSense::Def(PredReg, HexagonMCInstrInfo::isPredicatedTrue(MCII, MCI),
194                                                HexagonMCInstrInfo::isFloat(MCII, MCI)));
195    }
196  }
197
198  // Figure out definitions of new predicate registers.
199  if (HexagonMCInstrInfo::isPredicatedNew(MCII, MCI))
200    for (unsigned i = MCID.getNumDefs(); i < MCID.getNumOperands(); ++i)
201      if (MCI.getOperand(i).isReg()) {
202        unsigned P = MCI.getOperand(i).getReg();
203
204        if (isPredicateRegister(P))
205          NewPreds.insert(P);
206      }
207
208  // Figure out uses of new values.
209  if (HexagonMCInstrInfo::isNewValue(MCII, MCI)) {
210    unsigned N = HexagonMCInstrInfo::getNewValueOperand(MCII, MCI).getReg();
211
212    if (!MCSubRegIterator(N, &RI).isValid()) {
213      // Super-registers cannot use new values.
214      if (MCID.isBranch())
215        NewUses[N] = NewSense::Jmp(llvm::HexagonMCInstrInfo::getType(MCII, MCI) == HexagonII::TypeNV);
216      else
217        NewUses[N] = NewSense::Use(PredReg, HexagonMCInstrInfo::isPredicatedTrue(MCII, MCI));
218    }
219  }
220}
221
222HexagonMCChecker::HexagonMCChecker(MCInstrInfo const &MCII, MCSubtargetInfo const &STI, MCInst &mcb, MCInst &mcbdx,
223                                   MCRegisterInfo const &ri)
224    : MCB(mcb), MCBDX(mcbdx), RI(ri), MCII(MCII), STI(STI),
225      bLoadErrInfo(false) {
226  init();
227}
228
229bool HexagonMCChecker::check() {
230  bool chkB = checkBranches();
231  bool chkP = checkPredicates();
232  bool chkNV = checkNewValues();
233  bool chkR = checkRegisters();
234  bool chkS = checkSolo();
235  bool chkSh = checkShuffle();
236  bool chkSl = checkSlots();
237  bool chk = chkB && chkP && chkNV && chkR && chkS && chkSh && chkSl;
238
239  return chk;
240}
241
242bool HexagonMCChecker::checkSlots()
243
244{
245  unsigned slotsUsed = 0;
246  for (auto HMI: HexagonMCInstrInfo::bundleInstructions(MCBDX)) {
247    MCInst const& MCI = *HMI.getInst();
248    if (HexagonMCInstrInfo::isImmext(MCI))
249      continue;
250    if (HexagonMCInstrInfo::isDuplex(MCII, MCI))
251      slotsUsed += 2;
252    else
253      ++slotsUsed;
254  }
255
256  if (slotsUsed > HEXAGON_PACKET_SIZE) {
257    HexagonMCErrInfo errInfo;
258    errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_NOSLOTS);
259    addErrInfo(errInfo);
260    return false;
261  }
262  return true;
263}
264
265// Check legal use of branches.
266bool HexagonMCChecker::checkBranches() {
267  HexagonMCErrInfo errInfo;
268  if (HexagonMCInstrInfo::isBundle(MCB)) {
269    bool hasConditional = false;
270    unsigned Branches = 0, Returns = 0, NewIndirectBranches = 0,
271             NewValueBranches = 0, Conditional = HEXAGON_PRESHUFFLE_PACKET_SIZE,
272             Unconditional = HEXAGON_PRESHUFFLE_PACKET_SIZE;
273
274    for (unsigned i = HexagonMCInstrInfo::bundleInstructionsOffset;
275         i < MCB.size(); ++i) {
276      MCInst const &MCI = *MCB.begin()[i].getInst();
277
278      if (HexagonMCInstrInfo::isImmext(MCI))
279        continue;
280      if (HexagonMCInstrInfo::getDesc(MCII, MCI).isBranch() ||
281          HexagonMCInstrInfo::getDesc(MCII, MCI).isCall()) {
282        ++Branches;
283        if (HexagonMCInstrInfo::getDesc(MCII, MCI).isIndirectBranch() &&
284            HexagonMCInstrInfo::isPredicatedNew(MCII, MCI))
285          ++NewIndirectBranches;
286        if (HexagonMCInstrInfo::isNewValue(MCII, MCI))
287          ++NewValueBranches;
288
289        if (HexagonMCInstrInfo::isPredicated(MCII, MCI) ||
290            HexagonMCInstrInfo::isPredicatedNew(MCII, MCI)) {
291          hasConditional = true;
292          Conditional = i; // Record the position of the conditional branch.
293        } else {
294          Unconditional = i; // Record the position of the unconditional branch.
295        }
296      }
297      if (HexagonMCInstrInfo::getDesc(MCII, MCI).isReturn() &&
298          HexagonMCInstrInfo::getDesc(MCII, MCI).mayLoad())
299        ++Returns;
300    }
301
302    if (Branches) // FIXME: should "Defs.count(Hexagon::PC)" be here too?
303      if (HexagonMCInstrInfo::isInnerLoop(MCB) ||
304          HexagonMCInstrInfo::isOuterLoop(MCB)) {
305        // Error out if there's any branch in a loop-end packet.
306        errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_ENDLOOP, Hexagon::PC);
307        addErrInfo(errInfo);
308        return false;
309      }
310    if (Branches > 1)
311      if (!hasConditional || Conditional > Unconditional) {
312        // Error out if more than one unconditional branch or
313        // the conditional branch appears after the unconditional one.
314        errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_BRANCHES);
315        addErrInfo(errInfo);
316        return false;
317      }
318  }
319
320  return true;
321}
322
323// Check legal use of predicate registers.
324bool HexagonMCChecker::checkPredicates() {
325  HexagonMCErrInfo errInfo;
326  // Check for proper use of new predicate registers.
327  for (const auto& I : NewPreds) {
328    unsigned P = I;
329
330    if (!Defs.count(P) || LatePreds.count(P)) {
331      // Error out if the new predicate register is not defined,
332      // or defined "late"
333      // (e.g., "{ if (p3.new)... ; p3 = sp1loop0(#r7:2, Rs) }").
334      errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_NEWP, P);
335      addErrInfo(errInfo);
336      return false;
337    }
338  }
339
340  // Check for proper use of auto-anded of predicate registers.
341  for (const auto& I : LatePreds) {
342    unsigned P = I;
343
344    if (LatePreds.count(P) > 1 || Defs.count(P)) {
345      // Error out if predicate register defined "late" multiple times or
346      // defined late and regularly defined
347      // (e.g., "{ p3 = sp1loop0(...); p3 = cmp.eq(...) }".
348      errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_REGISTERS, P);
349      addErrInfo(errInfo);
350      return false;
351    }
352  }
353
354  return true;
355}
356
357// Check legal use of new values.
358bool HexagonMCChecker::checkNewValues() {
359  HexagonMCErrInfo errInfo;
360  memset(&errInfo, 0, sizeof(errInfo));
361  for (auto& I : NewUses) {
362    unsigned R = I.first;
363    NewSense &US = I.second;
364
365    if (!hasValidNewValueDef(US, NewDefs[R])) {
366      errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_NEWV, R);
367      addErrInfo(errInfo);
368      return false;
369    }
370  }
371
372  return true;
373}
374
375// Check for legal register uses and definitions.
376bool HexagonMCChecker::checkRegisters() {
377  HexagonMCErrInfo errInfo;
378  // Check for proper register definitions.
379  for (const auto& I : Defs) {
380    unsigned R = I.first;
381
382    if (ReadOnly.count(R)) {
383      // Error out for definitions of read-only registers.
384      errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_READONLY, R);
385      addErrInfo(errInfo);
386      return false;
387    }
388    if (isLoopRegister(R) && Defs.count(R) > 1 &&
389        (HexagonMCInstrInfo::isInnerLoop(MCB) ||
390         HexagonMCInstrInfo::isOuterLoop(MCB))) {
391      // Error out for definitions of loop registers at the end of a loop.
392      errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_LOOP, R);
393      addErrInfo(errInfo);
394      return false;
395    }
396    if (SoftDefs.count(R)) {
397      // Error out for explicit changes to registers also weakly defined
398      // (e.g., "{ usr = r0; r0 = sfadd(...) }").
399      unsigned UsrR = Hexagon::USR; // Silence warning about mixed types in ?:.
400      unsigned BadR = RI.isSubRegister(Hexagon::USR, R) ? UsrR : R;
401      errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_REGISTERS, BadR);
402      addErrInfo(errInfo);
403      return false;
404    }
405    if (!isPredicateRegister(R) && Defs[R].size() > 1) {
406      // Check for multiple register definitions.
407      PredSet &PM = Defs[R];
408
409      // Check for multiple unconditional register definitions.
410      if (PM.count(Unconditional)) {
411        // Error out on an unconditional change when there are any other
412        // changes, conditional or not.
413        unsigned UsrR = Hexagon::USR;
414        unsigned BadR = RI.isSubRegister(Hexagon::USR, R) ? UsrR : R;
415        errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_REGISTERS, BadR);
416        addErrInfo(errInfo);
417        return false;
418      }
419      // Check for multiple conditional register definitions.
420      for (const auto& J : PM) {
421        PredSense P = J;
422
423        // Check for multiple uses of the same condition.
424        if (PM.count(P) > 1) {
425          // Error out on conditional changes based on the same predicate
426          // (e.g., "{ if (!p0) r0 =...; if (!p0) r0 =... }").
427          errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_REGISTERS, R);
428          addErrInfo(errInfo);
429          return false;
430        }
431        // Check for the use of the complementary condition.
432        P.second = !P.second;
433        if (PM.count(P) && PM.size() > 2) {
434          // Error out on conditional changes based on the same predicate
435          // multiple times
436          // (e.g., "{ if (p0) r0 =...; if (!p0) r0 =... }; if (!p0) r0 =... }").
437          errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_REGISTERS, R);
438          addErrInfo(errInfo);
439          return false;
440        }
441      }
442    }
443  }
444
445  // Check for use of current definitions.
446  for (const auto& I : CurDefs) {
447    unsigned R = I;
448
449    if (!Uses.count(R)) {
450      // Warn on an unused current definition.
451      errInfo.setWarning(HexagonMCErrInfo::CHECK_WARN_CURRENT, R);
452      addErrInfo(errInfo);
453      return true;
454    }
455  }
456
457  // Check for use of temporary definitions.
458  for (const auto& I : TmpDefs) {
459    unsigned R = I;
460
461    if (!Uses.count(R)) {
462      // special case for vhist
463      bool vHistFound = false;
464      for (auto const&HMI : HexagonMCInstrInfo::bundleInstructions(MCB)) {
465        if(llvm::HexagonMCInstrInfo::getType(MCII, *HMI.getInst()) == HexagonII::TypeCVI_HIST) {
466          vHistFound = true;  // vhist() implicitly uses ALL REGxx.tmp
467          break;
468        }
469      }
470      // Warn on an unused temporary definition.
471      if (vHistFound == false) {
472        errInfo.setWarning(HexagonMCErrInfo::CHECK_WARN_TEMPORARY, R);
473        addErrInfo(errInfo);
474        return true;
475      }
476    }
477  }
478
479  return true;
480}
481
482// Check for legal use of solo insns.
483bool HexagonMCChecker::checkSolo() {
484  HexagonMCErrInfo errInfo;
485  if (HexagonMCInstrInfo::isBundle(MCB) &&
486      HexagonMCInstrInfo::bundleSize(MCB) > 1) {
487    for (auto const&I : HexagonMCInstrInfo::bundleInstructions(MCB)) {
488      if (llvm::HexagonMCInstrInfo::isSolo(MCII, *I.getInst())) {
489        errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_SOLO);
490        addErrInfo(errInfo);
491        return false;
492      }
493    }
494  }
495
496  return true;
497}
498
499bool HexagonMCChecker::checkShuffle() {
500  HexagonMCErrInfo errInfo;
501  // Branch info is lost when duplexing. The unduplexed insns must be
502  // checked and only branch errors matter for this case.
503  HexagonMCShuffler MCS(MCII, STI, MCB);
504  if (!MCS.check()) {
505    if (MCS.getError() == HexagonShuffler::SHUFFLE_ERROR_BRANCHES) {
506      errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_SHUFFLE);
507      errInfo.setShuffleError(MCS.getError());
508      addErrInfo(errInfo);
509      return false;
510    }
511  }
512  HexagonMCShuffler MCSDX(MCII, STI, MCBDX);
513  if (!MCSDX.check()) {
514    errInfo.setError(HexagonMCErrInfo::CHECK_ERROR_SHUFFLE);
515    errInfo.setShuffleError(MCSDX.getError());
516    addErrInfo(errInfo);
517    return false;
518  }
519  return true;
520}
521
522void HexagonMCChecker::compoundRegisterMap(unsigned& Register) {
523  switch (Register) {
524  default:
525    break;
526  case Hexagon::R15:
527    Register = Hexagon::R23;
528    break;
529  case Hexagon::R14:
530    Register = Hexagon::R22;
531    break;
532  case Hexagon::R13:
533    Register = Hexagon::R21;
534    break;
535  case Hexagon::R12:
536    Register = Hexagon::R20;
537    break;
538  case Hexagon::R11:
539    Register = Hexagon::R19;
540    break;
541  case Hexagon::R10:
542    Register = Hexagon::R18;
543    break;
544  case Hexagon::R9:
545    Register = Hexagon::R17;
546    break;
547  case Hexagon::R8:
548    Register = Hexagon::R16;
549    break;
550  }
551}
552
553bool HexagonMCChecker::hasValidNewValueDef(const NewSense &Use,
554      const NewSenseList &Defs) const {
555  bool Strict = !RelaxNVChecks;
556
557  for (unsigned i = 0, n = Defs.size(); i < n; ++i) {
558    const NewSense &Def = Defs[i];
559    // NVJ cannot use a new FP value [7.6.1]
560    if (Use.IsNVJ && (Def.IsFloat || Def.PredReg != 0))
561      continue;
562    // If the definition was not predicated, then it does not matter if
563    // the use is.
564    if (Def.PredReg == 0)
565      return true;
566    // With the strict checks, both the definition and the use must be
567    // predicated on the same register and condition.
568    if (Strict) {
569      if (Def.PredReg == Use.PredReg && Def.Cond == Use.Cond)
570        return true;
571    } else {
572      // With the relaxed checks, if the definition was predicated, the only
573      // detectable violation is if the use is predicated on the opposing
574      // condition, otherwise, it's ok.
575      if (Def.PredReg != Use.PredReg || Def.Cond == Use.Cond)
576        return true;
577    }
578  }
579  return false;
580}
581
582