1 ///===- FastISelEmitter.cpp - Generate an instruction selector -------------===// 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 tablegen backend emits code for use by the "fast" instruction 10 // selection algorithm. See the comments at the top of 11 // lib/CodeGen/SelectionDAG/FastISel.cpp for background. 12 // 13 // This file scans through the target's tablegen instruction-info files 14 // and extracts instructions with obvious-looking patterns, and it emits 15 // code to look up these instructions by type and operator. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "CodeGenDAGPatterns.h" 20 #include "CodeGenInstruction.h" 21 #include "llvm/ADT/StringSwitch.h" 22 #include "llvm/Support/Debug.h" 23 #include "llvm/Support/ErrorHandling.h" 24 #include "llvm/TableGen/Error.h" 25 #include "llvm/TableGen/Record.h" 26 #include "llvm/TableGen/TableGenBackend.h" 27 #include <utility> 28 using namespace llvm; 29 30 31 /// InstructionMemo - This class holds additional information about an 32 /// instruction needed to emit code for it. 33 /// 34 namespace { 35 struct InstructionMemo { 36 std::string Name; 37 const CodeGenRegisterClass *RC; 38 std::string SubRegNo; 39 std::vector<std::string> PhysRegs; 40 std::string PredicateCheck; 41 42 InstructionMemo(StringRef Name, const CodeGenRegisterClass *RC, 43 std::string SubRegNo, std::vector<std::string> PhysRegs, 44 std::string PredicateCheck) 45 : Name(Name), RC(RC), SubRegNo(std::move(SubRegNo)), 46 PhysRegs(std::move(PhysRegs)), 47 PredicateCheck(std::move(PredicateCheck)) {} 48 49 // Make sure we do not copy InstructionMemo. 50 InstructionMemo(const InstructionMemo &Other) = delete; 51 InstructionMemo(InstructionMemo &&Other) = default; 52 }; 53 } // End anonymous namespace 54 55 /// ImmPredicateSet - This uniques predicates (represented as a string) and 56 /// gives them unique (small) integer ID's that start at 0. 57 namespace { 58 class ImmPredicateSet { 59 DenseMap<TreePattern *, unsigned> ImmIDs; 60 std::vector<TreePredicateFn> PredsByName; 61 public: 62 63 unsigned getIDFor(TreePredicateFn Pred) { 64 unsigned &Entry = ImmIDs[Pred.getOrigPatFragRecord()]; 65 if (Entry == 0) { 66 PredsByName.push_back(Pred); 67 Entry = PredsByName.size(); 68 } 69 return Entry-1; 70 } 71 72 const TreePredicateFn &getPredicate(unsigned i) { 73 assert(i < PredsByName.size()); 74 return PredsByName[i]; 75 } 76 77 typedef std::vector<TreePredicateFn>::const_iterator iterator; 78 iterator begin() const { return PredsByName.begin(); } 79 iterator end() const { return PredsByName.end(); } 80 81 }; 82 } // End anonymous namespace 83 84 /// OperandsSignature - This class holds a description of a list of operand 85 /// types. It has utility methods for emitting text based on the operands. 86 /// 87 namespace { 88 struct OperandsSignature { 89 class OpKind { 90 enum { OK_Reg, OK_FP, OK_Imm, OK_Invalid = -1 }; 91 char Repr; 92 public: 93 94 OpKind() : Repr(OK_Invalid) {} 95 96 bool operator<(OpKind RHS) const { return Repr < RHS.Repr; } 97 bool operator==(OpKind RHS) const { return Repr == RHS.Repr; } 98 99 static OpKind getReg() { OpKind K; K.Repr = OK_Reg; return K; } 100 static OpKind getFP() { OpKind K; K.Repr = OK_FP; return K; } 101 static OpKind getImm(unsigned V) { 102 assert((unsigned)OK_Imm+V < 128 && 103 "Too many integer predicates for the 'Repr' char"); 104 OpKind K; K.Repr = OK_Imm+V; return K; 105 } 106 107 bool isReg() const { return Repr == OK_Reg; } 108 bool isFP() const { return Repr == OK_FP; } 109 bool isImm() const { return Repr >= OK_Imm; } 110 111 unsigned getImmCode() const { assert(isImm()); return Repr-OK_Imm; } 112 113 void printManglingSuffix(raw_ostream &OS, ImmPredicateSet &ImmPredicates, 114 bool StripImmCodes) const { 115 if (isReg()) 116 OS << 'r'; 117 else if (isFP()) 118 OS << 'f'; 119 else { 120 OS << 'i'; 121 if (!StripImmCodes) 122 if (unsigned Code = getImmCode()) 123 OS << "_" << ImmPredicates.getPredicate(Code-1).getFnName(); 124 } 125 } 126 }; 127 128 129 SmallVector<OpKind, 3> Operands; 130 131 bool operator<(const OperandsSignature &O) const { 132 return Operands < O.Operands; 133 } 134 bool operator==(const OperandsSignature &O) const { 135 return Operands == O.Operands; 136 } 137 138 bool empty() const { return Operands.empty(); } 139 140 bool hasAnyImmediateCodes() const { 141 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 142 if (Operands[i].isImm() && Operands[i].getImmCode() != 0) 143 return true; 144 return false; 145 } 146 147 /// getWithoutImmCodes - Return a copy of this with any immediate codes forced 148 /// to zero. 149 OperandsSignature getWithoutImmCodes() const { 150 OperandsSignature Result; 151 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 152 if (!Operands[i].isImm()) 153 Result.Operands.push_back(Operands[i]); 154 else 155 Result.Operands.push_back(OpKind::getImm(0)); 156 return Result; 157 } 158 159 void emitImmediatePredicate(raw_ostream &OS, ImmPredicateSet &ImmPredicates) { 160 bool EmittedAnything = false; 161 for (unsigned i = 0, e = Operands.size(); i != e; ++i) { 162 if (!Operands[i].isImm()) continue; 163 164 unsigned Code = Operands[i].getImmCode(); 165 if (Code == 0) continue; 166 167 if (EmittedAnything) 168 OS << " &&\n "; 169 170 TreePredicateFn PredFn = ImmPredicates.getPredicate(Code-1); 171 172 // Emit the type check. 173 TreePattern *TP = PredFn.getOrigPatFragRecord(); 174 ValueTypeByHwMode VVT = TP->getTree(0)->getType(0); 175 assert(VVT.isSimple() && 176 "Cannot use variable value types with fast isel"); 177 OS << "VT == " << getEnumName(VVT.getSimple().SimpleTy) << " && "; 178 179 OS << PredFn.getFnName() << "(imm" << i <<')'; 180 EmittedAnything = true; 181 } 182 } 183 184 /// initialize - Examine the given pattern and initialize the contents 185 /// of the Operands array accordingly. Return true if all the operands 186 /// are supported, false otherwise. 187 /// 188 bool initialize(TreePatternNode *InstPatNode, const CodeGenTarget &Target, 189 MVT::SimpleValueType VT, 190 ImmPredicateSet &ImmediatePredicates, 191 const CodeGenRegisterClass *OrigDstRC) { 192 if (InstPatNode->isLeaf()) 193 return false; 194 195 if (InstPatNode->getOperator()->getName() == "imm") { 196 Operands.push_back(OpKind::getImm(0)); 197 return true; 198 } 199 200 if (InstPatNode->getOperator()->getName() == "fpimm") { 201 Operands.push_back(OpKind::getFP()); 202 return true; 203 } 204 205 const CodeGenRegisterClass *DstRC = nullptr; 206 207 for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) { 208 TreePatternNode *Op = InstPatNode->getChild(i); 209 210 // Handle imm operands specially. 211 if (!Op->isLeaf() && Op->getOperator()->getName() == "imm") { 212 unsigned PredNo = 0; 213 if (!Op->getPredicateCalls().empty()) { 214 TreePredicateFn PredFn = Op->getPredicateCalls()[0].Fn; 215 // If there is more than one predicate weighing in on this operand 216 // then we don't handle it. This doesn't typically happen for 217 // immediates anyway. 218 if (Op->getPredicateCalls().size() > 1 || 219 !PredFn.isImmediatePattern() || PredFn.usesOperands()) 220 return false; 221 // Ignore any instruction with 'FastIselShouldIgnore', these are 222 // not needed and just bloat the fast instruction selector. For 223 // example, X86 doesn't need to generate code to match ADD16ri8 since 224 // ADD16ri will do just fine. 225 Record *Rec = PredFn.getOrigPatFragRecord()->getRecord(); 226 if (Rec->getValueAsBit("FastIselShouldIgnore")) 227 return false; 228 229 PredNo = ImmediatePredicates.getIDFor(PredFn)+1; 230 } 231 232 Operands.push_back(OpKind::getImm(PredNo)); 233 continue; 234 } 235 236 237 // For now, filter out any operand with a predicate. 238 // For now, filter out any operand with multiple values. 239 if (!Op->getPredicateCalls().empty() || Op->getNumTypes() != 1) 240 return false; 241 242 if (!Op->isLeaf()) { 243 if (Op->getOperator()->getName() == "fpimm") { 244 Operands.push_back(OpKind::getFP()); 245 continue; 246 } 247 // For now, ignore other non-leaf nodes. 248 return false; 249 } 250 251 assert(Op->hasConcreteType(0) && "Type infererence not done?"); 252 253 // For now, all the operands must have the same type (if they aren't 254 // immediates). Note that this causes us to reject variable sized shifts 255 // on X86. 256 if (Op->getSimpleType(0) != VT) 257 return false; 258 259 DefInit *OpDI = dyn_cast<DefInit>(Op->getLeafValue()); 260 if (!OpDI) 261 return false; 262 Record *OpLeafRec = OpDI->getDef(); 263 264 // For now, the only other thing we accept is register operands. 265 const CodeGenRegisterClass *RC = nullptr; 266 if (OpLeafRec->isSubClassOf("RegisterOperand")) 267 OpLeafRec = OpLeafRec->getValueAsDef("RegClass"); 268 if (OpLeafRec->isSubClassOf("RegisterClass")) 269 RC = &Target.getRegisterClass(OpLeafRec); 270 else if (OpLeafRec->isSubClassOf("Register")) 271 RC = Target.getRegBank().getRegClassForRegister(OpLeafRec); 272 else if (OpLeafRec->isSubClassOf("ValueType")) { 273 RC = OrigDstRC; 274 } else 275 return false; 276 277 // For now, this needs to be a register class of some sort. 278 if (!RC) 279 return false; 280 281 // For now, all the operands must have the same register class or be 282 // a strict subclass of the destination. 283 if (DstRC) { 284 if (DstRC != RC && !DstRC->hasSubClass(RC)) 285 return false; 286 } else 287 DstRC = RC; 288 Operands.push_back(OpKind::getReg()); 289 } 290 return true; 291 } 292 293 void PrintParameters(raw_ostream &OS) const { 294 ListSeparator LS; 295 for (unsigned i = 0, e = Operands.size(); i != e; ++i) { 296 OS << LS; 297 if (Operands[i].isReg()) { 298 OS << "unsigned Op" << i; 299 } else if (Operands[i].isImm()) { 300 OS << "uint64_t imm" << i; 301 } else if (Operands[i].isFP()) { 302 OS << "const ConstantFP *f" << i; 303 } else { 304 llvm_unreachable("Unknown operand kind!"); 305 } 306 } 307 } 308 309 void PrintArguments(raw_ostream &OS, 310 const std::vector<std::string> &PR) const { 311 assert(PR.size() == Operands.size()); 312 ListSeparator LS; 313 for (unsigned i = 0, e = Operands.size(); i != e; ++i) { 314 if (PR[i] != "") 315 // Implicit physical register operand. 316 continue; 317 318 OS << LS; 319 if (Operands[i].isReg()) { 320 OS << "Op" << i; 321 } else if (Operands[i].isImm()) { 322 OS << "imm" << i; 323 } else if (Operands[i].isFP()) { 324 OS << "f" << i; 325 } else { 326 llvm_unreachable("Unknown operand kind!"); 327 } 328 } 329 } 330 331 void PrintArguments(raw_ostream &OS) const { 332 ListSeparator LS; 333 for (unsigned i = 0, e = Operands.size(); i != e; ++i) { 334 OS << LS; 335 if (Operands[i].isReg()) { 336 OS << "Op" << i; 337 } else if (Operands[i].isImm()) { 338 OS << "imm" << i; 339 } else if (Operands[i].isFP()) { 340 OS << "f" << i; 341 } else { 342 llvm_unreachable("Unknown operand kind!"); 343 } 344 } 345 } 346 347 348 void PrintManglingSuffix(raw_ostream &OS, const std::vector<std::string> &PR, 349 ImmPredicateSet &ImmPredicates, 350 bool StripImmCodes = false) const { 351 for (unsigned i = 0, e = Operands.size(); i != e; ++i) { 352 if (PR[i] != "") 353 // Implicit physical register operand. e.g. Instruction::Mul expect to 354 // select to a binary op. On x86, mul may take a single operand with 355 // the other operand being implicit. We must emit something that looks 356 // like a binary instruction except for the very inner fastEmitInst_* 357 // call. 358 continue; 359 Operands[i].printManglingSuffix(OS, ImmPredicates, StripImmCodes); 360 } 361 } 362 363 void PrintManglingSuffix(raw_ostream &OS, ImmPredicateSet &ImmPredicates, 364 bool StripImmCodes = false) const { 365 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 366 Operands[i].printManglingSuffix(OS, ImmPredicates, StripImmCodes); 367 } 368 }; 369 } // End anonymous namespace 370 371 namespace { 372 class FastISelMap { 373 // A multimap is needed instead of a "plain" map because the key is 374 // the instruction's complexity (an int) and they are not unique. 375 typedef std::multimap<int, InstructionMemo> PredMap; 376 typedef std::map<MVT::SimpleValueType, PredMap> RetPredMap; 377 typedef std::map<MVT::SimpleValueType, RetPredMap> TypeRetPredMap; 378 typedef std::map<std::string, TypeRetPredMap> OpcodeTypeRetPredMap; 379 typedef std::map<OperandsSignature, OpcodeTypeRetPredMap> 380 OperandsOpcodeTypeRetPredMap; 381 382 OperandsOpcodeTypeRetPredMap SimplePatterns; 383 384 // This is used to check that there are no duplicate predicates 385 typedef std::multimap<std::string, bool> PredCheckMap; 386 typedef std::map<MVT::SimpleValueType, PredCheckMap> RetPredCheckMap; 387 typedef std::map<MVT::SimpleValueType, RetPredCheckMap> TypeRetPredCheckMap; 388 typedef std::map<std::string, TypeRetPredCheckMap> OpcodeTypeRetPredCheckMap; 389 typedef std::map<OperandsSignature, OpcodeTypeRetPredCheckMap> 390 OperandsOpcodeTypeRetPredCheckMap; 391 392 OperandsOpcodeTypeRetPredCheckMap SimplePatternsCheck; 393 394 std::map<OperandsSignature, std::vector<OperandsSignature> > 395 SignaturesWithConstantForms; 396 397 StringRef InstNS; 398 ImmPredicateSet ImmediatePredicates; 399 public: 400 explicit FastISelMap(StringRef InstNS); 401 402 void collectPatterns(CodeGenDAGPatterns &CGP); 403 void printImmediatePredicates(raw_ostream &OS); 404 void printFunctionDefinitions(raw_ostream &OS); 405 private: 406 void emitInstructionCode(raw_ostream &OS, 407 const OperandsSignature &Operands, 408 const PredMap &PM, 409 const std::string &RetVTName); 410 }; 411 } // End anonymous namespace 412 413 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) { 414 return std::string(CGP.getSDNodeInfo(Op).getEnumName()); 415 } 416 417 static std::string getLegalCName(std::string OpName) { 418 std::string::size_type pos = OpName.find("::"); 419 if (pos != std::string::npos) 420 OpName.replace(pos, 2, "_"); 421 return OpName; 422 } 423 424 FastISelMap::FastISelMap(StringRef instns) : InstNS(instns) {} 425 426 static std::string PhyRegForNode(TreePatternNode *Op, 427 const CodeGenTarget &Target) { 428 std::string PhysReg; 429 430 if (!Op->isLeaf()) 431 return PhysReg; 432 433 Record *OpLeafRec = cast<DefInit>(Op->getLeafValue())->getDef(); 434 if (!OpLeafRec->isSubClassOf("Register")) 435 return PhysReg; 436 437 PhysReg += cast<StringInit>(OpLeafRec->getValue("Namespace")->getValue()) 438 ->getValue(); 439 PhysReg += "::"; 440 PhysReg += Target.getRegBank().getReg(OpLeafRec)->getName(); 441 return PhysReg; 442 } 443 444 void FastISelMap::collectPatterns(CodeGenDAGPatterns &CGP) { 445 const CodeGenTarget &Target = CGP.getTargetInfo(); 446 447 // Scan through all the patterns and record the simple ones. 448 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), 449 E = CGP.ptm_end(); I != E; ++I) { 450 const PatternToMatch &Pattern = *I; 451 452 // For now, just look at Instructions, so that we don't have to worry 453 // about emitting multiple instructions for a pattern. 454 TreePatternNode *Dst = Pattern.getDstPattern(); 455 if (Dst->isLeaf()) continue; 456 Record *Op = Dst->getOperator(); 457 if (!Op->isSubClassOf("Instruction")) 458 continue; 459 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op); 460 if (II.Operands.empty()) 461 continue; 462 463 // Allow instructions to be marked as unavailable for FastISel for 464 // certain cases, i.e. an ISA has two 'and' instruction which differ 465 // by what registers they can use but are otherwise identical for 466 // codegen purposes. 467 if (II.FastISelShouldIgnore) 468 continue; 469 470 // For now, ignore multi-instruction patterns. 471 bool MultiInsts = false; 472 for (unsigned i = 0, e = Dst->getNumChildren(); i != e; ++i) { 473 TreePatternNode *ChildOp = Dst->getChild(i); 474 if (ChildOp->isLeaf()) 475 continue; 476 if (ChildOp->getOperator()->isSubClassOf("Instruction")) { 477 MultiInsts = true; 478 break; 479 } 480 } 481 if (MultiInsts) 482 continue; 483 484 // For now, ignore instructions where the first operand is not an 485 // output register. 486 const CodeGenRegisterClass *DstRC = nullptr; 487 std::string SubRegNo; 488 if (Op->getName() != "EXTRACT_SUBREG") { 489 Record *Op0Rec = II.Operands[0].Rec; 490 if (Op0Rec->isSubClassOf("RegisterOperand")) 491 Op0Rec = Op0Rec->getValueAsDef("RegClass"); 492 if (!Op0Rec->isSubClassOf("RegisterClass")) 493 continue; 494 DstRC = &Target.getRegisterClass(Op0Rec); 495 if (!DstRC) 496 continue; 497 } else { 498 // If this isn't a leaf, then continue since the register classes are 499 // a bit too complicated for now. 500 if (!Dst->getChild(1)->isLeaf()) continue; 501 502 DefInit *SR = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue()); 503 if (SR) 504 SubRegNo = getQualifiedName(SR->getDef()); 505 else 506 SubRegNo = Dst->getChild(1)->getLeafValue()->getAsString(); 507 } 508 509 // Inspect the pattern. 510 TreePatternNode *InstPatNode = Pattern.getSrcPattern(); 511 if (!InstPatNode) continue; 512 if (InstPatNode->isLeaf()) continue; 513 514 // Ignore multiple result nodes for now. 515 if (InstPatNode->getNumTypes() > 1) continue; 516 517 Record *InstPatOp = InstPatNode->getOperator(); 518 std::string OpcodeName = getOpcodeName(InstPatOp, CGP); 519 MVT::SimpleValueType RetVT = MVT::isVoid; 520 if (InstPatNode->getNumTypes()) RetVT = InstPatNode->getSimpleType(0); 521 MVT::SimpleValueType VT = RetVT; 522 if (InstPatNode->getNumChildren()) { 523 assert(InstPatNode->getChild(0)->getNumTypes() == 1); 524 VT = InstPatNode->getChild(0)->getSimpleType(0); 525 } 526 527 // For now, filter out any instructions with predicates. 528 if (!InstPatNode->getPredicateCalls().empty()) 529 continue; 530 531 // Check all the operands. 532 OperandsSignature Operands; 533 if (!Operands.initialize(InstPatNode, Target, VT, ImmediatePredicates, 534 DstRC)) 535 continue; 536 537 std::vector<std::string> PhysRegInputs; 538 if (InstPatNode->getOperator()->getName() == "imm" || 539 InstPatNode->getOperator()->getName() == "fpimm") 540 PhysRegInputs.push_back(""); 541 else { 542 // Compute the PhysRegs used by the given pattern, and check that 543 // the mapping from the src to dst patterns is simple. 544 bool FoundNonSimplePattern = false; 545 unsigned DstIndex = 0; 546 for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) { 547 std::string PhysReg = PhyRegForNode(InstPatNode->getChild(i), Target); 548 if (PhysReg.empty()) { 549 if (DstIndex >= Dst->getNumChildren() || 550 Dst->getChild(DstIndex)->getName() != 551 InstPatNode->getChild(i)->getName()) { 552 FoundNonSimplePattern = true; 553 break; 554 } 555 ++DstIndex; 556 } 557 558 PhysRegInputs.push_back(PhysReg); 559 } 560 561 if (Op->getName() != "EXTRACT_SUBREG" && DstIndex < Dst->getNumChildren()) 562 FoundNonSimplePattern = true; 563 564 if (FoundNonSimplePattern) 565 continue; 566 } 567 568 // Check if the operands match one of the patterns handled by FastISel. 569 std::string ManglingSuffix; 570 raw_string_ostream SuffixOS(ManglingSuffix); 571 Operands.PrintManglingSuffix(SuffixOS, ImmediatePredicates, true); 572 if (!StringSwitch<bool>(ManglingSuffix) 573 .Cases("", "r", "rr", "ri", "i", "f", true) 574 .Default(false)) 575 continue; 576 577 // Get the predicate that guards this pattern. 578 std::string PredicateCheck = Pattern.getPredicateCheck(); 579 580 // Ok, we found a pattern that we can handle. Remember it. 581 InstructionMemo Memo( 582 Pattern.getDstPattern()->getOperator()->getName(), 583 DstRC, 584 SubRegNo, 585 PhysRegInputs, 586 PredicateCheck 587 ); 588 589 int complexity = Pattern.getPatternComplexity(CGP); 590 591 if (SimplePatternsCheck[Operands][OpcodeName][VT] 592 [RetVT].count(PredicateCheck)) { 593 PrintFatalError(Pattern.getSrcRecord()->getLoc(), 594 "Duplicate predicate in FastISel table!"); 595 } 596 SimplePatternsCheck[Operands][OpcodeName][VT][RetVT].insert( 597 std::make_pair(PredicateCheck, true)); 598 599 // Note: Instructions with the same complexity will appear in the order 600 // that they are encountered. 601 SimplePatterns[Operands][OpcodeName][VT][RetVT].emplace(complexity, 602 std::move(Memo)); 603 604 // If any of the operands were immediates with predicates on them, strip 605 // them down to a signature that doesn't have predicates so that we can 606 // associate them with the stripped predicate version. 607 if (Operands.hasAnyImmediateCodes()) { 608 SignaturesWithConstantForms[Operands.getWithoutImmCodes()] 609 .push_back(Operands); 610 } 611 } 612 } 613 614 void FastISelMap::printImmediatePredicates(raw_ostream &OS) { 615 if (ImmediatePredicates.begin() == ImmediatePredicates.end()) 616 return; 617 618 OS << "\n// FastEmit Immediate Predicate functions.\n"; 619 for (auto ImmediatePredicate : ImmediatePredicates) { 620 OS << "static bool " << ImmediatePredicate.getFnName() 621 << "(int64_t Imm) {\n"; 622 OS << ImmediatePredicate.getImmediatePredicateCode() << "\n}\n"; 623 } 624 625 OS << "\n\n"; 626 } 627 628 void FastISelMap::emitInstructionCode(raw_ostream &OS, 629 const OperandsSignature &Operands, 630 const PredMap &PM, 631 const std::string &RetVTName) { 632 // Emit code for each possible instruction. There may be 633 // multiple if there are subtarget concerns. A reverse iterator 634 // is used to produce the ones with highest complexity first. 635 636 bool OneHadNoPredicate = false; 637 for (PredMap::const_reverse_iterator PI = PM.rbegin(), PE = PM.rend(); 638 PI != PE; ++PI) { 639 const InstructionMemo &Memo = PI->second; 640 std::string PredicateCheck = Memo.PredicateCheck; 641 642 if (PredicateCheck.empty()) { 643 assert(!OneHadNoPredicate && 644 "Multiple instructions match and more than one had " 645 "no predicate!"); 646 OneHadNoPredicate = true; 647 } else { 648 if (OneHadNoPredicate) { 649 PrintFatalError("Multiple instructions match and one with no " 650 "predicate came before one with a predicate! " 651 "name:" + Memo.Name + " predicate: " + PredicateCheck); 652 } 653 OS << " if (" + PredicateCheck + ") {\n"; 654 OS << " "; 655 } 656 657 for (unsigned i = 0; i < Memo.PhysRegs.size(); ++i) { 658 if (Memo.PhysRegs[i] != "") 659 OS << " BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, " 660 << "TII.get(TargetOpcode::COPY), " << Memo.PhysRegs[i] 661 << ").addReg(Op" << i << ");\n"; 662 } 663 664 OS << " return fastEmitInst_"; 665 if (Memo.SubRegNo.empty()) { 666 Operands.PrintManglingSuffix(OS, Memo.PhysRegs, ImmediatePredicates, 667 true); 668 OS << "(" << InstNS << "::" << Memo.Name << ", "; 669 OS << "&" << InstNS << "::" << Memo.RC->getName() << "RegClass"; 670 if (!Operands.empty()) 671 OS << ", "; 672 Operands.PrintArguments(OS, Memo.PhysRegs); 673 OS << ");\n"; 674 } else { 675 OS << "extractsubreg(" << RetVTName 676 << ", Op0, " << Memo.SubRegNo << ");\n"; 677 } 678 679 if (!PredicateCheck.empty()) { 680 OS << " }\n"; 681 } 682 } 683 // Return 0 if all of the possibilities had predicates but none 684 // were satisfied. 685 if (!OneHadNoPredicate) 686 OS << " return 0;\n"; 687 OS << "}\n"; 688 OS << "\n"; 689 } 690 691 692 void FastISelMap::printFunctionDefinitions(raw_ostream &OS) { 693 // Now emit code for all the patterns that we collected. 694 for (const auto &SimplePattern : SimplePatterns) { 695 const OperandsSignature &Operands = SimplePattern.first; 696 const OpcodeTypeRetPredMap &OTM = SimplePattern.second; 697 698 for (const auto &I : OTM) { 699 const std::string &Opcode = I.first; 700 const TypeRetPredMap &TM = I.second; 701 702 OS << "// FastEmit functions for " << Opcode << ".\n"; 703 OS << "\n"; 704 705 // Emit one function for each opcode,type pair. 706 for (const auto &TI : TM) { 707 MVT::SimpleValueType VT = TI.first; 708 const RetPredMap &RM = TI.second; 709 if (RM.size() != 1) { 710 for (const auto &RI : RM) { 711 MVT::SimpleValueType RetVT = RI.first; 712 const PredMap &PM = RI.second; 713 714 OS << "unsigned fastEmit_" << getLegalCName(Opcode) << "_" 715 << getLegalCName(std::string(getName(VT))) << "_" 716 << getLegalCName(std::string(getName(RetVT))) << "_"; 717 Operands.PrintManglingSuffix(OS, ImmediatePredicates); 718 OS << "("; 719 Operands.PrintParameters(OS); 720 OS << ") {\n"; 721 722 emitInstructionCode(OS, Operands, PM, std::string(getName(RetVT))); 723 } 724 725 // Emit one function for the type that demultiplexes on return type. 726 OS << "unsigned fastEmit_" << getLegalCName(Opcode) << "_" 727 << getLegalCName(std::string(getName(VT))) << "_"; 728 Operands.PrintManglingSuffix(OS, ImmediatePredicates); 729 OS << "(MVT RetVT"; 730 if (!Operands.empty()) 731 OS << ", "; 732 Operands.PrintParameters(OS); 733 OS << ") {\nswitch (RetVT.SimpleTy) {\n"; 734 for (const auto &RI : RM) { 735 MVT::SimpleValueType RetVT = RI.first; 736 OS << " case " << getName(RetVT) << ": return fastEmit_" 737 << getLegalCName(Opcode) << "_" 738 << getLegalCName(std::string(getName(VT))) << "_" 739 << getLegalCName(std::string(getName(RetVT))) << "_"; 740 Operands.PrintManglingSuffix(OS, ImmediatePredicates); 741 OS << "("; 742 Operands.PrintArguments(OS); 743 OS << ");\n"; 744 } 745 OS << " default: return 0;\n}\n}\n\n"; 746 747 } else { 748 // Non-variadic return type. 749 OS << "unsigned fastEmit_" << getLegalCName(Opcode) << "_" 750 << getLegalCName(std::string(getName(VT))) << "_"; 751 Operands.PrintManglingSuffix(OS, ImmediatePredicates); 752 OS << "(MVT RetVT"; 753 if (!Operands.empty()) 754 OS << ", "; 755 Operands.PrintParameters(OS); 756 OS << ") {\n"; 757 758 OS << " if (RetVT.SimpleTy != " << getName(RM.begin()->first) 759 << ")\n return 0;\n"; 760 761 const PredMap &PM = RM.begin()->second; 762 763 emitInstructionCode(OS, Operands, PM, "RetVT"); 764 } 765 } 766 767 // Emit one function for the opcode that demultiplexes based on the type. 768 OS << "unsigned fastEmit_" 769 << getLegalCName(Opcode) << "_"; 770 Operands.PrintManglingSuffix(OS, ImmediatePredicates); 771 OS << "(MVT VT, MVT RetVT"; 772 if (!Operands.empty()) 773 OS << ", "; 774 Operands.PrintParameters(OS); 775 OS << ") {\n"; 776 OS << " switch (VT.SimpleTy) {\n"; 777 for (const auto &TI : TM) { 778 MVT::SimpleValueType VT = TI.first; 779 std::string TypeName = std::string(getName(VT)); 780 OS << " case " << TypeName << ": return fastEmit_" 781 << getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "_"; 782 Operands.PrintManglingSuffix(OS, ImmediatePredicates); 783 OS << "(RetVT"; 784 if (!Operands.empty()) 785 OS << ", "; 786 Operands.PrintArguments(OS); 787 OS << ");\n"; 788 } 789 OS << " default: return 0;\n"; 790 OS << " }\n"; 791 OS << "}\n"; 792 OS << "\n"; 793 } 794 795 OS << "// Top-level FastEmit function.\n"; 796 OS << "\n"; 797 798 // Emit one function for the operand signature that demultiplexes based 799 // on opcode and type. 800 OS << "unsigned fastEmit_"; 801 Operands.PrintManglingSuffix(OS, ImmediatePredicates); 802 OS << "(MVT VT, MVT RetVT, unsigned Opcode"; 803 if (!Operands.empty()) 804 OS << ", "; 805 Operands.PrintParameters(OS); 806 OS << ") "; 807 if (!Operands.hasAnyImmediateCodes()) 808 OS << "override "; 809 OS << "{\n"; 810 811 // If there are any forms of this signature available that operate on 812 // constrained forms of the immediate (e.g., 32-bit sext immediate in a 813 // 64-bit operand), check them first. 814 815 std::map<OperandsSignature, std::vector<OperandsSignature> >::iterator MI 816 = SignaturesWithConstantForms.find(Operands); 817 if (MI != SignaturesWithConstantForms.end()) { 818 // Unique any duplicates out of the list. 819 llvm::sort(MI->second); 820 MI->second.erase(std::unique(MI->second.begin(), MI->second.end()), 821 MI->second.end()); 822 823 // Check each in order it was seen. It would be nice to have a good 824 // relative ordering between them, but we're not going for optimality 825 // here. 826 for (unsigned i = 0, e = MI->second.size(); i != e; ++i) { 827 OS << " if ("; 828 MI->second[i].emitImmediatePredicate(OS, ImmediatePredicates); 829 OS << ")\n if (unsigned Reg = fastEmit_"; 830 MI->second[i].PrintManglingSuffix(OS, ImmediatePredicates); 831 OS << "(VT, RetVT, Opcode"; 832 if (!MI->second[i].empty()) 833 OS << ", "; 834 MI->second[i].PrintArguments(OS); 835 OS << "))\n return Reg;\n\n"; 836 } 837 838 // Done with this, remove it. 839 SignaturesWithConstantForms.erase(MI); 840 } 841 842 OS << " switch (Opcode) {\n"; 843 for (const auto &I : OTM) { 844 const std::string &Opcode = I.first; 845 846 OS << " case " << Opcode << ": return fastEmit_" 847 << getLegalCName(Opcode) << "_"; 848 Operands.PrintManglingSuffix(OS, ImmediatePredicates); 849 OS << "(VT, RetVT"; 850 if (!Operands.empty()) 851 OS << ", "; 852 Operands.PrintArguments(OS); 853 OS << ");\n"; 854 } 855 OS << " default: return 0;\n"; 856 OS << " }\n"; 857 OS << "}\n"; 858 OS << "\n"; 859 } 860 861 // TODO: SignaturesWithConstantForms should be empty here. 862 } 863 864 namespace llvm { 865 866 void EmitFastISel(RecordKeeper &RK, raw_ostream &OS) { 867 CodeGenDAGPatterns CGP(RK); 868 const CodeGenTarget &Target = CGP.getTargetInfo(); 869 emitSourceFileHeader("\"Fast\" Instruction Selector for the " + 870 Target.getName().str() + " target", OS); 871 872 // Determine the target's namespace name. 873 StringRef InstNS = Target.getInstNamespace(); 874 assert(!InstNS.empty() && "Can't determine target-specific namespace!"); 875 876 FastISelMap F(InstNS); 877 F.collectPatterns(CGP); 878 F.printImmediatePredicates(OS); 879 F.printFunctionDefinitions(OS); 880 } 881 882 } // End llvm namespace 883