1 //===- DAGISelMatcherGen.cpp - Matcher generator --------------------------===// 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 #include "CodeGenDAGPatterns.h" 10 #include "CodeGenInstruction.h" 11 #include "CodeGenRegisters.h" 12 #include "CodeGenTarget.h" 13 #include "DAGISelMatcher.h" 14 #include "InfoByHwMode.h" 15 #include "SDNodeProperties.h" 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/StringMap.h" 18 #include "llvm/TableGen/Error.h" 19 #include "llvm/TableGen/Record.h" 20 #include <utility> 21 using namespace llvm; 22 23 24 /// getRegisterValueType - Look up and return the ValueType of the specified 25 /// register. If the register is a member of multiple register classes, they 26 /// must all have the same type. 27 static MVT::SimpleValueType getRegisterValueType(Record *R, 28 const CodeGenTarget &T) { 29 bool FoundRC = false; 30 MVT::SimpleValueType VT = MVT::Other; 31 const CodeGenRegister *Reg = T.getRegBank().getReg(R); 32 33 for (const auto &RC : T.getRegBank().getRegClasses()) { 34 if (!RC.contains(Reg)) 35 continue; 36 37 if (!FoundRC) { 38 FoundRC = true; 39 const ValueTypeByHwMode &VVT = RC.getValueTypeNum(0); 40 assert(VVT.isSimple()); 41 VT = VVT.getSimple().SimpleTy; 42 continue; 43 } 44 45 #ifndef NDEBUG 46 // If this occurs in multiple register classes, they all have to agree. 47 const ValueTypeByHwMode &VVT = RC.getValueTypeNum(0); 48 assert(VVT.isSimple() && VVT.getSimple().SimpleTy == VT && 49 "ValueType mismatch between register classes for this register"); 50 #endif 51 } 52 return VT; 53 } 54 55 56 namespace { 57 class MatcherGen { 58 const PatternToMatch &Pattern; 59 const CodeGenDAGPatterns &CGP; 60 61 /// PatWithNoTypes - This is a clone of Pattern.getSrcPattern() that starts 62 /// out with all of the types removed. This allows us to insert type checks 63 /// as we scan the tree. 64 TreePatternNodePtr PatWithNoTypes; 65 66 /// VariableMap - A map from variable names ('$dst') to the recorded operand 67 /// number that they were captured as. These are biased by 1 to make 68 /// insertion easier. 69 StringMap<unsigned> VariableMap; 70 71 /// This maintains the recorded operand number that OPC_CheckComplexPattern 72 /// drops each sub-operand into. We don't want to insert these into 73 /// VariableMap because that leads to identity checking if they are 74 /// encountered multiple times. Biased by 1 like VariableMap for 75 /// consistency. 76 StringMap<unsigned> NamedComplexPatternOperands; 77 78 /// NextRecordedOperandNo - As we emit opcodes to record matched values in 79 /// the RecordedNodes array, this keeps track of which slot will be next to 80 /// record into. 81 unsigned NextRecordedOperandNo; 82 83 /// MatchedChainNodes - This maintains the position in the recorded nodes 84 /// array of all of the recorded input nodes that have chains. 85 SmallVector<unsigned, 2> MatchedChainNodes; 86 87 /// MatchedComplexPatterns - This maintains a list of all of the 88 /// ComplexPatterns that we need to check. The second element of each pair 89 /// is the recorded operand number of the input node. 90 SmallVector<std::pair<const TreePatternNode*, 91 unsigned>, 2> MatchedComplexPatterns; 92 93 /// PhysRegInputs - List list has an entry for each explicitly specified 94 /// physreg input to the pattern. The first elt is the Register node, the 95 /// second is the recorded slot number the input pattern match saved it in. 96 SmallVector<std::pair<Record*, unsigned>, 2> PhysRegInputs; 97 98 /// Matcher - This is the top level of the generated matcher, the result. 99 Matcher *TheMatcher; 100 101 /// CurPredicate - As we emit matcher nodes, this points to the latest check 102 /// which should have future checks stuck into its Next position. 103 Matcher *CurPredicate; 104 public: 105 MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp); 106 107 bool EmitMatcherCode(unsigned Variant); 108 void EmitResultCode(); 109 110 Matcher *GetMatcher() const { return TheMatcher; } 111 private: 112 void AddMatcher(Matcher *NewNode); 113 void InferPossibleTypes(); 114 115 // Matcher Generation. 116 void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes); 117 void EmitLeafMatchCode(const TreePatternNode *N); 118 void EmitOperatorMatchCode(const TreePatternNode *N, 119 TreePatternNode *NodeNoTypes); 120 121 /// If this is the first time a node with unique identifier Name has been 122 /// seen, record it. Otherwise, emit a check to make sure this is the same 123 /// node. Returns true if this is the first encounter. 124 bool recordUniqueNode(ArrayRef<std::string> Names); 125 126 // Result Code Generation. 127 unsigned getNamedArgumentSlot(StringRef Name) { 128 unsigned VarMapEntry = VariableMap[Name]; 129 assert(VarMapEntry != 0 && 130 "Variable referenced but not defined and not caught earlier!"); 131 return VarMapEntry-1; 132 } 133 134 void EmitResultOperand(const TreePatternNode *N, 135 SmallVectorImpl<unsigned> &ResultOps); 136 void EmitResultOfNamedOperand(const TreePatternNode *N, 137 SmallVectorImpl<unsigned> &ResultOps); 138 void EmitResultLeafAsOperand(const TreePatternNode *N, 139 SmallVectorImpl<unsigned> &ResultOps); 140 void EmitResultInstructionAsOperand(const TreePatternNode *N, 141 SmallVectorImpl<unsigned> &ResultOps); 142 void EmitResultSDNodeXFormAsOperand(const TreePatternNode *N, 143 SmallVectorImpl<unsigned> &ResultOps); 144 }; 145 146 } // end anonymous namespace 147 148 MatcherGen::MatcherGen(const PatternToMatch &pattern, 149 const CodeGenDAGPatterns &cgp) 150 : Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0), 151 TheMatcher(nullptr), CurPredicate(nullptr) { 152 // We need to produce the matcher tree for the patterns source pattern. To do 153 // this we need to match the structure as well as the types. To do the type 154 // matching, we want to figure out the fewest number of type checks we need to 155 // emit. For example, if there is only one integer type supported by a 156 // target, there should be no type comparisons at all for integer patterns! 157 // 158 // To figure out the fewest number of type checks needed, clone the pattern, 159 // remove the types, then perform type inference on the pattern as a whole. 160 // If there are unresolved types, emit an explicit check for those types, 161 // apply the type to the tree, then rerun type inference. Iterate until all 162 // types are resolved. 163 // 164 PatWithNoTypes = Pattern.getSrcPattern()->clone(); 165 PatWithNoTypes->RemoveAllTypes(); 166 167 // If there are types that are manifestly known, infer them. 168 InferPossibleTypes(); 169 } 170 171 /// InferPossibleTypes - As we emit the pattern, we end up generating type 172 /// checks and applying them to the 'PatWithNoTypes' tree. As we do this, we 173 /// want to propagate implied types as far throughout the tree as possible so 174 /// that we avoid doing redundant type checks. This does the type propagation. 175 void MatcherGen::InferPossibleTypes() { 176 // TP - Get *SOME* tree pattern, we don't care which. It is only used for 177 // diagnostics, which we know are impossible at this point. 178 TreePattern &TP = *CGP.pf_begin()->second; 179 180 bool MadeChange = true; 181 while (MadeChange) 182 MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP, 183 true/*Ignore reg constraints*/); 184 } 185 186 187 /// AddMatcher - Add a matcher node to the current graph we're building. 188 void MatcherGen::AddMatcher(Matcher *NewNode) { 189 if (CurPredicate) 190 CurPredicate->setNext(NewNode); 191 else 192 TheMatcher = NewNode; 193 CurPredicate = NewNode; 194 } 195 196 197 //===----------------------------------------------------------------------===// 198 // Pattern Match Generation 199 //===----------------------------------------------------------------------===// 200 201 /// EmitLeafMatchCode - Generate matching code for leaf nodes. 202 void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) { 203 assert(N->isLeaf() && "Not a leaf?"); 204 205 // Direct match against an integer constant. 206 if (IntInit *II = dyn_cast<IntInit>(N->getLeafValue())) { 207 // If this is the root of the dag we're matching, we emit a redundant opcode 208 // check to ensure that this gets folded into the normal top-level 209 // OpcodeSwitch. 210 if (N == Pattern.getSrcPattern()) { 211 const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed("imm")); 212 AddMatcher(new CheckOpcodeMatcher(NI)); 213 } 214 215 return AddMatcher(new CheckIntegerMatcher(II->getValue())); 216 } 217 218 // An UnsetInit represents a named node without any constraints. 219 if (isa<UnsetInit>(N->getLeafValue())) { 220 assert(N->hasName() && "Unnamed ? leaf"); 221 return; 222 } 223 224 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue()); 225 if (!DI) { 226 errs() << "Unknown leaf kind: " << *N << "\n"; 227 abort(); 228 } 229 230 Record *LeafRec = DI->getDef(); 231 232 // A ValueType leaf node can represent a register when named, or itself when 233 // unnamed. 234 if (LeafRec->isSubClassOf("ValueType")) { 235 // A named ValueType leaf always matches: (add i32:$a, i32:$b). 236 if (N->hasName()) 237 return; 238 // An unnamed ValueType as in (sext_inreg GPR:$foo, i8). 239 return AddMatcher(new CheckValueTypeMatcher(LeafRec->getName())); 240 } 241 242 if (// Handle register references. Nothing to do here, they always match. 243 LeafRec->isSubClassOf("RegisterClass") || 244 LeafRec->isSubClassOf("RegisterOperand") || 245 LeafRec->isSubClassOf("PointerLikeRegClass") || 246 LeafRec->isSubClassOf("SubRegIndex") || 247 // Place holder for SRCVALUE nodes. Nothing to do here. 248 LeafRec->getName() == "srcvalue") 249 return; 250 251 // If we have a physreg reference like (mul gpr:$src, EAX) then we need to 252 // record the register 253 if (LeafRec->isSubClassOf("Register")) { 254 AddMatcher(new RecordMatcher("physreg input "+LeafRec->getName().str(), 255 NextRecordedOperandNo)); 256 PhysRegInputs.push_back(std::make_pair(LeafRec, NextRecordedOperandNo++)); 257 return; 258 } 259 260 if (LeafRec->isSubClassOf("CondCode")) 261 return AddMatcher(new CheckCondCodeMatcher(LeafRec->getName())); 262 263 if (LeafRec->isSubClassOf("ComplexPattern")) { 264 // We can't model ComplexPattern uses that don't have their name taken yet. 265 // The OPC_CheckComplexPattern operation implicitly records the results. 266 if (N->getName().empty()) { 267 std::string S; 268 raw_string_ostream OS(S); 269 OS << "We expect complex pattern uses to have names: " << *N; 270 PrintFatalError(S); 271 } 272 273 // Remember this ComplexPattern so that we can emit it after all the other 274 // structural matches are done. 275 unsigned InputOperand = VariableMap[N->getName()] - 1; 276 MatchedComplexPatterns.push_back(std::make_pair(N, InputOperand)); 277 return; 278 } 279 280 if (LeafRec->getName() == "immAllOnesV" || 281 LeafRec->getName() == "immAllZerosV") { 282 // If this is the root of the dag we're matching, we emit a redundant opcode 283 // check to ensure that this gets folded into the normal top-level 284 // OpcodeSwitch. 285 if (N == Pattern.getSrcPattern()) { 286 MVT VT = N->getSimpleType(0); 287 StringRef Name = VT.isScalableVector() ? "splat_vector" : "build_vector"; 288 const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed(Name)); 289 AddMatcher(new CheckOpcodeMatcher(NI)); 290 } 291 if (LeafRec->getName() == "immAllOnesV") 292 AddMatcher(new CheckImmAllOnesVMatcher()); 293 else 294 AddMatcher(new CheckImmAllZerosVMatcher()); 295 return; 296 } 297 298 errs() << "Unknown leaf kind: " << *N << "\n"; 299 abort(); 300 } 301 302 void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N, 303 TreePatternNode *NodeNoTypes) { 304 assert(!N->isLeaf() && "Not an operator?"); 305 306 if (N->getOperator()->isSubClassOf("ComplexPattern")) { 307 // The "name" of a non-leaf complex pattern (MY_PAT $op1, $op2) is 308 // "MY_PAT:op1:op2". We should already have validated that the uses are 309 // consistent. 310 std::string PatternName = std::string(N->getOperator()->getName()); 311 for (unsigned i = 0; i < N->getNumChildren(); ++i) { 312 PatternName += ":"; 313 PatternName += N->getChild(i)->getName(); 314 } 315 316 if (recordUniqueNode(PatternName)) { 317 auto NodeAndOpNum = std::make_pair(N, NextRecordedOperandNo - 1); 318 MatchedComplexPatterns.push_back(NodeAndOpNum); 319 } 320 321 return; 322 } 323 324 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator()); 325 326 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is 327 // a constant without a predicate fn that has more than one bit set, handle 328 // this as a special case. This is usually for targets that have special 329 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit 330 // handling stuff). Using these instructions is often far more efficient 331 // than materializing the constant. Unfortunately, both the instcombiner 332 // and the dag combiner can often infer that bits are dead, and thus drop 333 // them from the mask in the dag. For example, it might turn 'AND X, 255' 334 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks 335 // to handle this. 336 if ((N->getOperator()->getName() == "and" || 337 N->getOperator()->getName() == "or") && 338 N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateCalls().empty() && 339 N->getPredicateCalls().empty()) { 340 if (IntInit *II = dyn_cast<IntInit>(N->getChild(1)->getLeafValue())) { 341 if (!llvm::has_single_bit<uint32_t>( 342 II->getValue())) { // Don't bother with single bits. 343 // If this is at the root of the pattern, we emit a redundant 344 // CheckOpcode so that the following checks get factored properly under 345 // a single opcode check. 346 if (N == Pattern.getSrcPattern()) 347 AddMatcher(new CheckOpcodeMatcher(CInfo)); 348 349 // Emit the CheckAndImm/CheckOrImm node. 350 if (N->getOperator()->getName() == "and") 351 AddMatcher(new CheckAndImmMatcher(II->getValue())); 352 else 353 AddMatcher(new CheckOrImmMatcher(II->getValue())); 354 355 // Match the LHS of the AND as appropriate. 356 AddMatcher(new MoveChildMatcher(0)); 357 EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0)); 358 AddMatcher(new MoveParentMatcher()); 359 return; 360 } 361 } 362 } 363 364 // Check that the current opcode lines up. 365 AddMatcher(new CheckOpcodeMatcher(CInfo)); 366 367 // If this node has memory references (i.e. is a load or store), tell the 368 // interpreter to capture them in the memref array. 369 if (N->NodeHasProperty(SDNPMemOperand, CGP)) 370 AddMatcher(new RecordMemRefMatcher()); 371 372 // If this node has a chain, then the chain is operand #0 is the SDNode, and 373 // the child numbers of the node are all offset by one. 374 unsigned OpNo = 0; 375 if (N->NodeHasProperty(SDNPHasChain, CGP)) { 376 // Record the node and remember it in our chained nodes list. 377 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName().str() + 378 "' chained node", 379 NextRecordedOperandNo)); 380 // Remember all of the input chains our pattern will match. 381 MatchedChainNodes.push_back(NextRecordedOperandNo++); 382 383 // Don't look at the input chain when matching the tree pattern to the 384 // SDNode. 385 OpNo = 1; 386 387 // If this node is not the root and the subtree underneath it produces a 388 // chain, then the result of matching the node is also produce a chain. 389 // Beyond that, this means that we're also folding (at least) the root node 390 // into the node that produce the chain (for example, matching 391 // "(add reg, (load ptr))" as a add_with_memory on X86). This is 392 // problematic, if the 'reg' node also uses the load (say, its chain). 393 // Graphically: 394 // 395 // [LD] 396 // ^ ^ 397 // | \ DAG's like cheese. 398 // / | 399 // / [YY] 400 // | ^ 401 // [XX]--/ 402 // 403 // It would be invalid to fold XX and LD. In this case, folding the two 404 // nodes together would induce a cycle in the DAG, making it a 'cyclic DAG' 405 // To prevent this, we emit a dynamic check for legality before allowing 406 // this to be folded. 407 // 408 const TreePatternNode *Root = Pattern.getSrcPattern(); 409 if (N != Root) { // Not the root of the pattern. 410 // If there is a node between the root and this node, then we definitely 411 // need to emit the check. 412 bool NeedCheck = !Root->hasChild(N); 413 414 // If it *is* an immediate child of the root, we can still need a check if 415 // the root SDNode has multiple inputs. For us, this means that it is an 416 // intrinsic, has multiple operands, or has other inputs like chain or 417 // glue). 418 if (!NeedCheck) { 419 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator()); 420 NeedCheck = 421 Root->getOperator() == CGP.get_intrinsic_void_sdnode() || 422 Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() || 423 Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() || 424 PInfo.getNumOperands() > 1 || 425 PInfo.hasProperty(SDNPHasChain) || 426 PInfo.hasProperty(SDNPInGlue) || 427 PInfo.hasProperty(SDNPOptInGlue); 428 } 429 430 if (NeedCheck) 431 AddMatcher(new CheckFoldableChainNodeMatcher()); 432 } 433 } 434 435 // If this node has an output glue and isn't the root, remember it. 436 if (N->NodeHasProperty(SDNPOutGlue, CGP) && 437 N != Pattern.getSrcPattern()) { 438 // TODO: This redundantly records nodes with both glues and chains. 439 440 // Record the node and remember it in our chained nodes list. 441 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName().str() + 442 "' glue output node", 443 NextRecordedOperandNo)); 444 } 445 446 // If this node is known to have an input glue or if it *might* have an input 447 // glue, capture it as the glue input of the pattern. 448 if (N->NodeHasProperty(SDNPOptInGlue, CGP) || 449 N->NodeHasProperty(SDNPInGlue, CGP)) 450 AddMatcher(new CaptureGlueInputMatcher()); 451 452 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) { 453 // Get the code suitable for matching this child. Move to the child, check 454 // it then move back to the parent. 455 AddMatcher(new MoveChildMatcher(OpNo)); 456 EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i)); 457 AddMatcher(new MoveParentMatcher()); 458 } 459 } 460 461 bool MatcherGen::recordUniqueNode(ArrayRef<std::string> Names) { 462 unsigned Entry = 0; 463 for (const std::string &Name : Names) { 464 unsigned &VarMapEntry = VariableMap[Name]; 465 if (!Entry) 466 Entry = VarMapEntry; 467 assert(Entry == VarMapEntry); 468 } 469 470 bool NewRecord = false; 471 if (Entry == 0) { 472 // If it is a named node, we must emit a 'Record' opcode. 473 std::string WhatFor; 474 for (const std::string &Name : Names) { 475 if (!WhatFor.empty()) 476 WhatFor += ','; 477 WhatFor += "$" + Name; 478 } 479 AddMatcher(new RecordMatcher(WhatFor, NextRecordedOperandNo)); 480 Entry = ++NextRecordedOperandNo; 481 NewRecord = true; 482 } else { 483 // If we get here, this is a second reference to a specific name. Since 484 // we already have checked that the first reference is valid, we don't 485 // have to recursively match it, just check that it's the same as the 486 // previously named thing. 487 AddMatcher(new CheckSameMatcher(Entry-1)); 488 } 489 490 for (const std::string &Name : Names) 491 VariableMap[Name] = Entry; 492 493 return NewRecord; 494 } 495 496 void MatcherGen::EmitMatchCode(const TreePatternNode *N, 497 TreePatternNode *NodeNoTypes) { 498 // If N and NodeNoTypes don't agree on a type, then this is a case where we 499 // need to do a type check. Emit the check, apply the type to NodeNoTypes and 500 // reinfer any correlated types. 501 SmallVector<unsigned, 2> ResultsToTypeCheck; 502 503 for (unsigned i = 0, e = NodeNoTypes->getNumTypes(); i != e; ++i) { 504 if (NodeNoTypes->getExtType(i) == N->getExtType(i)) continue; 505 NodeNoTypes->setType(i, N->getExtType(i)); 506 InferPossibleTypes(); 507 ResultsToTypeCheck.push_back(i); 508 } 509 510 // If this node has a name associated with it, capture it in VariableMap. If 511 // we already saw this in the pattern, emit code to verify dagness. 512 SmallVector<std::string, 4> Names; 513 if (!N->getName().empty()) 514 Names.push_back(N->getName()); 515 516 for (const ScopedName &Name : N->getNamesAsPredicateArg()) { 517 Names.push_back(("pred:" + Twine(Name.getScope()) + ":" + Name.getIdentifier()).str()); 518 } 519 520 if (!Names.empty()) { 521 if (!recordUniqueNode(Names)) 522 return; 523 } 524 525 if (N->isLeaf()) 526 EmitLeafMatchCode(N); 527 else 528 EmitOperatorMatchCode(N, NodeNoTypes); 529 530 // If there are node predicates for this node, generate their checks. 531 for (unsigned i = 0, e = N->getPredicateCalls().size(); i != e; ++i) { 532 const TreePredicateCall &Pred = N->getPredicateCalls()[i]; 533 SmallVector<unsigned, 4> Operands; 534 if (Pred.Fn.usesOperands()) { 535 TreePattern *TP = Pred.Fn.getOrigPatFragRecord(); 536 for (unsigned i = 0; i < TP->getNumArgs(); ++i) { 537 std::string Name = 538 ("pred:" + Twine(Pred.Scope) + ":" + TP->getArgName(i)).str(); 539 Operands.push_back(getNamedArgumentSlot(Name)); 540 } 541 } 542 AddMatcher(new CheckPredicateMatcher(Pred.Fn, Operands)); 543 } 544 545 for (unsigned i = 0, e = ResultsToTypeCheck.size(); i != e; ++i) 546 AddMatcher(new CheckTypeMatcher(N->getSimpleType(ResultsToTypeCheck[i]), 547 ResultsToTypeCheck[i])); 548 } 549 550 /// EmitMatcherCode - Generate the code that matches the predicate of this 551 /// pattern for the specified Variant. If the variant is invalid this returns 552 /// true and does not generate code, if it is valid, it returns false. 553 bool MatcherGen::EmitMatcherCode(unsigned Variant) { 554 // If the root of the pattern is a ComplexPattern and if it is specified to 555 // match some number of root opcodes, these are considered to be our variants. 556 // Depending on which variant we're generating code for, emit the root opcode 557 // check. 558 if (const ComplexPattern *CP = 559 Pattern.getSrcPattern()->getComplexPatternInfo(CGP)) { 560 const std::vector<Record*> &OpNodes = CP->getRootNodes(); 561 assert(!OpNodes.empty() &&"Complex Pattern must specify what it can match"); 562 if (Variant >= OpNodes.size()) return true; 563 564 AddMatcher(new CheckOpcodeMatcher(CGP.getSDNodeInfo(OpNodes[Variant]))); 565 } else { 566 if (Variant != 0) return true; 567 } 568 569 // Emit the matcher for the pattern structure and types. 570 EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes.get()); 571 572 // If the pattern has a predicate on it (e.g. only enabled when a subtarget 573 // feature is around, do the check). 574 std::string PredicateCheck = Pattern.getPredicateCheck(); 575 if (!PredicateCheck.empty()) 576 AddMatcher(new CheckPatternPredicateMatcher(PredicateCheck)); 577 578 // Now that we've completed the structural type match, emit any ComplexPattern 579 // checks (e.g. addrmode matches). We emit this after the structural match 580 // because they are generally more expensive to evaluate and more difficult to 581 // factor. 582 for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i) { 583 auto N = MatchedComplexPatterns[i].first; 584 585 // Remember where the results of this match get stuck. 586 if (N->isLeaf()) { 587 NamedComplexPatternOperands[N->getName()] = NextRecordedOperandNo + 1; 588 } else { 589 unsigned CurOp = NextRecordedOperandNo; 590 for (unsigned i = 0; i < N->getNumChildren(); ++i) { 591 NamedComplexPatternOperands[N->getChild(i)->getName()] = CurOp + 1; 592 CurOp += N->getChild(i)->getNumMIResults(CGP); 593 } 594 } 595 596 // Get the slot we recorded the value in from the name on the node. 597 unsigned RecNodeEntry = MatchedComplexPatterns[i].second; 598 599 const ComplexPattern *CP = N->getComplexPatternInfo(CGP); 600 assert(CP && "Not a valid ComplexPattern!"); 601 602 // Emit a CheckComplexPat operation, which does the match (aborting if it 603 // fails) and pushes the matched operands onto the recorded nodes list. 604 AddMatcher(new CheckComplexPatMatcher(*CP, RecNodeEntry, N->getName(), 605 NextRecordedOperandNo)); 606 607 // Record the right number of operands. 608 NextRecordedOperandNo += CP->getNumOperands(); 609 if (CP->hasProperty(SDNPHasChain)) { 610 // If the complex pattern has a chain, then we need to keep track of the 611 // fact that we just recorded a chain input. The chain input will be 612 // matched as the last operand of the predicate if it was successful. 613 ++NextRecordedOperandNo; // Chained node operand. 614 615 // It is the last operand recorded. 616 assert(NextRecordedOperandNo > 1 && 617 "Should have recorded input/result chains at least!"); 618 MatchedChainNodes.push_back(NextRecordedOperandNo-1); 619 } 620 621 // TODO: Complex patterns can't have output glues, if they did, we'd want 622 // to record them. 623 } 624 625 return false; 626 } 627 628 629 //===----------------------------------------------------------------------===// 630 // Node Result Generation 631 //===----------------------------------------------------------------------===// 632 633 void MatcherGen::EmitResultOfNamedOperand(const TreePatternNode *N, 634 SmallVectorImpl<unsigned> &ResultOps){ 635 assert(!N->getName().empty() && "Operand not named!"); 636 637 if (unsigned SlotNo = NamedComplexPatternOperands[N->getName()]) { 638 // Complex operands have already been completely selected, just find the 639 // right slot ant add the arguments directly. 640 for (unsigned i = 0; i < N->getNumMIResults(CGP); ++i) 641 ResultOps.push_back(SlotNo - 1 + i); 642 643 return; 644 } 645 646 unsigned SlotNo = getNamedArgumentSlot(N->getName()); 647 648 // If this is an 'imm' or 'fpimm' node, make sure to convert it to the target 649 // version of the immediate so that it doesn't get selected due to some other 650 // node use. 651 if (!N->isLeaf()) { 652 StringRef OperatorName = N->getOperator()->getName(); 653 if (OperatorName == "imm" || OperatorName == "fpimm") { 654 AddMatcher(new EmitConvertToTargetMatcher(SlotNo)); 655 ResultOps.push_back(NextRecordedOperandNo++); 656 return; 657 } 658 } 659 660 for (unsigned i = 0; i < N->getNumMIResults(CGP); ++i) 661 ResultOps.push_back(SlotNo + i); 662 } 663 664 void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode *N, 665 SmallVectorImpl<unsigned> &ResultOps) { 666 assert(N->isLeaf() && "Must be a leaf"); 667 668 if (IntInit *II = dyn_cast<IntInit>(N->getLeafValue())) { 669 AddMatcher(new EmitIntegerMatcher(II->getValue(), N->getSimpleType(0))); 670 ResultOps.push_back(NextRecordedOperandNo++); 671 return; 672 } 673 674 // If this is an explicit register reference, handle it. 675 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) { 676 Record *Def = DI->getDef(); 677 if (Def->isSubClassOf("Register")) { 678 const CodeGenRegister *Reg = 679 CGP.getTargetInfo().getRegBank().getReg(Def); 680 AddMatcher(new EmitRegisterMatcher(Reg, N->getSimpleType(0))); 681 ResultOps.push_back(NextRecordedOperandNo++); 682 return; 683 } 684 685 if (Def->getName() == "zero_reg") { 686 AddMatcher(new EmitRegisterMatcher(nullptr, N->getSimpleType(0))); 687 ResultOps.push_back(NextRecordedOperandNo++); 688 return; 689 } 690 691 if (Def->getName() == "undef_tied_input") { 692 MVT::SimpleValueType ResultVT = N->getSimpleType(0); 693 auto IDOperandNo = NextRecordedOperandNo++; 694 Record *ImpDef = Def->getRecords().getDef("IMPLICIT_DEF"); 695 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(ImpDef); 696 AddMatcher(new EmitNodeMatcher(II, ResultVT, std::nullopt, false, false, 697 false, false, -1, IDOperandNo)); 698 ResultOps.push_back(IDOperandNo); 699 return; 700 } 701 702 // Handle a reference to a register class. This is used 703 // in COPY_TO_SUBREG instructions. 704 if (Def->isSubClassOf("RegisterOperand")) 705 Def = Def->getValueAsDef("RegClass"); 706 if (Def->isSubClassOf("RegisterClass")) { 707 // If the register class has an enum integer value greater than 127, the 708 // encoding overflows the limit of 7 bits, which precludes the use of 709 // StringIntegerMatcher. In this case, fallback to using IntegerMatcher. 710 const CodeGenRegisterClass &RC = 711 CGP.getTargetInfo().getRegisterClass(Def); 712 if (RC.EnumValue <= 127) { 713 std::string Value = getQualifiedName(Def) + "RegClassID"; 714 AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32)); 715 ResultOps.push_back(NextRecordedOperandNo++); 716 } else { 717 AddMatcher(new EmitIntegerMatcher(RC.EnumValue, MVT::i32)); 718 ResultOps.push_back(NextRecordedOperandNo++); 719 } 720 return; 721 } 722 723 // Handle a subregister index. This is used for INSERT_SUBREG etc. 724 if (Def->isSubClassOf("SubRegIndex")) { 725 const CodeGenRegBank &RB = CGP.getTargetInfo().getRegBank(); 726 // If we have more than 127 subreg indices the encoding can overflow 727 // 7 bit and we cannot use StringInteger. 728 if (RB.getSubRegIndices().size() > 127) { 729 const CodeGenSubRegIndex *I = RB.findSubRegIdx(Def); 730 assert(I && "Cannot find subreg index by name!"); 731 if (I->EnumValue > 127) { 732 AddMatcher(new EmitIntegerMatcher(I->EnumValue, MVT::i32)); 733 ResultOps.push_back(NextRecordedOperandNo++); 734 return; 735 } 736 } 737 std::string Value = getQualifiedName(Def); 738 AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32)); 739 ResultOps.push_back(NextRecordedOperandNo++); 740 return; 741 } 742 } 743 744 errs() << "unhandled leaf node:\n"; 745 N->dump(); 746 } 747 748 static bool 749 mayInstNodeLoadOrStore(const TreePatternNode *N, 750 const CodeGenDAGPatterns &CGP) { 751 Record *Op = N->getOperator(); 752 const CodeGenTarget &CGT = CGP.getTargetInfo(); 753 CodeGenInstruction &II = CGT.getInstruction(Op); 754 return II.mayLoad || II.mayStore; 755 } 756 757 static unsigned 758 numNodesThatMayLoadOrStore(const TreePatternNode *N, 759 const CodeGenDAGPatterns &CGP) { 760 if (N->isLeaf()) 761 return 0; 762 763 Record *OpRec = N->getOperator(); 764 if (!OpRec->isSubClassOf("Instruction")) 765 return 0; 766 767 unsigned Count = 0; 768 if (mayInstNodeLoadOrStore(N, CGP)) 769 ++Count; 770 771 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) 772 Count += numNodesThatMayLoadOrStore(N->getChild(i), CGP); 773 774 return Count; 775 } 776 777 void MatcherGen:: 778 EmitResultInstructionAsOperand(const TreePatternNode *N, 779 SmallVectorImpl<unsigned> &OutputOps) { 780 Record *Op = N->getOperator(); 781 const CodeGenTarget &CGT = CGP.getTargetInfo(); 782 CodeGenInstruction &II = CGT.getInstruction(Op); 783 const DAGInstruction &Inst = CGP.getInstruction(Op); 784 785 bool isRoot = N == Pattern.getDstPattern(); 786 787 // TreeHasOutGlue - True if this tree has glue. 788 bool TreeHasInGlue = false, TreeHasOutGlue = false; 789 if (isRoot) { 790 const TreePatternNode *SrcPat = Pattern.getSrcPattern(); 791 TreeHasInGlue = SrcPat->TreeHasProperty(SDNPOptInGlue, CGP) || 792 SrcPat->TreeHasProperty(SDNPInGlue, CGP); 793 794 // FIXME2: this is checking the entire pattern, not just the node in 795 // question, doing this just for the root seems like a total hack. 796 TreeHasOutGlue = SrcPat->TreeHasProperty(SDNPOutGlue, CGP); 797 } 798 799 // NumResults - This is the number of results produced by the instruction in 800 // the "outs" list. 801 unsigned NumResults = Inst.getNumResults(); 802 803 // Number of operands we know the output instruction must have. If it is 804 // variadic, we could have more operands. 805 unsigned NumFixedOperands = II.Operands.size(); 806 807 SmallVector<unsigned, 8> InstOps; 808 809 // Loop over all of the fixed operands of the instruction pattern, emitting 810 // code to fill them all in. The node 'N' usually has number children equal to 811 // the number of input operands of the instruction. However, in cases where 812 // there are predicate operands for an instruction, we need to fill in the 813 // 'execute always' values. Match up the node operands to the instruction 814 // operands to do this. 815 unsigned ChildNo = 0; 816 817 // Similarly to the code in TreePatternNode::ApplyTypeConstraints, count the 818 // number of operands at the end of the list which have default values. 819 // Those can come from the pattern if it provides enough arguments, or be 820 // filled in with the default if the pattern hasn't provided them. But any 821 // operand with a default value _before_ the last mandatory one will be 822 // filled in with their defaults unconditionally. 823 unsigned NonOverridableOperands = NumFixedOperands; 824 while (NonOverridableOperands > NumResults && 825 CGP.operandHasDefault(II.Operands[NonOverridableOperands-1].Rec)) 826 --NonOverridableOperands; 827 828 for (unsigned InstOpNo = NumResults, e = NumFixedOperands; 829 InstOpNo != e; ++InstOpNo) { 830 // Determine what to emit for this operand. 831 Record *OperandNode = II.Operands[InstOpNo].Rec; 832 if (CGP.operandHasDefault(OperandNode) && 833 (InstOpNo < NonOverridableOperands || ChildNo >= N->getNumChildren())) { 834 // This is a predicate or optional def operand which the pattern has not 835 // overridden, or which we aren't letting it override; emit the 'default 836 // ops' operands. 837 const DAGDefaultOperand &DefaultOp 838 = CGP.getDefaultOperand(OperandNode); 839 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) 840 EmitResultOperand(DefaultOp.DefaultOps[i].get(), InstOps); 841 continue; 842 } 843 844 // Otherwise this is a normal operand or a predicate operand without 845 // 'execute always'; emit it. 846 847 // For operands with multiple sub-operands we may need to emit 848 // multiple child patterns to cover them all. However, ComplexPattern 849 // children may themselves emit multiple MI operands. 850 unsigned NumSubOps = 1; 851 if (OperandNode->isSubClassOf("Operand")) { 852 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo"); 853 if (unsigned NumArgs = MIOpInfo->getNumArgs()) 854 NumSubOps = NumArgs; 855 } 856 857 unsigned FinalNumOps = InstOps.size() + NumSubOps; 858 while (InstOps.size() < FinalNumOps) { 859 const TreePatternNode *Child = N->getChild(ChildNo); 860 unsigned BeforeAddingNumOps = InstOps.size(); 861 EmitResultOperand(Child, InstOps); 862 assert(InstOps.size() > BeforeAddingNumOps && "Didn't add any operands"); 863 864 // If the operand is an instruction and it produced multiple results, just 865 // take the first one. 866 if (!Child->isLeaf() && Child->getOperator()->isSubClassOf("Instruction")) 867 InstOps.resize(BeforeAddingNumOps+1); 868 869 ++ChildNo; 870 } 871 } 872 873 // If this is a variadic output instruction (i.e. REG_SEQUENCE), we can't 874 // expand suboperands, use default operands, or other features determined from 875 // the CodeGenInstruction after the fixed operands, which were handled 876 // above. Emit the remaining instructions implicitly added by the use for 877 // variable_ops. 878 if (II.Operands.isVariadic) { 879 for (unsigned I = ChildNo, E = N->getNumChildren(); I < E; ++I) 880 EmitResultOperand(N->getChild(I), InstOps); 881 } 882 883 // If this node has input glue or explicitly specified input physregs, we 884 // need to add chained and glued copyfromreg nodes and materialize the glue 885 // input. 886 if (isRoot && !PhysRegInputs.empty()) { 887 // Emit all of the CopyToReg nodes for the input physical registers. These 888 // occur in patterns like (mul:i8 AL:i8, GR8:i8:$src). 889 for (unsigned i = 0, e = PhysRegInputs.size(); i != e; ++i) { 890 const CodeGenRegister *Reg = 891 CGP.getTargetInfo().getRegBank().getReg(PhysRegInputs[i].first); 892 AddMatcher(new EmitCopyToRegMatcher(PhysRegInputs[i].second, 893 Reg)); 894 } 895 896 // Even if the node has no other glue inputs, the resultant node must be 897 // glued to the CopyFromReg nodes we just generated. 898 TreeHasInGlue = true; 899 } 900 901 // Result order: node results, chain, glue 902 903 // Determine the result types. 904 SmallVector<MVT::SimpleValueType, 4> ResultVTs; 905 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) 906 ResultVTs.push_back(N->getSimpleType(i)); 907 908 // If this is the root instruction of a pattern that has physical registers in 909 // its result pattern, add output VTs for them. For example, X86 has: 910 // (set AL, (mul ...)) 911 // This also handles implicit results like: 912 // (implicit EFLAGS) 913 if (isRoot && !Pattern.getDstRegs().empty()) { 914 // If the root came from an implicit def in the instruction handling stuff, 915 // don't re-add it. 916 Record *HandledReg = nullptr; 917 if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other) 918 HandledReg = II.ImplicitDefs[0]; 919 920 for (Record *Reg : Pattern.getDstRegs()) { 921 if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue; 922 ResultVTs.push_back(getRegisterValueType(Reg, CGT)); 923 } 924 } 925 926 // If this is the root of the pattern and the pattern we're matching includes 927 // a node that is variadic, mark the generated node as variadic so that it 928 // gets the excess operands from the input DAG. 929 int NumFixedArityOperands = -1; 930 if (isRoot && 931 Pattern.getSrcPattern()->NodeHasProperty(SDNPVariadic, CGP)) 932 NumFixedArityOperands = Pattern.getSrcPattern()->getNumChildren(); 933 934 // If this is the root node and multiple matched nodes in the input pattern 935 // have MemRefs in them, have the interpreter collect them and plop them onto 936 // this node. If there is just one node with MemRefs, leave them on that node 937 // even if it is not the root. 938 // 939 // FIXME3: This is actively incorrect for result patterns with multiple 940 // memory-referencing instructions. 941 bool PatternHasMemOperands = 942 Pattern.getSrcPattern()->TreeHasProperty(SDNPMemOperand, CGP); 943 944 bool NodeHasMemRefs = false; 945 if (PatternHasMemOperands) { 946 unsigned NumNodesThatLoadOrStore = 947 numNodesThatMayLoadOrStore(Pattern.getDstPattern(), CGP); 948 bool NodeIsUniqueLoadOrStore = mayInstNodeLoadOrStore(N, CGP) && 949 NumNodesThatLoadOrStore == 1; 950 NodeHasMemRefs = 951 NodeIsUniqueLoadOrStore || (isRoot && (mayInstNodeLoadOrStore(N, CGP) || 952 NumNodesThatLoadOrStore != 1)); 953 } 954 955 // Determine whether we need to attach a chain to this node. 956 bool NodeHasChain = false; 957 if (Pattern.getSrcPattern()->TreeHasProperty(SDNPHasChain, CGP)) { 958 // For some instructions, we were able to infer from the pattern whether 959 // they should have a chain. Otherwise, attach the chain to the root. 960 // 961 // FIXME2: This is extremely dubious for several reasons, not the least of 962 // which it gives special status to instructions with patterns that Pat<> 963 // nodes can't duplicate. 964 if (II.hasChain_Inferred) 965 NodeHasChain = II.hasChain; 966 else 967 NodeHasChain = isRoot; 968 // Instructions which load and store from memory should have a chain, 969 // regardless of whether they happen to have a pattern saying so. 970 if (II.hasCtrlDep || II.mayLoad || II.mayStore || II.canFoldAsLoad || 971 II.hasSideEffects) 972 NodeHasChain = true; 973 } 974 975 assert((!ResultVTs.empty() || TreeHasOutGlue || NodeHasChain) && 976 "Node has no result"); 977 978 AddMatcher(new EmitNodeMatcher(II, ResultVTs, InstOps, NodeHasChain, 979 TreeHasInGlue, TreeHasOutGlue, NodeHasMemRefs, 980 NumFixedArityOperands, NextRecordedOperandNo)); 981 982 // The non-chain and non-glue results of the newly emitted node get recorded. 983 for (unsigned i = 0, e = ResultVTs.size(); i != e; ++i) { 984 if (ResultVTs[i] == MVT::Other || ResultVTs[i] == MVT::Glue) break; 985 OutputOps.push_back(NextRecordedOperandNo++); 986 } 987 } 988 989 void MatcherGen:: 990 EmitResultSDNodeXFormAsOperand(const TreePatternNode *N, 991 SmallVectorImpl<unsigned> &ResultOps) { 992 assert(N->getOperator()->isSubClassOf("SDNodeXForm") && "Not SDNodeXForm?"); 993 994 // Emit the operand. 995 SmallVector<unsigned, 8> InputOps; 996 997 // FIXME2: Could easily generalize this to support multiple inputs and outputs 998 // to the SDNodeXForm. For now we just support one input and one output like 999 // the old instruction selector. 1000 assert(N->getNumChildren() == 1); 1001 EmitResultOperand(N->getChild(0), InputOps); 1002 1003 // The input currently must have produced exactly one result. 1004 assert(InputOps.size() == 1 && "Unexpected input to SDNodeXForm"); 1005 1006 AddMatcher(new EmitNodeXFormMatcher(InputOps[0], N->getOperator())); 1007 ResultOps.push_back(NextRecordedOperandNo++); 1008 } 1009 1010 void MatcherGen::EmitResultOperand(const TreePatternNode *N, 1011 SmallVectorImpl<unsigned> &ResultOps) { 1012 // This is something selected from the pattern we matched. 1013 if (!N->getName().empty()) 1014 return EmitResultOfNamedOperand(N, ResultOps); 1015 1016 if (N->isLeaf()) 1017 return EmitResultLeafAsOperand(N, ResultOps); 1018 1019 Record *OpRec = N->getOperator(); 1020 if (OpRec->isSubClassOf("Instruction")) 1021 return EmitResultInstructionAsOperand(N, ResultOps); 1022 if (OpRec->isSubClassOf("SDNodeXForm")) 1023 return EmitResultSDNodeXFormAsOperand(N, ResultOps); 1024 errs() << "Unknown result node to emit code for: " << *N << '\n'; 1025 PrintFatalError("Unknown node in result pattern!"); 1026 } 1027 1028 void MatcherGen::EmitResultCode() { 1029 // Patterns that match nodes with (potentially multiple) chain inputs have to 1030 // merge them together into a token factor. This informs the generated code 1031 // what all the chained nodes are. 1032 if (!MatchedChainNodes.empty()) 1033 AddMatcher(new EmitMergeInputChainsMatcher(MatchedChainNodes)); 1034 1035 // Codegen the root of the result pattern, capturing the resulting values. 1036 SmallVector<unsigned, 8> Ops; 1037 EmitResultOperand(Pattern.getDstPattern(), Ops); 1038 1039 // At this point, we have however many values the result pattern produces. 1040 // However, the input pattern might not need all of these. If there are 1041 // excess values at the end (such as implicit defs of condition codes etc) 1042 // just lop them off. This doesn't need to worry about glue or chains, just 1043 // explicit results. 1044 // 1045 unsigned NumSrcResults = Pattern.getSrcPattern()->getNumTypes(); 1046 1047 // If the pattern also has (implicit) results, count them as well. 1048 if (!Pattern.getDstRegs().empty()) { 1049 // If the root came from an implicit def in the instruction handling stuff, 1050 // don't re-add it. 1051 Record *HandledReg = nullptr; 1052 const TreePatternNode *DstPat = Pattern.getDstPattern(); 1053 if (!DstPat->isLeaf() &&DstPat->getOperator()->isSubClassOf("Instruction")){ 1054 const CodeGenTarget &CGT = CGP.getTargetInfo(); 1055 CodeGenInstruction &II = CGT.getInstruction(DstPat->getOperator()); 1056 1057 if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other) 1058 HandledReg = II.ImplicitDefs[0]; 1059 } 1060 1061 for (Record *Reg : Pattern.getDstRegs()) { 1062 if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue; 1063 ++NumSrcResults; 1064 } 1065 } 1066 1067 SmallVector<unsigned, 8> Results(Ops); 1068 1069 // Apply result permutation. 1070 for (unsigned ResNo = 0; ResNo < Pattern.getDstPattern()->getNumResults(); 1071 ++ResNo) { 1072 Results[ResNo] = Ops[Pattern.getDstPattern()->getResultIndex(ResNo)]; 1073 } 1074 1075 Results.resize(NumSrcResults); 1076 AddMatcher(new CompleteMatchMatcher(Results, Pattern)); 1077 } 1078 1079 1080 /// ConvertPatternToMatcher - Create the matcher for the specified pattern with 1081 /// the specified variant. If the variant number is invalid, this returns null. 1082 Matcher *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern, 1083 unsigned Variant, 1084 const CodeGenDAGPatterns &CGP) { 1085 MatcherGen Gen(Pattern, CGP); 1086 1087 // Generate the code for the matcher. 1088 if (Gen.EmitMatcherCode(Variant)) 1089 return nullptr; 1090 1091 // FIXME2: Kill extra MoveParent commands at the end of the matcher sequence. 1092 // FIXME2: Split result code out to another table, and make the matcher end 1093 // with an "Emit <index>" command. This allows result generation stuff to be 1094 // shared and factored? 1095 1096 // If the match succeeds, then we generate Pattern. 1097 Gen.EmitResultCode(); 1098 1099 // Unconditional match. 1100 return Gen.GetMatcher(); 1101 } 1102