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