Home | History | Annotate | Line # | Download | only in TableGen
      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>
     21 using namespace llvm;
     22 
     23 //===----------------------------------------------------------------------===//
     24 // CGIOperandList Implementation
     25 //===----------------------------------------------------------------------===//
     26 
     27 CGIOperandList::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 ///
    157 unsigned 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.
    169 bool 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 
    179 std::pair<unsigned,unsigned>
    180 CGIOperandList::ParseOperandName(StringRef Op, bool AllowWholeOp) {
    181   if (Op.empty() || Op[0] != '$')
    182     PrintFatalError(TheDef->getLoc(),
    183                     TheDef->getName() + ": Illegal operand name: '" + Op + "'");
    184 
    185   StringRef OpName = Op.substr(1);
    186   StringRef SubOpName;
    187 
    188   // Check to see if this is $foo.bar.
    189   StringRef::size_type DotIdx = OpName.find_first_of('.');
    190   if (DotIdx != StringRef::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 
    234 static void ParseConstraint(StringRef CStr, CGIOperandList &Ops,
    235                             Record *Rec) {
    236   // EARLY_CLOBBER: @early $reg
    237   StringRef::size_type wpos = CStr.find_first_of(" \t");
    238   StringRef::size_type start = CStr.find_first_not_of(" \t");
    239   StringRef Tok = CStr.substr(start, wpos - start);
    240   if (Tok == "@earlyclobber") {
    241     StringRef Name = CStr.substr(wpos+1);
    242     wpos = Name.find_first_not_of(" \t");
    243     if (wpos == StringRef::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   StringRef::size_type pos = CStr.find_first_of('=');
    262   if (pos == StringRef::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 == StringRef::npos || wpos > pos)
    271     PrintFatalError(
    272       Rec->getLoc(), "Illegal format for tied-to constraint in '" +
    273       Rec->getName() + "': '" + CStr + "'");
    274   StringRef LHSOpName = CStr.substr(start, wpos - start);
    275   std::pair<unsigned,unsigned> LHSOp = Ops.ParseOperandName(LHSOpName, false);
    276 
    277   wpos = CStr.find_first_not_of(" \t", pos + 1);
    278   if (wpos == StringRef::npos)
    279     PrintFatalError(
    280       Rec->getLoc(), "Illegal format for tied-to constraint: '" + CStr + "'");
    281 
    282   StringRef RHSOpName = CStr.substr(wpos);
    283   std::pair<unsigned,unsigned> RHSOp = Ops.ParseOperandName(RHSOpName, false);
    284 
    285   // Sort the operands into order, which should put the output one
    286   // first. But keep the original order, for use in diagnostics.
    287   bool FirstIsDest = (LHSOp < RHSOp);
    288   std::pair<unsigned,unsigned> DestOp = (FirstIsDest ? LHSOp : RHSOp);
    289   StringRef DestOpName = (FirstIsDest ? LHSOpName : RHSOpName);
    290   std::pair<unsigned,unsigned> SrcOp = (FirstIsDest ? RHSOp : LHSOp);
    291   StringRef SrcOpName = (FirstIsDest ? RHSOpName : LHSOpName);
    292 
    293   // Ensure one operand is a def and the other is a use.
    294   if (DestOp.first >= Ops.NumDefs)
    295     PrintFatalError(
    296       Rec->getLoc(), "Input operands '" + LHSOpName + "' and '" + RHSOpName +
    297       "' of '" + Rec->getName() + "' cannot be tied!");
    298   if (SrcOp.first < Ops.NumDefs)
    299     PrintFatalError(
    300       Rec->getLoc(), "Output operands '" + LHSOpName + "' and '" + RHSOpName +
    301       "' of '" + Rec->getName() + "' cannot be tied!");
    302 
    303   // The constraint has to go on the operand with higher index, i.e.
    304   // the source one. Check there isn't another constraint there
    305   // already.
    306   if (!Ops[SrcOp.first].Constraints[SrcOp.second].isNone())
    307     PrintFatalError(
    308       Rec->getLoc(), "Operand '" + SrcOpName + "' of '" + Rec->getName() +
    309       "' cannot have multiple constraints!");
    310 
    311   unsigned DestFlatOpNo = Ops.getFlattenedOperandNumber(DestOp);
    312   auto NewConstraint = CGIOperandList::ConstraintInfo::getTied(DestFlatOpNo);
    313 
    314   // Check that the earlier operand is not the target of another tie
    315   // before making it the target of this one.
    316   for (const CGIOperandList::OperandInfo &Op : Ops) {
    317     for (unsigned i = 0; i < Op.MINumOperands; i++)
    318       if (Op.Constraints[i] == NewConstraint)
    319         PrintFatalError(
    320           Rec->getLoc(), "Operand '" + DestOpName + "' of '" + Rec->getName() +
    321           "' cannot have multiple operands tied to it!");
    322   }
    323 
    324   Ops[SrcOp.first].Constraints[SrcOp.second] = NewConstraint;
    325 }
    326 
    327 static void ParseConstraints(StringRef CStr, CGIOperandList &Ops, Record *Rec) {
    328   if (CStr.empty()) return;
    329 
    330   StringRef delims(",");
    331   StringRef::size_type bidx, eidx;
    332 
    333   bidx = CStr.find_first_not_of(delims);
    334   while (bidx != StringRef::npos) {
    335     eidx = CStr.find_first_of(delims, bidx);
    336     if (eidx == StringRef::npos)
    337       eidx = CStr.size();
    338 
    339     ParseConstraint(CStr.substr(bidx, eidx - bidx), Ops, Rec);
    340     bidx = CStr.find_first_not_of(delims, eidx);
    341   }
    342 }
    343 
    344 void CGIOperandList::ProcessDisableEncoding(StringRef DisableEncoding) {
    345   while (1) {
    346     StringRef OpName;
    347     std::tie(OpName, DisableEncoding) = getToken(DisableEncoding, " ,\t");
    348     if (OpName.empty()) break;
    349 
    350     // Figure out which operand this is.
    351     std::pair<unsigned,unsigned> Op = ParseOperandName(OpName, false);
    352 
    353     // Mark the operand as not-to-be encoded.
    354     if (Op.second >= OperandList[Op.first].DoNotEncode.size())
    355       OperandList[Op.first].DoNotEncode.resize(Op.second+1);
    356     OperandList[Op.first].DoNotEncode[Op.second] = true;
    357   }
    358 
    359 }
    360 
    361 //===----------------------------------------------------------------------===//
    362 // CodeGenInstruction Implementation
    363 //===----------------------------------------------------------------------===//
    364 
    365 CodeGenInstruction::CodeGenInstruction(Record *R)
    366   : TheDef(R), Operands(R), InferredFrom(nullptr) {
    367   Namespace = R->getValueAsString("Namespace");
    368   AsmString = std::string(R->getValueAsString("AsmString"));
    369 
    370   isPreISelOpcode = R->getValueAsBit("isPreISelOpcode");
    371   isReturn     = R->getValueAsBit("isReturn");
    372   isEHScopeReturn = R->getValueAsBit("isEHScopeReturn");
    373   isBranch     = R->getValueAsBit("isBranch");
    374   isIndirectBranch = R->getValueAsBit("isIndirectBranch");
    375   isCompare    = R->getValueAsBit("isCompare");
    376   isMoveImm    = R->getValueAsBit("isMoveImm");
    377   isMoveReg    = R->getValueAsBit("isMoveReg");
    378   isBitcast    = R->getValueAsBit("isBitcast");
    379   isSelect     = R->getValueAsBit("isSelect");
    380   isBarrier    = R->getValueAsBit("isBarrier");
    381   isCall       = R->getValueAsBit("isCall");
    382   isAdd        = R->getValueAsBit("isAdd");
    383   isTrap       = R->getValueAsBit("isTrap");
    384   canFoldAsLoad = R->getValueAsBit("canFoldAsLoad");
    385   isPredicable = !R->getValueAsBit("isUnpredicable") && (
    386       Operands.isPredicable || R->getValueAsBit("isPredicable"));
    387   isConvertibleToThreeAddress = R->getValueAsBit("isConvertibleToThreeAddress");
    388   isCommutable = R->getValueAsBit("isCommutable");
    389   isTerminator = R->getValueAsBit("isTerminator");
    390   isReMaterializable = R->getValueAsBit("isReMaterializable");
    391   hasDelaySlot = R->getValueAsBit("hasDelaySlot");
    392   usesCustomInserter = R->getValueAsBit("usesCustomInserter");
    393   hasPostISelHook = R->getValueAsBit("hasPostISelHook");
    394   hasCtrlDep   = R->getValueAsBit("hasCtrlDep");
    395   isNotDuplicable = R->getValueAsBit("isNotDuplicable");
    396   isRegSequence = R->getValueAsBit("isRegSequence");
    397   isExtractSubreg = R->getValueAsBit("isExtractSubreg");
    398   isInsertSubreg = R->getValueAsBit("isInsertSubreg");
    399   isConvergent = R->getValueAsBit("isConvergent");
    400   hasNoSchedulingInfo = R->getValueAsBit("hasNoSchedulingInfo");
    401   FastISelShouldIgnore = R->getValueAsBit("FastISelShouldIgnore");
    402   variadicOpsAreDefs = R->getValueAsBit("variadicOpsAreDefs");
    403   isAuthenticated = R->getValueAsBit("isAuthenticated");
    404 
    405   bool Unset;
    406   mayLoad      = R->getValueAsBitOrUnset("mayLoad", Unset);
    407   mayLoad_Unset = Unset;
    408   mayStore     = R->getValueAsBitOrUnset("mayStore", Unset);
    409   mayStore_Unset = Unset;
    410   mayRaiseFPException = R->getValueAsBit("mayRaiseFPException");
    411   hasSideEffects = R->getValueAsBitOrUnset("hasSideEffects", Unset);
    412   hasSideEffects_Unset = Unset;
    413 
    414   isAsCheapAsAMove = R->getValueAsBit("isAsCheapAsAMove");
    415   hasExtraSrcRegAllocReq = R->getValueAsBit("hasExtraSrcRegAllocReq");
    416   hasExtraDefRegAllocReq = R->getValueAsBit("hasExtraDefRegAllocReq");
    417   isCodeGenOnly = R->getValueAsBit("isCodeGenOnly");
    418   isPseudo = R->getValueAsBit("isPseudo");
    419   ImplicitDefs = R->getValueAsListOfDefs("Defs");
    420   ImplicitUses = R->getValueAsListOfDefs("Uses");
    421 
    422   // This flag is only inferred from the pattern.
    423   hasChain = false;
    424   hasChain_Inferred = false;
    425 
    426   // Parse Constraints.
    427   ParseConstraints(R->getValueAsString("Constraints"), Operands, R);
    428 
    429   // Parse the DisableEncoding field.
    430   Operands.ProcessDisableEncoding(
    431       R->getValueAsString("DisableEncoding"));
    432 
    433   // First check for a ComplexDeprecationPredicate.
    434   if (R->getValue("ComplexDeprecationPredicate")) {
    435     HasComplexDeprecationPredicate = true;
    436     DeprecatedReason =
    437         std::string(R->getValueAsString("ComplexDeprecationPredicate"));
    438   } else if (RecordVal *Dep = R->getValue("DeprecatedFeatureMask")) {
    439     // Check if we have a Subtarget feature mask.
    440     HasComplexDeprecationPredicate = false;
    441     DeprecatedReason = Dep->getValue()->getAsString();
    442   } else {
    443     // This instruction isn't deprecated.
    444     HasComplexDeprecationPredicate = false;
    445     DeprecatedReason = "";
    446   }
    447 }
    448 
    449 /// HasOneImplicitDefWithKnownVT - If the instruction has at least one
    450 /// implicit def and it has a known VT, return the VT, otherwise return
    451 /// MVT::Other.
    452 MVT::SimpleValueType CodeGenInstruction::
    453 HasOneImplicitDefWithKnownVT(const CodeGenTarget &TargetInfo) const {
    454   if (ImplicitDefs.empty()) return MVT::Other;
    455 
    456   // Check to see if the first implicit def has a resolvable type.
    457   Record *FirstImplicitDef = ImplicitDefs[0];
    458   assert(FirstImplicitDef->isSubClassOf("Register"));
    459   const std::vector<ValueTypeByHwMode> &RegVTs =
    460     TargetInfo.getRegisterVTs(FirstImplicitDef);
    461   if (RegVTs.size() == 1 && RegVTs[0].isSimple())
    462     return RegVTs[0].getSimple().SimpleTy;
    463   return MVT::Other;
    464 }
    465 
    466 
    467 /// FlattenAsmStringVariants - Flatten the specified AsmString to only
    468 /// include text from the specified variant, returning the new string.
    469 std::string CodeGenInstruction::
    470 FlattenAsmStringVariants(StringRef Cur, unsigned Variant) {
    471   std::string Res;
    472 
    473   for (;;) {
    474     // Find the start of the next variant string.
    475     size_t VariantsStart = 0;
    476     for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)
    477       if (Cur[VariantsStart] == '{' &&
    478           (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
    479                                   Cur[VariantsStart-1] != '\\')))
    480         break;
    481 
    482     // Add the prefix to the result.
    483     Res += Cur.slice(0, VariantsStart);
    484     if (VariantsStart == Cur.size())
    485       break;
    486 
    487     ++VariantsStart; // Skip the '{'.
    488 
    489     // Scan to the end of the variants string.
    490     size_t VariantsEnd = VariantsStart;
    491     unsigned NestedBraces = 1;
    492     for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {
    493       if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
    494         if (--NestedBraces == 0)
    495           break;
    496       } else if (Cur[VariantsEnd] == '{')
    497         ++NestedBraces;
    498     }
    499 
    500     // Select the Nth variant (or empty).
    501     StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
    502     for (unsigned i = 0; i != Variant; ++i)
    503       Selection = Selection.split('|').second;
    504     Res += Selection.split('|').first;
    505 
    506     assert(VariantsEnd != Cur.size() &&
    507            "Unterminated variants in assembly string!");
    508     Cur = Cur.substr(VariantsEnd + 1);
    509   }
    510 
    511   return Res;
    512 }
    513 
    514 bool CodeGenInstruction::isOperandImpl(unsigned i,
    515                                        StringRef PropertyName) const {
    516   DagInit *ConstraintList = TheDef->getValueAsDag("InOperandList");
    517   if (!ConstraintList || i >= ConstraintList->getNumArgs())
    518     return false;
    519 
    520   DefInit *Constraint = dyn_cast<DefInit>(ConstraintList->getArg(i));
    521   if (!Constraint)
    522     return false;
    523 
    524   return Constraint->getDef()->isSubClassOf("TypedOperand") &&
    525          Constraint->getDef()->getValueAsBit(PropertyName);
    526 }
    527 
    528 //===----------------------------------------------------------------------===//
    529 /// CodeGenInstAlias Implementation
    530 //===----------------------------------------------------------------------===//
    531 
    532 /// tryAliasOpMatch - This is a helper function for the CodeGenInstAlias
    533 /// constructor.  It checks if an argument in an InstAlias pattern matches
    534 /// the corresponding operand of the instruction.  It returns true on a
    535 /// successful match, with ResOp set to the result operand to be used.
    536 bool CodeGenInstAlias::tryAliasOpMatch(DagInit *Result, unsigned AliasOpNo,
    537                                        Record *InstOpRec, bool hasSubOps,
    538                                        ArrayRef<SMLoc> Loc, CodeGenTarget &T,
    539                                        ResultOperand &ResOp) {
    540   Init *Arg = Result->getArg(AliasOpNo);
    541   DefInit *ADI = dyn_cast<DefInit>(Arg);
    542   Record *ResultRecord = ADI ? ADI->getDef() : nullptr;
    543 
    544   if (ADI && ADI->getDef() == InstOpRec) {
    545     // If the operand is a record, it must have a name, and the record type
    546     // must match up with the instruction's argument type.
    547     if (!Result->getArgName(AliasOpNo))
    548       PrintFatalError(Loc, "result argument #" + Twine(AliasOpNo) +
    549                            " must have a name!");
    550     ResOp = ResultOperand(std::string(Result->getArgNameStr(AliasOpNo)),
    551                           ResultRecord);
    552     return true;
    553   }
    554 
    555   // For register operands, the source register class can be a subclass
    556   // of the instruction register class, not just an exact match.
    557   if (InstOpRec->isSubClassOf("RegisterOperand"))
    558     InstOpRec = InstOpRec->getValueAsDef("RegClass");
    559 
    560   if (ADI && ADI->getDef()->isSubClassOf("RegisterOperand"))
    561     ADI = ADI->getDef()->getValueAsDef("RegClass")->getDefInit();
    562 
    563   if (ADI && ADI->getDef()->isSubClassOf("RegisterClass")) {
    564     if (!InstOpRec->isSubClassOf("RegisterClass"))
    565       return false;
    566     if (!T.getRegisterClass(InstOpRec)
    567               .hasSubClass(&T.getRegisterClass(ADI->getDef())))
    568       return false;
    569     ResOp = ResultOperand(std::string(Result->getArgNameStr(AliasOpNo)),
    570                           ResultRecord);
    571     return true;
    572   }
    573 
    574   // Handle explicit registers.
    575   if (ADI && ADI->getDef()->isSubClassOf("Register")) {
    576     if (InstOpRec->isSubClassOf("OptionalDefOperand")) {
    577       DagInit *DI = InstOpRec->getValueAsDag("MIOperandInfo");
    578       // The operand info should only have a single (register) entry. We
    579       // want the register class of it.
    580       InstOpRec = cast<DefInit>(DI->getArg(0))->getDef();
    581     }
    582 
    583     if (!InstOpRec->isSubClassOf("RegisterClass"))
    584       return false;
    585 
    586     if (!T.getRegisterClass(InstOpRec)
    587         .contains(T.getRegBank().getReg(ADI->getDef())))
    588       PrintFatalError(Loc, "fixed register " + ADI->getDef()->getName() +
    589                       " is not a member of the " + InstOpRec->getName() +
    590                       " register class!");
    591 
    592     if (Result->getArgName(AliasOpNo))
    593       PrintFatalError(Loc, "result fixed register argument must "
    594                       "not have a name!");
    595 
    596     ResOp = ResultOperand(ResultRecord);
    597     return true;
    598   }
    599 
    600   // Handle "zero_reg" for optional def operands.
    601   if (ADI && ADI->getDef()->getName() == "zero_reg") {
    602 
    603     // Check if this is an optional def.
    604     // Tied operands where the source is a sub-operand of a complex operand
    605     // need to represent both operands in the alias destination instruction.
    606     // Allow zero_reg for the tied portion. This can and should go away once
    607     // the MC representation of things doesn't use tied operands at all.
    608     //if (!InstOpRec->isSubClassOf("OptionalDefOperand"))
    609     //  throw TGError(Loc, "reg0 used for result that is not an "
    610     //                "OptionalDefOperand!");
    611 
    612     ResOp = ResultOperand(static_cast<Record*>(nullptr));
    613     return true;
    614   }
    615 
    616   // Literal integers.
    617   if (IntInit *II = dyn_cast<IntInit>(Arg)) {
    618     if (hasSubOps || !InstOpRec->isSubClassOf("Operand"))
    619       return false;
    620     // Integer arguments can't have names.
    621     if (Result->getArgName(AliasOpNo))
    622       PrintFatalError(Loc, "result argument #" + Twine(AliasOpNo) +
    623                       " must not have a name!");
    624     ResOp = ResultOperand(II->getValue());
    625     return true;
    626   }
    627 
    628   // Bits<n> (also used for 0bxx literals)
    629   if (BitsInit *BI = dyn_cast<BitsInit>(Arg)) {
    630     if (hasSubOps || !InstOpRec->isSubClassOf("Operand"))
    631       return false;
    632     if (!BI->isComplete())
    633       return false;
    634     // Convert the bits init to an integer and use that for the result.
    635     IntInit *II =
    636       dyn_cast_or_null<IntInit>(BI->convertInitializerTo(IntRecTy::get()));
    637     if (!II)
    638       return false;
    639     ResOp = ResultOperand(II->getValue());
    640     return true;
    641   }
    642 
    643   // If both are Operands with the same MVT, allow the conversion. It's
    644   // up to the user to make sure the values are appropriate, just like
    645   // for isel Pat's.
    646   if (InstOpRec->isSubClassOf("Operand") && ADI &&
    647       ADI->getDef()->isSubClassOf("Operand")) {
    648     // FIXME: What other attributes should we check here? Identical
    649     // MIOperandInfo perhaps?
    650     if (InstOpRec->getValueInit("Type") != ADI->getDef()->getValueInit("Type"))
    651       return false;
    652     ResOp = ResultOperand(std::string(Result->getArgNameStr(AliasOpNo)),
    653                           ADI->getDef());
    654     return true;
    655   }
    656 
    657   return false;
    658 }
    659 
    660 unsigned CodeGenInstAlias::ResultOperand::getMINumOperands() const {
    661   if (!isRecord())
    662     return 1;
    663 
    664   Record *Rec = getRecord();
    665   if (!Rec->isSubClassOf("Operand"))
    666     return 1;
    667 
    668   DagInit *MIOpInfo = Rec->getValueAsDag("MIOperandInfo");
    669   if (MIOpInfo->getNumArgs() == 0) {
    670     // Unspecified, so it defaults to 1
    671     return 1;
    672   }
    673 
    674   return MIOpInfo->getNumArgs();
    675 }
    676 
    677 CodeGenInstAlias::CodeGenInstAlias(Record *R, CodeGenTarget &T)
    678     : TheDef(R) {
    679   Result = R->getValueAsDag("ResultInst");
    680   AsmString = std::string(R->getValueAsString("AsmString"));
    681 
    682   // Verify that the root of the result is an instruction.
    683   DefInit *DI = dyn_cast<DefInit>(Result->getOperator());
    684   if (!DI || !DI->getDef()->isSubClassOf("Instruction"))
    685     PrintFatalError(R->getLoc(),
    686                     "result of inst alias should be an instruction");
    687 
    688   ResultInst = &T.getInstruction(DI->getDef());
    689 
    690   // NameClass - If argument names are repeated, we need to verify they have
    691   // the same class.
    692   StringMap<Record*> NameClass;
    693   for (unsigned i = 0, e = Result->getNumArgs(); i != e; ++i) {
    694     DefInit *ADI = dyn_cast<DefInit>(Result->getArg(i));
    695     if (!ADI || !Result->getArgName(i))
    696       continue;
    697     // Verify we don't have something like: (someinst GR16:$foo, GR32:$foo)
    698     // $foo can exist multiple times in the result list, but it must have the
    699     // same type.
    700     Record *&Entry = NameClass[Result->getArgNameStr(i)];
    701     if (Entry && Entry != ADI->getDef())
    702       PrintFatalError(R->getLoc(), "result value $" + Result->getArgNameStr(i) +
    703                       " is both " + Entry->getName() + " and " +
    704                       ADI->getDef()->getName() + "!");
    705     Entry = ADI->getDef();
    706   }
    707 
    708   // Decode and validate the arguments of the result.
    709   unsigned AliasOpNo = 0;
    710   for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
    711 
    712     // Tied registers don't have an entry in the result dag unless they're part
    713     // of a complex operand, in which case we include them anyways, as we
    714     // don't have any other way to specify the whole operand.
    715     if (ResultInst->Operands[i].MINumOperands == 1 &&
    716         ResultInst->Operands[i].getTiedRegister() != -1) {
    717       // Tied operands of different RegisterClass should be explicit within an
    718       // instruction's syntax and so cannot be skipped.
    719       int TiedOpNum = ResultInst->Operands[i].getTiedRegister();
    720       if (ResultInst->Operands[i].Rec->getName() ==
    721           ResultInst->Operands[TiedOpNum].Rec->getName())
    722         continue;
    723     }
    724 
    725     if (AliasOpNo >= Result->getNumArgs())
    726       PrintFatalError(R->getLoc(), "not enough arguments for instruction!");
    727 
    728     Record *InstOpRec = ResultInst->Operands[i].Rec;
    729     unsigned NumSubOps = ResultInst->Operands[i].MINumOperands;
    730     ResultOperand ResOp(static_cast<int64_t>(0));
    731     if (tryAliasOpMatch(Result, AliasOpNo, InstOpRec, (NumSubOps > 1),
    732                         R->getLoc(), T, ResOp)) {
    733       // If this is a simple operand, or a complex operand with a custom match
    734       // class, then we can match is verbatim.
    735       if (NumSubOps == 1 ||
    736           (InstOpRec->getValue("ParserMatchClass") &&
    737            InstOpRec->getValueAsDef("ParserMatchClass")
    738              ->getValueAsString("Name") != "Imm")) {
    739         ResultOperands.push_back(ResOp);
    740         ResultInstOperandIndex.push_back(std::make_pair(i, -1));
    741         ++AliasOpNo;
    742 
    743       // Otherwise, we need to match each of the suboperands individually.
    744       } else {
    745          DagInit *MIOI = ResultInst->Operands[i].MIOperandInfo;
    746          for (unsigned SubOp = 0; SubOp != NumSubOps; ++SubOp) {
    747           Record *SubRec = cast<DefInit>(MIOI->getArg(SubOp))->getDef();
    748 
    749           // Take care to instantiate each of the suboperands with the correct
    750           // nomenclature: $foo.bar
    751           ResultOperands.emplace_back(
    752             Result->getArgName(AliasOpNo)->getAsUnquotedString() + "." +
    753             MIOI->getArgName(SubOp)->getAsUnquotedString(), SubRec);
    754           ResultInstOperandIndex.push_back(std::make_pair(i, SubOp));
    755          }
    756          ++AliasOpNo;
    757       }
    758       continue;
    759     }
    760 
    761     // If the argument did not match the instruction operand, and the operand
    762     // is composed of multiple suboperands, try matching the suboperands.
    763     if (NumSubOps > 1) {
    764       DagInit *MIOI = ResultInst->Operands[i].MIOperandInfo;
    765       for (unsigned SubOp = 0; SubOp != NumSubOps; ++SubOp) {
    766         if (AliasOpNo >= Result->getNumArgs())
    767           PrintFatalError(R->getLoc(), "not enough arguments for instruction!");
    768         Record *SubRec = cast<DefInit>(MIOI->getArg(SubOp))->getDef();
    769         if (tryAliasOpMatch(Result, AliasOpNo, SubRec, false,
    770                             R->getLoc(), T, ResOp)) {
    771           ResultOperands.push_back(ResOp);
    772           ResultInstOperandIndex.push_back(std::make_pair(i, SubOp));
    773           ++AliasOpNo;
    774         } else {
    775           PrintFatalError(R->getLoc(), "result argument #" + Twine(AliasOpNo) +
    776                         " does not match instruction operand class " +
    777                         (SubOp == 0 ? InstOpRec->getName() :SubRec->getName()));
    778         }
    779       }
    780       continue;
    781     }
    782     PrintFatalError(R->getLoc(), "result argument #" + Twine(AliasOpNo) +
    783                     " does not match instruction operand class " +
    784                     InstOpRec->getName());
    785   }
    786 
    787   if (AliasOpNo != Result->getNumArgs())
    788     PrintFatalError(R->getLoc(), "too many operands for instruction!");
    789 }
    790