1//===- CodeGenInstruction.cpp - CodeGen Instruction Class Wrapper ---------===//
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 file implements the CodeGenInstruction class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CodeGenInstruction.h"
14#include "CodeGenTarget.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/StringExtras.h"
17#include "llvm/ADT/StringMap.h"
18#include "llvm/TableGen/Error.h"
19#include "llvm/TableGen/Record.h"
20#include <set>
21using namespace llvm;
22
23//===----------------------------------------------------------------------===//
24// CGIOperandList Implementation
25//===----------------------------------------------------------------------===//
26
27CGIOperandList::CGIOperandList(Record *R) : TheDef(R) {
28  isPredicable = false;
29  hasOptionalDef = false;
30  isVariadic = false;
31
32  DagInit *OutDI = R->getValueAsDag("OutOperandList");
33
34  if (DefInit *Init = dyn_cast<DefInit>(OutDI->getOperator())) {
35    if (Init->getDef()->getName() != "outs")
36      PrintFatalError(R->getLoc(),
37                      R->getName() +
38                          ": invalid def name for output list: use 'outs'");
39  } else
40    PrintFatalError(R->getLoc(),
41                    R->getName() + ": invalid output list: use 'outs'");
42
43  NumDefs = OutDI->getNumArgs();
44
45  DagInit *InDI = R->getValueAsDag("InOperandList");
46  if (DefInit *Init = dyn_cast<DefInit>(InDI->getOperator())) {
47    if (Init->getDef()->getName() != "ins")
48      PrintFatalError(R->getLoc(),
49                      R->getName() +
50                          ": invalid def name for input list: use 'ins'");
51  } else
52    PrintFatalError(R->getLoc(),
53                    R->getName() + ": invalid input list: use 'ins'");
54
55  unsigned MIOperandNo = 0;
56  std::set<std::string> OperandNames;
57  unsigned e = InDI->getNumArgs() + OutDI->getNumArgs();
58  OperandList.reserve(e);
59  bool VariadicOuts = false;
60  for (unsigned i = 0; i != e; ++i){
61    Init *ArgInit;
62    StringRef ArgName;
63    if (i < NumDefs) {
64      ArgInit = OutDI->getArg(i);
65      ArgName = OutDI->getArgNameStr(i);
66    } else {
67      ArgInit = InDI->getArg(i-NumDefs);
68      ArgName = InDI->getArgNameStr(i-NumDefs);
69    }
70
71    DefInit *Arg = dyn_cast<DefInit>(ArgInit);
72    if (!Arg)
73      PrintFatalError(R->getLoc(), "Illegal operand for the '" + R->getName() +
74                                       "' instruction!");
75
76    Record *Rec = Arg->getDef();
77    std::string PrintMethod = "printOperand";
78    std::string EncoderMethod;
79    std::string OperandType = "OPERAND_UNKNOWN";
80    std::string OperandNamespace = "MCOI";
81    unsigned NumOps = 1;
82    DagInit *MIOpInfo = nullptr;
83    if (Rec->isSubClassOf("RegisterOperand")) {
84      PrintMethod = std::string(Rec->getValueAsString("PrintMethod"));
85      OperandType = std::string(Rec->getValueAsString("OperandType"));
86      OperandNamespace = std::string(Rec->getValueAsString("OperandNamespace"));
87      EncoderMethod = std::string(Rec->getValueAsString("EncoderMethod"));
88    } else if (Rec->isSubClassOf("Operand")) {
89      PrintMethod = std::string(Rec->getValueAsString("PrintMethod"));
90      OperandType = std::string(Rec->getValueAsString("OperandType"));
91      OperandNamespace = std::string(Rec->getValueAsString("OperandNamespace"));
92      // If there is an explicit encoder method, use it.
93      EncoderMethod = std::string(Rec->getValueAsString("EncoderMethod"));
94      MIOpInfo = Rec->getValueAsDag("MIOperandInfo");
95
96      // Verify that MIOpInfo has an 'ops' root value.
97      if (!isa<DefInit>(MIOpInfo->getOperator()) ||
98          cast<DefInit>(MIOpInfo->getOperator())->getDef()->getName() != "ops")
99        PrintFatalError(R->getLoc(),
100                        "Bad value for MIOperandInfo in operand '" +
101                            Rec->getName() + "'\n");
102
103      // If we have MIOpInfo, then we have #operands equal to number of entries
104      // in MIOperandInfo.
105      if (unsigned NumArgs = MIOpInfo->getNumArgs())
106        NumOps = NumArgs;
107
108      if (Rec->isSubClassOf("PredicateOp"))
109        isPredicable = true;
110      else if (Rec->isSubClassOf("OptionalDefOperand"))
111        hasOptionalDef = true;
112    } else if (Rec->getName() == "variable_ops") {
113      if (i < NumDefs)
114        VariadicOuts = true;
115      isVariadic = true;
116      continue;
117    } else if (Rec->isSubClassOf("RegisterClass")) {
118      OperandType = "OPERAND_REGISTER";
119    } else if (!Rec->isSubClassOf("PointerLikeRegClass") &&
120               !Rec->isSubClassOf("unknown_class"))
121      PrintFatalError(R->getLoc(), "Unknown operand class '" + Rec->getName() +
122                                       "' in '" + R->getName() +
123                                       "' instruction!");
124
125    // Check that the operand has a name and that it's unique.
126    if (ArgName.empty())
127      PrintFatalError(R->getLoc(), "In instruction '" + R->getName() +
128                                       "', operand #" + Twine(i) +
129                                       " has no name!");
130    if (!OperandNames.insert(std::string(ArgName)).second)
131      PrintFatalError(R->getLoc(),
132                      "In instruction '" + R->getName() + "', operand #" +
133                          Twine(i) +
134                          " has the same name as a previous operand!");
135
136    OperandList.emplace_back(
137        Rec, std::string(ArgName), std::string(PrintMethod),
138        std::string(EncoderMethod), OperandNamespace + "::" + OperandType,
139        MIOperandNo, NumOps, MIOpInfo);
140    MIOperandNo += NumOps;
141  }
142
143  if (VariadicOuts)
144    --NumDefs;
145
146  // Make sure the constraints list for each operand is large enough to hold
147  // constraint info, even if none is present.
148  for (OperandInfo &OpInfo : OperandList)
149    OpInfo.Constraints.resize(OpInfo.MINumOperands);
150}
151
152
153/// getOperandNamed - Return the index of the operand with the specified
154/// non-empty name.  If the instruction does not have an operand with the
155/// specified name, abort.
156///
157unsigned CGIOperandList::getOperandNamed(StringRef Name) const {
158  unsigned OpIdx;
159  if (hasOperandNamed(Name, OpIdx))
160    return OpIdx;
161  PrintFatalError(TheDef->getLoc(), "'" + TheDef->getName() +
162                                        "' does not have an operand named '$" +
163                                        Name + "'!");
164}
165
166/// hasOperandNamed - Query whether the instruction has an operand of the
167/// given name. If so, return true and set OpIdx to the index of the
168/// operand. Otherwise, return false.
169bool CGIOperandList::hasOperandNamed(StringRef Name, unsigned &OpIdx) const {
170  assert(!Name.empty() && "Cannot search for operand with no name!");
171  for (unsigned i = 0, e = OperandList.size(); i != e; ++i)
172    if (OperandList[i].Name == Name) {
173      OpIdx = i;
174      return true;
175    }
176  return false;
177}
178
179std::pair<unsigned,unsigned>
180CGIOperandList::ParseOperandName(const std::string &Op, bool AllowWholeOp) {
181  if (Op.empty() || Op[0] != '$')
182    PrintFatalError(TheDef->getLoc(),
183                    TheDef->getName() + ": Illegal operand name: '" + Op + "'");
184
185  std::string OpName = Op.substr(1);
186  std::string SubOpName;
187
188  // Check to see if this is $foo.bar.
189  std::string::size_type DotIdx = OpName.find_first_of('.');
190  if (DotIdx != std::string::npos) {
191    SubOpName = OpName.substr(DotIdx+1);
192    if (SubOpName.empty())
193      PrintFatalError(TheDef->getLoc(),
194                      TheDef->getName() +
195                          ": illegal empty suboperand name in '" + Op + "'");
196    OpName = OpName.substr(0, DotIdx);
197  }
198
199  unsigned OpIdx = getOperandNamed(OpName);
200
201  if (SubOpName.empty()) {  // If no suboperand name was specified:
202    // If one was needed, throw.
203    if (OperandList[OpIdx].MINumOperands > 1 && !AllowWholeOp &&
204        SubOpName.empty())
205      PrintFatalError(TheDef->getLoc(),
206                      TheDef->getName() +
207                          ": Illegal to refer to"
208                          " whole operand part of complex operand '" +
209                          Op + "'");
210
211    // Otherwise, return the operand.
212    return std::make_pair(OpIdx, 0U);
213  }
214
215  // Find the suboperand number involved.
216  DagInit *MIOpInfo = OperandList[OpIdx].MIOperandInfo;
217  if (!MIOpInfo)
218    PrintFatalError(TheDef->getLoc(), TheDef->getName() +
219                                          ": unknown suboperand name in '" +
220                                          Op + "'");
221
222  // Find the operand with the right name.
223  for (unsigned i = 0, e = MIOpInfo->getNumArgs(); i != e; ++i)
224    if (MIOpInfo->getArgNameStr(i) == SubOpName)
225      return std::make_pair(OpIdx, i);
226
227  // Otherwise, didn't find it!
228  PrintFatalError(TheDef->getLoc(), TheDef->getName() +
229                                        ": unknown suboperand name in '" + Op +
230                                        "'");
231  return std::make_pair(0U, 0U);
232}
233
234static void ParseConstraint(const std::string &CStr, CGIOperandList &Ops,
235                            Record *Rec) {
236  // EARLY_CLOBBER: @early $reg
237  std::string::size_type wpos = CStr.find_first_of(" \t");
238  std::string::size_type start = CStr.find_first_not_of(" \t");
239  std::string Tok = CStr.substr(start, wpos - start);
240  if (Tok == "@earlyclobber") {
241    std::string Name = CStr.substr(wpos+1);
242    wpos = Name.find_first_not_of(" \t");
243    if (wpos == std::string::npos)
244      PrintFatalError(
245        Rec->getLoc(), "Illegal format for @earlyclobber constraint in '" +
246        Rec->getName() + "': '" + CStr + "'");
247    Name = Name.substr(wpos);
248    std::pair<unsigned,unsigned> Op = Ops.ParseOperandName(Name, false);
249
250    // Build the string for the operand
251    if (!Ops[Op.first].Constraints[Op.second].isNone())
252      PrintFatalError(
253        Rec->getLoc(), "Operand '" + Name + "' of '" + Rec->getName() +
254        "' cannot have multiple constraints!");
255    Ops[Op.first].Constraints[Op.second] =
256    CGIOperandList::ConstraintInfo::getEarlyClobber();
257    return;
258  }
259
260  // Only other constraint is "TIED_TO" for now.
261  std::string::size_type pos = CStr.find_first_of('=');
262  if (pos == std::string::npos)
263    PrintFatalError(
264      Rec->getLoc(), "Unrecognized constraint '" + CStr +
265      "' in '" + Rec->getName() + "'");
266  start = CStr.find_first_not_of(" \t");
267
268  // TIED_TO: $src1 = $dst
269  wpos = CStr.find_first_of(" \t", start);
270  if (wpos == std::string::npos || wpos > pos)
271    PrintFatalError(
272      Rec->getLoc(), "Illegal format for tied-to constraint in '" +
273      Rec->getName() + "': '" + CStr + "'");
274  std::string LHSOpName =
275      std::string(StringRef(CStr).substr(start, wpos - start));
276  std::pair<unsigned,unsigned> LHSOp = Ops.ParseOperandName(LHSOpName, false);
277
278  wpos = CStr.find_first_not_of(" \t", pos + 1);
279  if (wpos == std::string::npos)
280    PrintFatalError(
281      Rec->getLoc(), "Illegal format for tied-to constraint: '" + CStr + "'");
282
283  std::string RHSOpName = std::string(StringRef(CStr).substr(wpos));
284  std::pair<unsigned,unsigned> RHSOp = Ops.ParseOperandName(RHSOpName, false);
285
286  // Sort the operands into order, which should put the output one
287  // first. But keep the original order, for use in diagnostics.
288  bool FirstIsDest = (LHSOp < RHSOp);
289  std::pair<unsigned,unsigned> DestOp = (FirstIsDest ? LHSOp : RHSOp);
290  StringRef DestOpName = (FirstIsDest ? LHSOpName : RHSOpName);
291  std::pair<unsigned,unsigned> SrcOp = (FirstIsDest ? RHSOp : LHSOp);
292  StringRef SrcOpName = (FirstIsDest ? RHSOpName : LHSOpName);
293
294  // Ensure one operand is a def and the other is a use.
295  if (DestOp.first >= Ops.NumDefs)
296    PrintFatalError(
297      Rec->getLoc(), "Input operands '" + LHSOpName + "' and '" + RHSOpName +
298      "' of '" + Rec->getName() + "' cannot be tied!");
299  if (SrcOp.first < Ops.NumDefs)
300    PrintFatalError(
301      Rec->getLoc(), "Output operands '" + LHSOpName + "' and '" + RHSOpName +
302      "' of '" + Rec->getName() + "' cannot be tied!");
303
304  // The constraint has to go on the operand with higher index, i.e.
305  // the source one. Check there isn't another constraint there
306  // already.
307  if (!Ops[SrcOp.first].Constraints[SrcOp.second].isNone())
308    PrintFatalError(
309      Rec->getLoc(), "Operand '" + SrcOpName + "' of '" + Rec->getName() +
310      "' cannot have multiple constraints!");
311
312  unsigned DestFlatOpNo = Ops.getFlattenedOperandNumber(DestOp);
313  auto NewConstraint = CGIOperandList::ConstraintInfo::getTied(DestFlatOpNo);
314
315  // Check that the earlier operand is not the target of another tie
316  // before making it the target of this one.
317  for (const CGIOperandList::OperandInfo &Op : Ops) {
318    for (unsigned i = 0; i < Op.MINumOperands; i++)
319      if (Op.Constraints[i] == NewConstraint)
320        PrintFatalError(
321          Rec->getLoc(), "Operand '" + DestOpName + "' of '" + Rec->getName() +
322          "' cannot have multiple operands tied to it!");
323  }
324
325  Ops[SrcOp.first].Constraints[SrcOp.second] = NewConstraint;
326}
327
328static void ParseConstraints(const std::string &CStr, CGIOperandList &Ops,
329                             Record *Rec) {
330  if (CStr.empty()) return;
331
332  const std::string delims(",");
333  std::string::size_type bidx, eidx;
334
335  bidx = CStr.find_first_not_of(delims);
336  while (bidx != std::string::npos) {
337    eidx = CStr.find_first_of(delims, bidx);
338    if (eidx == std::string::npos)
339      eidx = CStr.length();
340
341    ParseConstraint(CStr.substr(bidx, eidx - bidx), Ops, Rec);
342    bidx = CStr.find_first_not_of(delims, eidx);
343  }
344}
345
346void CGIOperandList::ProcessDisableEncoding(std::string DisableEncoding) {
347  while (1) {
348    std::pair<StringRef, StringRef> P = getToken(DisableEncoding, " ,\t");
349    std::string OpName = std::string(P.first);
350    DisableEncoding = std::string(P.second);
351    if (OpName.empty()) break;
352
353    // Figure out which operand this is.
354    std::pair<unsigned,unsigned> Op = ParseOperandName(OpName, false);
355
356    // Mark the operand as not-to-be encoded.
357    if (Op.second >= OperandList[Op.first].DoNotEncode.size())
358      OperandList[Op.first].DoNotEncode.resize(Op.second+1);
359    OperandList[Op.first].DoNotEncode[Op.second] = true;
360  }
361
362}
363
364//===----------------------------------------------------------------------===//
365// CodeGenInstruction Implementation
366//===----------------------------------------------------------------------===//
367
368CodeGenInstruction::CodeGenInstruction(Record *R)
369  : TheDef(R), Operands(R), InferredFrom(nullptr) {
370  Namespace = R->getValueAsString("Namespace");
371  AsmString = std::string(R->getValueAsString("AsmString"));
372
373  isPreISelOpcode = R->getValueAsBit("isPreISelOpcode");
374  isReturn     = R->getValueAsBit("isReturn");
375  isEHScopeReturn = R->getValueAsBit("isEHScopeReturn");
376  isBranch     = R->getValueAsBit("isBranch");
377  isIndirectBranch = R->getValueAsBit("isIndirectBranch");
378  isCompare    = R->getValueAsBit("isCompare");
379  isMoveImm    = R->getValueAsBit("isMoveImm");
380  isMoveReg    = R->getValueAsBit("isMoveReg");
381  isBitcast    = R->getValueAsBit("isBitcast");
382  isSelect     = R->getValueAsBit("isSelect");
383  isBarrier    = R->getValueAsBit("isBarrier");
384  isCall       = R->getValueAsBit("isCall");
385  isAdd        = R->getValueAsBit("isAdd");
386  isTrap       = R->getValueAsBit("isTrap");
387  canFoldAsLoad = R->getValueAsBit("canFoldAsLoad");
388  isPredicable = !R->getValueAsBit("isUnpredicable") && (
389      Operands.isPredicable || R->getValueAsBit("isPredicable"));
390  isConvertibleToThreeAddress = R->getValueAsBit("isConvertibleToThreeAddress");
391  isCommutable = R->getValueAsBit("isCommutable");
392  isTerminator = R->getValueAsBit("isTerminator");
393  isReMaterializable = R->getValueAsBit("isReMaterializable");
394  hasDelaySlot = R->getValueAsBit("hasDelaySlot");
395  usesCustomInserter = R->getValueAsBit("usesCustomInserter");
396  hasPostISelHook = R->getValueAsBit("hasPostISelHook");
397  hasCtrlDep   = R->getValueAsBit("hasCtrlDep");
398  isNotDuplicable = R->getValueAsBit("isNotDuplicable");
399  isRegSequence = R->getValueAsBit("isRegSequence");
400  isExtractSubreg = R->getValueAsBit("isExtractSubreg");
401  isInsertSubreg = R->getValueAsBit("isInsertSubreg");
402  isConvergent = R->getValueAsBit("isConvergent");
403  hasNoSchedulingInfo = R->getValueAsBit("hasNoSchedulingInfo");
404  FastISelShouldIgnore = R->getValueAsBit("FastISelShouldIgnore");
405  variadicOpsAreDefs = R->getValueAsBit("variadicOpsAreDefs");
406  isAuthenticated = R->getValueAsBit("isAuthenticated");
407
408  bool Unset;
409  mayLoad      = R->getValueAsBitOrUnset("mayLoad", Unset);
410  mayLoad_Unset = Unset;
411  mayStore     = R->getValueAsBitOrUnset("mayStore", Unset);
412  mayStore_Unset = Unset;
413  mayRaiseFPException = R->getValueAsBit("mayRaiseFPException");
414  hasSideEffects = R->getValueAsBitOrUnset("hasSideEffects", Unset);
415  hasSideEffects_Unset = Unset;
416
417  isAsCheapAsAMove = R->getValueAsBit("isAsCheapAsAMove");
418  hasExtraSrcRegAllocReq = R->getValueAsBit("hasExtraSrcRegAllocReq");
419  hasExtraDefRegAllocReq = R->getValueAsBit("hasExtraDefRegAllocReq");
420  isCodeGenOnly = R->getValueAsBit("isCodeGenOnly");
421  isPseudo = R->getValueAsBit("isPseudo");
422  ImplicitDefs = R->getValueAsListOfDefs("Defs");
423  ImplicitUses = R->getValueAsListOfDefs("Uses");
424
425  // This flag is only inferred from the pattern.
426  hasChain = false;
427  hasChain_Inferred = false;
428
429  // Parse Constraints.
430  ParseConstraints(std::string(R->getValueAsString("Constraints")), Operands,
431                   R);
432
433  // Parse the DisableEncoding field.
434  Operands.ProcessDisableEncoding(
435      std::string(R->getValueAsString("DisableEncoding")));
436
437  // First check for a ComplexDeprecationPredicate.
438  if (R->getValue("ComplexDeprecationPredicate")) {
439    HasComplexDeprecationPredicate = true;
440    DeprecatedReason =
441        std::string(R->getValueAsString("ComplexDeprecationPredicate"));
442  } else if (RecordVal *Dep = R->getValue("DeprecatedFeatureMask")) {
443    // Check if we have a Subtarget feature mask.
444    HasComplexDeprecationPredicate = false;
445    DeprecatedReason = Dep->getValue()->getAsString();
446  } else {
447    // This instruction isn't deprecated.
448    HasComplexDeprecationPredicate = false;
449    DeprecatedReason = "";
450  }
451}
452
453/// HasOneImplicitDefWithKnownVT - If the instruction has at least one
454/// implicit def and it has a known VT, return the VT, otherwise return
455/// MVT::Other.
456MVT::SimpleValueType CodeGenInstruction::
457HasOneImplicitDefWithKnownVT(const CodeGenTarget &TargetInfo) const {
458  if (ImplicitDefs.empty()) return MVT::Other;
459
460  // Check to see if the first implicit def has a resolvable type.
461  Record *FirstImplicitDef = ImplicitDefs[0];
462  assert(FirstImplicitDef->isSubClassOf("Register"));
463  const std::vector<ValueTypeByHwMode> &RegVTs =
464    TargetInfo.getRegisterVTs(FirstImplicitDef);
465  if (RegVTs.size() == 1 && RegVTs[0].isSimple())
466    return RegVTs[0].getSimple().SimpleTy;
467  return MVT::Other;
468}
469
470
471/// FlattenAsmStringVariants - Flatten the specified AsmString to only
472/// include text from the specified variant, returning the new string.
473std::string CodeGenInstruction::
474FlattenAsmStringVariants(StringRef Cur, unsigned Variant) {
475  std::string Res = "";
476
477  for (;;) {
478    // Find the start of the next variant string.
479    size_t VariantsStart = 0;
480    for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)
481      if (Cur[VariantsStart] == '{' &&
482          (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
483                                  Cur[VariantsStart-1] != '\\')))
484        break;
485
486    // Add the prefix to the result.
487    Res += Cur.slice(0, VariantsStart);
488    if (VariantsStart == Cur.size())
489      break;
490
491    ++VariantsStart; // Skip the '{'.
492
493    // Scan to the end of the variants string.
494    size_t VariantsEnd = VariantsStart;
495    unsigned NestedBraces = 1;
496    for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {
497      if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
498        if (--NestedBraces == 0)
499          break;
500      } else if (Cur[VariantsEnd] == '{')
501        ++NestedBraces;
502    }
503
504    // Select the Nth variant (or empty).
505    StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
506    for (unsigned i = 0; i != Variant; ++i)
507      Selection = Selection.split('|').second;
508    Res += Selection.split('|').first;
509
510    assert(VariantsEnd != Cur.size() &&
511           "Unterminated variants in assembly string!");
512    Cur = Cur.substr(VariantsEnd + 1);
513  }
514
515  return Res;
516}
517
518bool CodeGenInstruction::isOperandImpl(unsigned i,
519                                       StringRef PropertyName) const {
520  DagInit *ConstraintList = TheDef->getValueAsDag("InOperandList");
521  if (!ConstraintList || i >= ConstraintList->getNumArgs())
522    return false;
523
524  DefInit *Constraint = dyn_cast<DefInit>(ConstraintList->getArg(i));
525  if (!Constraint)
526    return false;
527
528  return Constraint->getDef()->isSubClassOf("TypedOperand") &&
529         Constraint->getDef()->getValueAsBit(PropertyName);
530}
531
532//===----------------------------------------------------------------------===//
533/// CodeGenInstAlias Implementation
534//===----------------------------------------------------------------------===//
535
536/// tryAliasOpMatch - This is a helper function for the CodeGenInstAlias
537/// constructor.  It checks if an argument in an InstAlias pattern matches
538/// the corresponding operand of the instruction.  It returns true on a
539/// successful match, with ResOp set to the result operand to be used.
540bool CodeGenInstAlias::tryAliasOpMatch(DagInit *Result, unsigned AliasOpNo,
541                                       Record *InstOpRec, bool hasSubOps,
542                                       ArrayRef<SMLoc> Loc, CodeGenTarget &T,
543                                       ResultOperand &ResOp) {
544  Init *Arg = Result->getArg(AliasOpNo);
545  DefInit *ADI = dyn_cast<DefInit>(Arg);
546  Record *ResultRecord = ADI ? ADI->getDef() : nullptr;
547
548  if (ADI && ADI->getDef() == InstOpRec) {
549    // If the operand is a record, it must have a name, and the record type
550    // must match up with the instruction's argument type.
551    if (!Result->getArgName(AliasOpNo))
552      PrintFatalError(Loc, "result argument #" + Twine(AliasOpNo) +
553                           " must have a name!");
554    ResOp = ResultOperand(std::string(Result->getArgNameStr(AliasOpNo)),
555                          ResultRecord);
556    return true;
557  }
558
559  // For register operands, the source register class can be a subclass
560  // of the instruction register class, not just an exact match.
561  if (InstOpRec->isSubClassOf("RegisterOperand"))
562    InstOpRec = InstOpRec->getValueAsDef("RegClass");
563
564  if (ADI && ADI->getDef()->isSubClassOf("RegisterOperand"))
565    ADI = ADI->getDef()->getValueAsDef("RegClass")->getDefInit();
566
567  if (ADI && ADI->getDef()->isSubClassOf("RegisterClass")) {
568    if (!InstOpRec->isSubClassOf("RegisterClass"))
569      return false;
570    if (!T.getRegisterClass(InstOpRec)
571              .hasSubClass(&T.getRegisterClass(ADI->getDef())))
572      return false;
573    ResOp = ResultOperand(std::string(Result->getArgNameStr(AliasOpNo)),
574                          ResultRecord);
575    return true;
576  }
577
578  // Handle explicit registers.
579  if (ADI && ADI->getDef()->isSubClassOf("Register")) {
580    if (InstOpRec->isSubClassOf("OptionalDefOperand")) {
581      DagInit *DI = InstOpRec->getValueAsDag("MIOperandInfo");
582      // The operand info should only have a single (register) entry. We
583      // want the register class of it.
584      InstOpRec = cast<DefInit>(DI->getArg(0))->getDef();
585    }
586
587    if (!InstOpRec->isSubClassOf("RegisterClass"))
588      return false;
589
590    if (!T.getRegisterClass(InstOpRec)
591        .contains(T.getRegBank().getReg(ADI->getDef())))
592      PrintFatalError(Loc, "fixed register " + ADI->getDef()->getName() +
593                      " is not a member of the " + InstOpRec->getName() +
594                      " register class!");
595
596    if (Result->getArgName(AliasOpNo))
597      PrintFatalError(Loc, "result fixed register argument must "
598                      "not have a name!");
599
600    ResOp = ResultOperand(ResultRecord);
601    return true;
602  }
603
604  // Handle "zero_reg" for optional def operands.
605  if (ADI && ADI->getDef()->getName() == "zero_reg") {
606
607    // Check if this is an optional def.
608    // Tied operands where the source is a sub-operand of a complex operand
609    // need to represent both operands in the alias destination instruction.
610    // Allow zero_reg for the tied portion. This can and should go away once
611    // the MC representation of things doesn't use tied operands at all.
612    //if (!InstOpRec->isSubClassOf("OptionalDefOperand"))
613    //  throw TGError(Loc, "reg0 used for result that is not an "
614    //                "OptionalDefOperand!");
615
616    ResOp = ResultOperand(static_cast<Record*>(nullptr));
617    return true;
618  }
619
620  // Literal integers.
621  if (IntInit *II = dyn_cast<IntInit>(Arg)) {
622    if (hasSubOps || !InstOpRec->isSubClassOf("Operand"))
623      return false;
624    // Integer arguments can't have names.
625    if (Result->getArgName(AliasOpNo))
626      PrintFatalError(Loc, "result argument #" + Twine(AliasOpNo) +
627                      " must not have a name!");
628    ResOp = ResultOperand(II->getValue());
629    return true;
630  }
631
632  // Bits<n> (also used for 0bxx literals)
633  if (BitsInit *BI = dyn_cast<BitsInit>(Arg)) {
634    if (hasSubOps || !InstOpRec->isSubClassOf("Operand"))
635      return false;
636    if (!BI->isComplete())
637      return false;
638    // Convert the bits init to an integer and use that for the result.
639    IntInit *II =
640      dyn_cast_or_null<IntInit>(BI->convertInitializerTo(IntRecTy::get()));
641    if (!II)
642      return false;
643    ResOp = ResultOperand(II->getValue());
644    return true;
645  }
646
647  // If both are Operands with the same MVT, allow the conversion. It's
648  // up to the user to make sure the values are appropriate, just like
649  // for isel Pat's.
650  if (InstOpRec->isSubClassOf("Operand") && ADI &&
651      ADI->getDef()->isSubClassOf("Operand")) {
652    // FIXME: What other attributes should we check here? Identical
653    // MIOperandInfo perhaps?
654    if (InstOpRec->getValueInit("Type") != ADI->getDef()->getValueInit("Type"))
655      return false;
656    ResOp = ResultOperand(std::string(Result->getArgNameStr(AliasOpNo)),
657                          ADI->getDef());
658    return true;
659  }
660
661  return false;
662}
663
664unsigned CodeGenInstAlias::ResultOperand::getMINumOperands() const {
665  if (!isRecord())
666    return 1;
667
668  Record *Rec = getRecord();
669  if (!Rec->isSubClassOf("Operand"))
670    return 1;
671
672  DagInit *MIOpInfo = Rec->getValueAsDag("MIOperandInfo");
673  if (MIOpInfo->getNumArgs() == 0) {
674    // Unspecified, so it defaults to 1
675    return 1;
676  }
677
678  return MIOpInfo->getNumArgs();
679}
680
681CodeGenInstAlias::CodeGenInstAlias(Record *R, CodeGenTarget &T)
682    : TheDef(R) {
683  Result = R->getValueAsDag("ResultInst");
684  AsmString = std::string(R->getValueAsString("AsmString"));
685
686  // Verify that the root of the result is an instruction.
687  DefInit *DI = dyn_cast<DefInit>(Result->getOperator());
688  if (!DI || !DI->getDef()->isSubClassOf("Instruction"))
689    PrintFatalError(R->getLoc(),
690                    "result of inst alias should be an instruction");
691
692  ResultInst = &T.getInstruction(DI->getDef());
693
694  // NameClass - If argument names are repeated, we need to verify they have
695  // the same class.
696  StringMap<Record*> NameClass;
697  for (unsigned i = 0, e = Result->getNumArgs(); i != e; ++i) {
698    DefInit *ADI = dyn_cast<DefInit>(Result->getArg(i));
699    if (!ADI || !Result->getArgName(i))
700      continue;
701    // Verify we don't have something like: (someinst GR16:$foo, GR32:$foo)
702    // $foo can exist multiple times in the result list, but it must have the
703    // same type.
704    Record *&Entry = NameClass[Result->getArgNameStr(i)];
705    if (Entry && Entry != ADI->getDef())
706      PrintFatalError(R->getLoc(), "result value $" + Result->getArgNameStr(i) +
707                      " is both " + Entry->getName() + " and " +
708                      ADI->getDef()->getName() + "!");
709    Entry = ADI->getDef();
710  }
711
712  // Decode and validate the arguments of the result.
713  unsigned AliasOpNo = 0;
714  for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
715
716    // Tied registers don't have an entry in the result dag unless they're part
717    // of a complex operand, in which case we include them anyways, as we
718    // don't have any other way to specify the whole operand.
719    if (ResultInst->Operands[i].MINumOperands == 1 &&
720        ResultInst->Operands[i].getTiedRegister() != -1) {
721      // Tied operands of different RegisterClass should be explicit within an
722      // instruction's syntax and so cannot be skipped.
723      int TiedOpNum = ResultInst->Operands[i].getTiedRegister();
724      if (ResultInst->Operands[i].Rec->getName() ==
725          ResultInst->Operands[TiedOpNum].Rec->getName())
726        continue;
727    }
728
729    if (AliasOpNo >= Result->getNumArgs())
730      PrintFatalError(R->getLoc(), "not enough arguments for instruction!");
731
732    Record *InstOpRec = ResultInst->Operands[i].Rec;
733    unsigned NumSubOps = ResultInst->Operands[i].MINumOperands;
734    ResultOperand ResOp(static_cast<int64_t>(0));
735    if (tryAliasOpMatch(Result, AliasOpNo, InstOpRec, (NumSubOps > 1),
736                        R->getLoc(), T, ResOp)) {
737      // If this is a simple operand, or a complex operand with a custom match
738      // class, then we can match is verbatim.
739      if (NumSubOps == 1 ||
740          (InstOpRec->getValue("ParserMatchClass") &&
741           InstOpRec->getValueAsDef("ParserMatchClass")
742             ->getValueAsString("Name") != "Imm")) {
743        ResultOperands.push_back(ResOp);
744        ResultInstOperandIndex.push_back(std::make_pair(i, -1));
745        ++AliasOpNo;
746
747      // Otherwise, we need to match each of the suboperands individually.
748      } else {
749         DagInit *MIOI = ResultInst->Operands[i].MIOperandInfo;
750         for (unsigned SubOp = 0; SubOp != NumSubOps; ++SubOp) {
751          Record *SubRec = cast<DefInit>(MIOI->getArg(SubOp))->getDef();
752
753          // Take care to instantiate each of the suboperands with the correct
754          // nomenclature: $foo.bar
755          ResultOperands.emplace_back(
756            Result->getArgName(AliasOpNo)->getAsUnquotedString() + "." +
757            MIOI->getArgName(SubOp)->getAsUnquotedString(), SubRec);
758          ResultInstOperandIndex.push_back(std::make_pair(i, SubOp));
759         }
760         ++AliasOpNo;
761      }
762      continue;
763    }
764
765    // If the argument did not match the instruction operand, and the operand
766    // is composed of multiple suboperands, try matching the suboperands.
767    if (NumSubOps > 1) {
768      DagInit *MIOI = ResultInst->Operands[i].MIOperandInfo;
769      for (unsigned SubOp = 0; SubOp != NumSubOps; ++SubOp) {
770        if (AliasOpNo >= Result->getNumArgs())
771          PrintFatalError(R->getLoc(), "not enough arguments for instruction!");
772        Record *SubRec = cast<DefInit>(MIOI->getArg(SubOp))->getDef();
773        if (tryAliasOpMatch(Result, AliasOpNo, SubRec, false,
774                            R->getLoc(), T, ResOp)) {
775          ResultOperands.push_back(ResOp);
776          ResultInstOperandIndex.push_back(std::make_pair(i, SubOp));
777          ++AliasOpNo;
778        } else {
779          PrintFatalError(R->getLoc(), "result argument #" + Twine(AliasOpNo) +
780                        " does not match instruction operand class " +
781                        (SubOp == 0 ? InstOpRec->getName() :SubRec->getName()));
782        }
783      }
784      continue;
785    }
786    PrintFatalError(R->getLoc(), "result argument #" + Twine(AliasOpNo) +
787                    " does not match instruction operand class " +
788                    InstOpRec->getName());
789  }
790
791  if (AliasOpNo != Result->getNumArgs())
792    PrintFatalError(R->getLoc(), "too many operands for instruction!");
793}
794