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