[llvm-readobj] - Implement LLVM-style dumping for .stack_sizes sections.
[llvm-complete.git] / utils / TableGen / CodeGenInstruction.cpp
blob2463824469abfa256e20700980878086813208ee
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.
11 //===----------------------------------------------------------------------===//
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;
23 //===----------------------------------------------------------------------===//
24 // CGIOperandList Implementation
25 //===----------------------------------------------------------------------===//
27 CGIOperandList::CGIOperandList(Record *R) : TheDef(R) {
28 isPredicable = false;
29 hasOptionalDef = false;
30 isVariadic = false;
32 DagInit *OutDI = R->getValueAsDag("OutOperandList");
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'");
43 NumDefs = OutDI->getNumArgs();
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'");
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);
70 DefInit *Arg = dyn_cast<DefInit>(ArgInit);
71 if (!Arg)
72 PrintFatalError(R->getLoc(), "Illegal operand for the '" + R->getName() +
73 "' instruction!");
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");
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");
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;
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!");
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!");
133 OperandList.emplace_back(Rec, ArgName, PrintMethod, EncoderMethod,
134 OperandNamespace + "::" + OperandType, MIOperandNo,
135 NumOps, MIOpInfo);
136 MIOperandNo += NumOps;
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);
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.
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 + "'!");
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;
170 return false;
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 + "'");
179 std::string OpName = Op.substr(1);
180 std::string SubOpName;
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);
193 unsigned OpIdx = getOperandNamed(OpName);
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 + "'");
205 // Otherwise, return the operand.
206 return std::make_pair(OpIdx, 0U);
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 + "'");
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);
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);
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);
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;
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");
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);
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 + "'");
276 std::string RHSOpName = StringRef(CStr).substr(wpos);
277 std::pair<unsigned,unsigned> RHSOp = Ops.ParseOperandName(RHSOpName, false);
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);
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!");
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!");
305 unsigned DestFlatOpNo = Ops.getFlattenedOperandNumber(DestOp);
306 auto NewConstraint = CGIOperandList::ConstraintInfo::getTied(DestFlatOpNo);
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!");
318 Ops[SrcOp.first].Constraints[SrcOp.second] = NewConstraint;
321 static void ParseConstraints(const std::string &CStr, CGIOperandList &Ops,
322 Record *Rec) {
323 if (CStr.empty()) return;
325 const std::string delims(",");
326 std::string::size_type bidx, eidx;
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();
334 ParseConstraint(CStr.substr(bidx, eidx - bidx), Ops, Rec);
335 bidx = CStr.find_first_not_of(delims, eidx);
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;
346 // Figure out which operand this is.
347 std::pair<unsigned,unsigned> Op = ParseOperandName(OpName, false);
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;
357 //===----------------------------------------------------------------------===//
358 // CodeGenInstruction Implementation
359 //===----------------------------------------------------------------------===//
361 CodeGenInstruction::CodeGenInstruction(Record *R)
362 : TheDef(R), Operands(R), InferredFrom(nullptr) {
363 Namespace = R->getValueAsString("Namespace");
364 AsmString = R->getValueAsString("AsmString");
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");
399 bool Unset;
400 mayLoad = R->getValueAsBitOrUnset("mayLoad", Unset);
401 mayLoad_Unset = Unset;
402 mayStore = R->getValueAsBitOrUnset("mayStore", Unset);
403 mayStore_Unset = Unset;
404 mayRaiseFPException = R->getValueAsBit("mayRaiseFPException");
405 hasSideEffects = R->getValueAsBitOrUnset("hasSideEffects", Unset);
406 hasSideEffects_Unset = Unset;
408 isAsCheapAsAMove = R->getValueAsBit("isAsCheapAsAMove");
409 hasExtraSrcRegAllocReq = R->getValueAsBit("hasExtraSrcRegAllocReq");
410 hasExtraDefRegAllocReq = R->getValueAsBit("hasExtraDefRegAllocReq");
411 isCodeGenOnly = R->getValueAsBit("isCodeGenOnly");
412 isPseudo = R->getValueAsBit("isPseudo");
413 ImplicitDefs = R->getValueAsListOfDefs("Defs");
414 ImplicitUses = R->getValueAsListOfDefs("Uses");
416 // This flag is only inferred from the pattern.
417 hasChain = false;
418 hasChain_Inferred = false;
420 // Parse Constraints.
421 ParseConstraints(R->getValueAsString("Constraints"), Operands, R);
423 // Parse the DisableEncoding field.
424 Operands.ProcessDisableEncoding(R->getValueAsString("DisableEncoding"));
426 // First check for a ComplexDeprecationPredicate.
427 if (R->getValue("ComplexDeprecationPredicate")) {
428 HasComplexDeprecationPredicate = true;
429 DeprecatedReason = R->getValueAsString("ComplexDeprecationPredicate");
430 } else if (RecordVal *Dep = R->getValue("DeprecatedFeatureMask")) {
431 // Check if we have a Subtarget feature mask.
432 HasComplexDeprecationPredicate = false;
433 DeprecatedReason = Dep->getValue()->getAsString();
434 } else {
435 // This instruction isn't deprecated.
436 HasComplexDeprecationPredicate = false;
437 DeprecatedReason = "";
441 /// HasOneImplicitDefWithKnownVT - If the instruction has at least one
442 /// implicit def and it has a known VT, return the VT, otherwise return
443 /// MVT::Other.
444 MVT::SimpleValueType CodeGenInstruction::
445 HasOneImplicitDefWithKnownVT(const CodeGenTarget &TargetInfo) const {
446 if (ImplicitDefs.empty()) return MVT::Other;
448 // Check to see if the first implicit def has a resolvable type.
449 Record *FirstImplicitDef = ImplicitDefs[0];
450 assert(FirstImplicitDef->isSubClassOf("Register"));
451 const std::vector<ValueTypeByHwMode> &RegVTs =
452 TargetInfo.getRegisterVTs(FirstImplicitDef);
453 if (RegVTs.size() == 1 && RegVTs[0].isSimple())
454 return RegVTs[0].getSimple().SimpleTy;
455 return MVT::Other;
459 /// FlattenAsmStringVariants - Flatten the specified AsmString to only
460 /// include text from the specified variant, returning the new string.
461 std::string CodeGenInstruction::
462 FlattenAsmStringVariants(StringRef Cur, unsigned Variant) {
463 std::string Res = "";
465 for (;;) {
466 // Find the start of the next variant string.
467 size_t VariantsStart = 0;
468 for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)
469 if (Cur[VariantsStart] == '{' &&
470 (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
471 Cur[VariantsStart-1] != '\\')))
472 break;
474 // Add the prefix to the result.
475 Res += Cur.slice(0, VariantsStart);
476 if (VariantsStart == Cur.size())
477 break;
479 ++VariantsStart; // Skip the '{'.
481 // Scan to the end of the variants string.
482 size_t VariantsEnd = VariantsStart;
483 unsigned NestedBraces = 1;
484 for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {
485 if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
486 if (--NestedBraces == 0)
487 break;
488 } else if (Cur[VariantsEnd] == '{')
489 ++NestedBraces;
492 // Select the Nth variant (or empty).
493 StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
494 for (unsigned i = 0; i != Variant; ++i)
495 Selection = Selection.split('|').second;
496 Res += Selection.split('|').first;
498 assert(VariantsEnd != Cur.size() &&
499 "Unterminated variants in assembly string!");
500 Cur = Cur.substr(VariantsEnd + 1);
503 return Res;
506 bool CodeGenInstruction::isOperandAPointer(unsigned i) const {
507 if (DagInit *ConstraintList = TheDef->getValueAsDag("InOperandList")) {
508 if (i < ConstraintList->getNumArgs()) {
509 if (DefInit *Constraint = dyn_cast<DefInit>(ConstraintList->getArg(i))) {
510 return Constraint->getDef()->isSubClassOf("TypedOperand") &&
511 Constraint->getDef()->getValueAsBit("IsPointer");
515 return false;
518 //===----------------------------------------------------------------------===//
519 /// CodeGenInstAlias Implementation
520 //===----------------------------------------------------------------------===//
522 /// tryAliasOpMatch - This is a helper function for the CodeGenInstAlias
523 /// constructor. It checks if an argument in an InstAlias pattern matches
524 /// the corresponding operand of the instruction. It returns true on a
525 /// successful match, with ResOp set to the result operand to be used.
526 bool CodeGenInstAlias::tryAliasOpMatch(DagInit *Result, unsigned AliasOpNo,
527 Record *InstOpRec, bool hasSubOps,
528 ArrayRef<SMLoc> Loc, CodeGenTarget &T,
529 ResultOperand &ResOp) {
530 Init *Arg = Result->getArg(AliasOpNo);
531 DefInit *ADI = dyn_cast<DefInit>(Arg);
532 Record *ResultRecord = ADI ? ADI->getDef() : nullptr;
534 if (ADI && ADI->getDef() == InstOpRec) {
535 // If the operand is a record, it must have a name, and the record type
536 // must match up with the instruction's argument type.
537 if (!Result->getArgName(AliasOpNo))
538 PrintFatalError(Loc, "result argument #" + Twine(AliasOpNo) +
539 " must have a name!");
540 ResOp = ResultOperand(Result->getArgNameStr(AliasOpNo), ResultRecord);
541 return true;
544 // For register operands, the source register class can be a subclass
545 // of the instruction register class, not just an exact match.
546 if (InstOpRec->isSubClassOf("RegisterOperand"))
547 InstOpRec = InstOpRec->getValueAsDef("RegClass");
549 if (ADI && ADI->getDef()->isSubClassOf("RegisterOperand"))
550 ADI = ADI->getDef()->getValueAsDef("RegClass")->getDefInit();
552 if (ADI && ADI->getDef()->isSubClassOf("RegisterClass")) {
553 if (!InstOpRec->isSubClassOf("RegisterClass"))
554 return false;
555 if (!T.getRegisterClass(InstOpRec)
556 .hasSubClass(&T.getRegisterClass(ADI->getDef())))
557 return false;
558 ResOp = ResultOperand(Result->getArgNameStr(AliasOpNo), ResultRecord);
559 return true;
562 // Handle explicit registers.
563 if (ADI && ADI->getDef()->isSubClassOf("Register")) {
564 if (InstOpRec->isSubClassOf("OptionalDefOperand")) {
565 DagInit *DI = InstOpRec->getValueAsDag("MIOperandInfo");
566 // The operand info should only have a single (register) entry. We
567 // want the register class of it.
568 InstOpRec = cast<DefInit>(DI->getArg(0))->getDef();
571 if (!InstOpRec->isSubClassOf("RegisterClass"))
572 return false;
574 if (!T.getRegisterClass(InstOpRec)
575 .contains(T.getRegBank().getReg(ADI->getDef())))
576 PrintFatalError(Loc, "fixed register " + ADI->getDef()->getName() +
577 " is not a member of the " + InstOpRec->getName() +
578 " register class!");
580 if (Result->getArgName(AliasOpNo))
581 PrintFatalError(Loc, "result fixed register argument must "
582 "not have a name!");
584 ResOp = ResultOperand(ResultRecord);
585 return true;
588 // Handle "zero_reg" for optional def operands.
589 if (ADI && ADI->getDef()->getName() == "zero_reg") {
591 // Check if this is an optional def.
592 // Tied operands where the source is a sub-operand of a complex operand
593 // need to represent both operands in the alias destination instruction.
594 // Allow zero_reg for the tied portion. This can and should go away once
595 // the MC representation of things doesn't use tied operands at all.
596 //if (!InstOpRec->isSubClassOf("OptionalDefOperand"))
597 // throw TGError(Loc, "reg0 used for result that is not an "
598 // "OptionalDefOperand!");
600 ResOp = ResultOperand(static_cast<Record*>(nullptr));
601 return true;
604 // Literal integers.
605 if (IntInit *II = dyn_cast<IntInit>(Arg)) {
606 if (hasSubOps || !InstOpRec->isSubClassOf("Operand"))
607 return false;
608 // Integer arguments can't have names.
609 if (Result->getArgName(AliasOpNo))
610 PrintFatalError(Loc, "result argument #" + Twine(AliasOpNo) +
611 " must not have a name!");
612 ResOp = ResultOperand(II->getValue());
613 return true;
616 // Bits<n> (also used for 0bxx literals)
617 if (BitsInit *BI = dyn_cast<BitsInit>(Arg)) {
618 if (hasSubOps || !InstOpRec->isSubClassOf("Operand"))
619 return false;
620 if (!BI->isComplete())
621 return false;
622 // Convert the bits init to an integer and use that for the result.
623 IntInit *II =
624 dyn_cast_or_null<IntInit>(BI->convertInitializerTo(IntRecTy::get()));
625 if (!II)
626 return false;
627 ResOp = ResultOperand(II->getValue());
628 return true;
631 // If both are Operands with the same MVT, allow the conversion. It's
632 // up to the user to make sure the values are appropriate, just like
633 // for isel Pat's.
634 if (InstOpRec->isSubClassOf("Operand") && ADI &&
635 ADI->getDef()->isSubClassOf("Operand")) {
636 // FIXME: What other attributes should we check here? Identical
637 // MIOperandInfo perhaps?
638 if (InstOpRec->getValueInit("Type") != ADI->getDef()->getValueInit("Type"))
639 return false;
640 ResOp = ResultOperand(Result->getArgNameStr(AliasOpNo), ADI->getDef());
641 return true;
644 return false;
647 unsigned CodeGenInstAlias::ResultOperand::getMINumOperands() const {
648 if (!isRecord())
649 return 1;
651 Record *Rec = getRecord();
652 if (!Rec->isSubClassOf("Operand"))
653 return 1;
655 DagInit *MIOpInfo = Rec->getValueAsDag("MIOperandInfo");
656 if (MIOpInfo->getNumArgs() == 0) {
657 // Unspecified, so it defaults to 1
658 return 1;
661 return MIOpInfo->getNumArgs();
664 CodeGenInstAlias::CodeGenInstAlias(Record *R, CodeGenTarget &T)
665 : TheDef(R) {
666 Result = R->getValueAsDag("ResultInst");
667 AsmString = R->getValueAsString("AsmString");
670 // Verify that the root of the result is an instruction.
671 DefInit *DI = dyn_cast<DefInit>(Result->getOperator());
672 if (!DI || !DI->getDef()->isSubClassOf("Instruction"))
673 PrintFatalError(R->getLoc(),
674 "result of inst alias should be an instruction");
676 ResultInst = &T.getInstruction(DI->getDef());
678 // NameClass - If argument names are repeated, we need to verify they have
679 // the same class.
680 StringMap<Record*> NameClass;
681 for (unsigned i = 0, e = Result->getNumArgs(); i != e; ++i) {
682 DefInit *ADI = dyn_cast<DefInit>(Result->getArg(i));
683 if (!ADI || !Result->getArgName(i))
684 continue;
685 // Verify we don't have something like: (someinst GR16:$foo, GR32:$foo)
686 // $foo can exist multiple times in the result list, but it must have the
687 // same type.
688 Record *&Entry = NameClass[Result->getArgNameStr(i)];
689 if (Entry && Entry != ADI->getDef())
690 PrintFatalError(R->getLoc(), "result value $" + Result->getArgNameStr(i) +
691 " is both " + Entry->getName() + " and " +
692 ADI->getDef()->getName() + "!");
693 Entry = ADI->getDef();
696 // Decode and validate the arguments of the result.
697 unsigned AliasOpNo = 0;
698 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
700 // Tied registers don't have an entry in the result dag unless they're part
701 // of a complex operand, in which case we include them anyways, as we
702 // don't have any other way to specify the whole operand.
703 if (ResultInst->Operands[i].MINumOperands == 1 &&
704 ResultInst->Operands[i].getTiedRegister() != -1) {
705 // Tied operands of different RegisterClass should be explicit within an
706 // instruction's syntax and so cannot be skipped.
707 int TiedOpNum = ResultInst->Operands[i].getTiedRegister();
708 if (ResultInst->Operands[i].Rec->getName() ==
709 ResultInst->Operands[TiedOpNum].Rec->getName())
710 continue;
713 if (AliasOpNo >= Result->getNumArgs())
714 PrintFatalError(R->getLoc(), "not enough arguments for instruction!");
716 Record *InstOpRec = ResultInst->Operands[i].Rec;
717 unsigned NumSubOps = ResultInst->Operands[i].MINumOperands;
718 ResultOperand ResOp(static_cast<int64_t>(0));
719 if (tryAliasOpMatch(Result, AliasOpNo, InstOpRec, (NumSubOps > 1),
720 R->getLoc(), T, ResOp)) {
721 // If this is a simple operand, or a complex operand with a custom match
722 // class, then we can match is verbatim.
723 if (NumSubOps == 1 ||
724 (InstOpRec->getValue("ParserMatchClass") &&
725 InstOpRec->getValueAsDef("ParserMatchClass")
726 ->getValueAsString("Name") != "Imm")) {
727 ResultOperands.push_back(ResOp);
728 ResultInstOperandIndex.push_back(std::make_pair(i, -1));
729 ++AliasOpNo;
731 // Otherwise, we need to match each of the suboperands individually.
732 } else {
733 DagInit *MIOI = ResultInst->Operands[i].MIOperandInfo;
734 for (unsigned SubOp = 0; SubOp != NumSubOps; ++SubOp) {
735 Record *SubRec = cast<DefInit>(MIOI->getArg(SubOp))->getDef();
737 // Take care to instantiate each of the suboperands with the correct
738 // nomenclature: $foo.bar
739 ResultOperands.emplace_back(
740 Result->getArgName(AliasOpNo)->getAsUnquotedString() + "." +
741 MIOI->getArgName(SubOp)->getAsUnquotedString(), SubRec);
742 ResultInstOperandIndex.push_back(std::make_pair(i, SubOp));
744 ++AliasOpNo;
746 continue;
749 // If the argument did not match the instruction operand, and the operand
750 // is composed of multiple suboperands, try matching the suboperands.
751 if (NumSubOps > 1) {
752 DagInit *MIOI = ResultInst->Operands[i].MIOperandInfo;
753 for (unsigned SubOp = 0; SubOp != NumSubOps; ++SubOp) {
754 if (AliasOpNo >= Result->getNumArgs())
755 PrintFatalError(R->getLoc(), "not enough arguments for instruction!");
756 Record *SubRec = cast<DefInit>(MIOI->getArg(SubOp))->getDef();
757 if (tryAliasOpMatch(Result, AliasOpNo, SubRec, false,
758 R->getLoc(), T, ResOp)) {
759 ResultOperands.push_back(ResOp);
760 ResultInstOperandIndex.push_back(std::make_pair(i, SubOp));
761 ++AliasOpNo;
762 } else {
763 PrintFatalError(R->getLoc(), "result argument #" + Twine(AliasOpNo) +
764 " does not match instruction operand class " +
765 (SubOp == 0 ? InstOpRec->getName() :SubRec->getName()));
768 continue;
770 PrintFatalError(R->getLoc(), "result argument #" + Twine(AliasOpNo) +
771 " does not match instruction operand class " +
772 InstOpRec->getName());
775 if (AliasOpNo != Result->getNumArgs())
776 PrintFatalError(R->getLoc(), "too many operands for instruction!");