1 //===-- SelectionDAGBuilder.h - Selection-DAG building --------*- C++ -*---===// 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 implements routines for translating from LLVM IR into SelectionDAG IR. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef LLVM_LIB_CODEGEN_SELECTIONDAG_SELECTIONDAGBUILDER_H 15 #define LLVM_LIB_CODEGEN_SELECTIONDAG_SELECTIONDAGBUILDER_H 16 17 #include "StatepointLowering.h" 18 #include "llvm/ADT/APInt.h" 19 #include "llvm/ADT/DenseMap.h" 20 #include "llvm/Analysis/AliasAnalysis.h" 21 #include "llvm/CodeGen/Analysis.h" 22 #include "llvm/CodeGen/SelectionDAG.h" 23 #include "llvm/CodeGen/SelectionDAGNodes.h" 24 #include "llvm/IR/CallSite.h" 25 #include "llvm/IR/Constants.h" 26 #include "llvm/IR/Statepoint.h" 27 #include "llvm/Support/ErrorHandling.h" 28 #include "llvm/Target/TargetLowering.h" 29 #include <utility> 30 #include <vector> 31 32 namespace llvm { 33 34 class AddrSpaceCastInst; 35 class AllocaInst; 36 class BasicBlock; 37 class BitCastInst; 38 class BranchInst; 39 class CallInst; 40 class DbgValueInst; 41 class ExtractElementInst; 42 class ExtractValueInst; 43 class FCmpInst; 44 class FPExtInst; 45 class FPToSIInst; 46 class FPToUIInst; 47 class FPTruncInst; 48 class Function; 49 class FunctionLoweringInfo; 50 class GetElementPtrInst; 51 class GCFunctionInfo; 52 class ICmpInst; 53 class IntToPtrInst; 54 class IndirectBrInst; 55 class InvokeInst; 56 class InsertElementInst; 57 class InsertValueInst; 58 class Instruction; 59 class LoadInst; 60 class MachineBasicBlock; 61 class MachineInstr; 62 class MachineRegisterInfo; 63 class MDNode; 64 class MVT; 65 class PHINode; 66 class PtrToIntInst; 67 class ReturnInst; 68 class SDDbgValue; 69 class SExtInst; 70 class SelectInst; 71 class ShuffleVectorInst; 72 class SIToFPInst; 73 class StoreInst; 74 class SwitchInst; 75 class DataLayout; 76 class TargetLibraryInfo; 77 class TargetLowering; 78 class TruncInst; 79 class UIToFPInst; 80 class UnreachableInst; 81 class VAArgInst; 82 class ZExtInst; 83 84 //===----------------------------------------------------------------------===// 85 /// SelectionDAGBuilder - This is the common target-independent lowering 86 /// implementation that is parameterized by a TargetLowering object. 87 /// 88 class SelectionDAGBuilder { 89 /// CurInst - The current instruction being visited 90 const Instruction *CurInst; 91 92 DenseMap<const Value*, SDValue> NodeMap; 93 94 /// UnusedArgNodeMap - Maps argument value for unused arguments. This is used 95 /// to preserve debug information for incoming arguments. 96 DenseMap<const Value*, SDValue> UnusedArgNodeMap; 97 98 /// DanglingDebugInfo - Helper type for DanglingDebugInfoMap. 99 class DanglingDebugInfo { 100 const DbgValueInst* DI; 101 DebugLoc dl; 102 unsigned SDNodeOrder; 103 public: 104 DanglingDebugInfo() : DI(nullptr), dl(DebugLoc()), SDNodeOrder(0) { } 105 DanglingDebugInfo(const DbgValueInst *di, DebugLoc DL, unsigned SDNO) 106 : DI(di), dl(std::move(DL)), SDNodeOrder(SDNO) {} 107 const DbgValueInst* getDI() { return DI; } 108 DebugLoc getdl() { return dl; } 109 unsigned getSDNodeOrder() { return SDNodeOrder; } 110 }; 111 112 /// DanglingDebugInfoMap - Keeps track of dbg_values for which we have not 113 /// yet seen the referent. We defer handling these until we do see it. 114 DenseMap<const Value*, DanglingDebugInfo> DanglingDebugInfoMap; 115 116 public: 117 /// PendingLoads - Loads are not emitted to the program immediately. We bunch 118 /// them up and then emit token factor nodes when possible. This allows us to 119 /// get simple disambiguation between loads without worrying about alias 120 /// analysis. 121 SmallVector<SDValue, 8> PendingLoads; 122 123 /// State used while lowering a statepoint sequence (gc_statepoint, 124 /// gc_relocate, and gc_result). See StatepointLowering.hpp/cpp for details. 125 StatepointLoweringState StatepointLowering; 126 private: 127 128 /// PendingExports - CopyToReg nodes that copy values to virtual registers 129 /// for export to other blocks need to be emitted before any terminator 130 /// instruction, but they have no other ordering requirements. We bunch them 131 /// up and the emit a single tokenfactor for them just before terminator 132 /// instructions. 133 SmallVector<SDValue, 8> PendingExports; 134 135 /// SDNodeOrder - A unique monotonically increasing number used to order the 136 /// SDNodes we create. 137 unsigned SDNodeOrder; 138 139 enum CaseClusterKind { 140 /// A cluster of adjacent case labels with the same destination, or just one 141 /// case. 142 CC_Range, 143 /// A cluster of cases suitable for jump table lowering. 144 CC_JumpTable, 145 /// A cluster of cases suitable for bit test lowering. 146 CC_BitTests 147 }; 148 149 /// A cluster of case labels. 150 struct CaseCluster { 151 CaseClusterKind Kind; 152 const ConstantInt *Low, *High; 153 union { 154 MachineBasicBlock *MBB; 155 unsigned JTCasesIndex; 156 unsigned BTCasesIndex; 157 }; 158 BranchProbability Prob; 159 160 static CaseCluster range(const ConstantInt *Low, const ConstantInt *High, 161 MachineBasicBlock *MBB, BranchProbability Prob) { 162 CaseCluster C; 163 C.Kind = CC_Range; 164 C.Low = Low; 165 C.High = High; 166 C.MBB = MBB; 167 C.Prob = Prob; 168 return C; 169 } 170 171 static CaseCluster jumpTable(const ConstantInt *Low, 172 const ConstantInt *High, unsigned JTCasesIndex, 173 BranchProbability Prob) { 174 CaseCluster C; 175 C.Kind = CC_JumpTable; 176 C.Low = Low; 177 C.High = High; 178 C.JTCasesIndex = JTCasesIndex; 179 C.Prob = Prob; 180 return C; 181 } 182 183 static CaseCluster bitTests(const ConstantInt *Low, const ConstantInt *High, 184 unsigned BTCasesIndex, BranchProbability Prob) { 185 CaseCluster C; 186 C.Kind = CC_BitTests; 187 C.Low = Low; 188 C.High = High; 189 C.BTCasesIndex = BTCasesIndex; 190 C.Prob = Prob; 191 return C; 192 } 193 }; 194 195 typedef std::vector<CaseCluster> CaseClusterVector; 196 typedef CaseClusterVector::iterator CaseClusterIt; 197 198 struct CaseBits { 199 uint64_t Mask; 200 MachineBasicBlock* BB; 201 unsigned Bits; 202 BranchProbability ExtraProb; 203 204 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits, 205 BranchProbability Prob): 206 Mask(mask), BB(bb), Bits(bits), ExtraProb(Prob) { } 207 208 CaseBits() : Mask(0), BB(nullptr), Bits(0) {} 209 }; 210 211 typedef std::vector<CaseBits> CaseBitsVector; 212 213 /// Sort Clusters and merge adjacent cases. 214 void sortAndRangeify(CaseClusterVector &Clusters); 215 216 /// CaseBlock - This structure is used to communicate between 217 /// SelectionDAGBuilder and SDISel for the code generation of additional basic 218 /// blocks needed by multi-case switch statements. 219 struct CaseBlock { 220 CaseBlock(ISD::CondCode cc, const Value *cmplhs, const Value *cmprhs, 221 const Value *cmpmiddle, MachineBasicBlock *truebb, 222 MachineBasicBlock *falsebb, MachineBasicBlock *me, 223 BranchProbability trueprob = BranchProbability::getUnknown(), 224 BranchProbability falseprob = BranchProbability::getUnknown()) 225 : CC(cc), CmpLHS(cmplhs), CmpMHS(cmpmiddle), CmpRHS(cmprhs), 226 TrueBB(truebb), FalseBB(falsebb), ThisBB(me), TrueProb(trueprob), 227 FalseProb(falseprob) {} 228 229 // CC - the condition code to use for the case block's setcc node 230 ISD::CondCode CC; 231 232 // CmpLHS/CmpRHS/CmpMHS - The LHS/MHS/RHS of the comparison to emit. 233 // Emit by default LHS op RHS. MHS is used for range comparisons: 234 // If MHS is not null: (LHS <= MHS) and (MHS <= RHS). 235 const Value *CmpLHS, *CmpMHS, *CmpRHS; 236 237 // TrueBB/FalseBB - the block to branch to if the setcc is true/false. 238 MachineBasicBlock *TrueBB, *FalseBB; 239 240 // ThisBB - the block into which to emit the code for the setcc and branches 241 MachineBasicBlock *ThisBB; 242 243 // TrueProb/FalseProb - branch weights. 244 BranchProbability TrueProb, FalseProb; 245 }; 246 247 struct JumpTable { 248 JumpTable(unsigned R, unsigned J, MachineBasicBlock *M, 249 MachineBasicBlock *D): Reg(R), JTI(J), MBB(M), Default(D) {} 250 251 /// Reg - the virtual register containing the index of the jump table entry 252 //. to jump to. 253 unsigned Reg; 254 /// JTI - the JumpTableIndex for this jump table in the function. 255 unsigned JTI; 256 /// MBB - the MBB into which to emit the code for the indirect jump. 257 MachineBasicBlock *MBB; 258 /// Default - the MBB of the default bb, which is a successor of the range 259 /// check MBB. This is when updating PHI nodes in successors. 260 MachineBasicBlock *Default; 261 }; 262 struct JumpTableHeader { 263 JumpTableHeader(APInt F, APInt L, const Value *SV, MachineBasicBlock *H, 264 bool E = false) 265 : First(std::move(F)), Last(std::move(L)), SValue(SV), HeaderBB(H), 266 Emitted(E) {} 267 APInt First; 268 APInt Last; 269 const Value *SValue; 270 MachineBasicBlock *HeaderBB; 271 bool Emitted; 272 }; 273 typedef std::pair<JumpTableHeader, JumpTable> JumpTableBlock; 274 275 struct BitTestCase { 276 BitTestCase(uint64_t M, MachineBasicBlock* T, MachineBasicBlock* Tr, 277 BranchProbability Prob): 278 Mask(M), ThisBB(T), TargetBB(Tr), ExtraProb(Prob) { } 279 uint64_t Mask; 280 MachineBasicBlock *ThisBB; 281 MachineBasicBlock *TargetBB; 282 BranchProbability ExtraProb; 283 }; 284 285 typedef SmallVector<BitTestCase, 3> BitTestInfo; 286 287 struct BitTestBlock { 288 BitTestBlock(APInt F, APInt R, const Value *SV, unsigned Rg, MVT RgVT, 289 bool E, bool CR, MachineBasicBlock *P, MachineBasicBlock *D, 290 BitTestInfo C, BranchProbability Pr) 291 : First(std::move(F)), Range(std::move(R)), SValue(SV), Reg(Rg), 292 RegVT(RgVT), Emitted(E), ContiguousRange(CR), Parent(P), Default(D), 293 Cases(std::move(C)), Prob(Pr) {} 294 APInt First; 295 APInt Range; 296 const Value *SValue; 297 unsigned Reg; 298 MVT RegVT; 299 bool Emitted; 300 bool ContiguousRange; 301 MachineBasicBlock *Parent; 302 MachineBasicBlock *Default; 303 BitTestInfo Cases; 304 BranchProbability Prob; 305 BranchProbability DefaultProb; 306 }; 307 308 /// Check whether a range of clusters is dense enough for a jump table. 309 bool isDense(const CaseClusterVector &Clusters, unsigned *TotalCases, 310 unsigned First, unsigned Last, unsigned MinDensity); 311 312 /// Build a jump table cluster from Clusters[First..Last]. Returns false if it 313 /// decides it's not a good idea. 314 bool buildJumpTable(CaseClusterVector &Clusters, unsigned First, 315 unsigned Last, const SwitchInst *SI, 316 MachineBasicBlock *DefaultMBB, CaseCluster &JTCluster); 317 318 /// Find clusters of cases suitable for jump table lowering. 319 void findJumpTables(CaseClusterVector &Clusters, const SwitchInst *SI, 320 MachineBasicBlock *DefaultMBB); 321 322 /// Check whether the range [Low,High] fits in a machine word. 323 bool rangeFitsInWord(const APInt &Low, const APInt &High); 324 325 /// Check whether these clusters are suitable for lowering with bit tests based 326 /// on the number of destinations, comparison metric, and range. 327 bool isSuitableForBitTests(unsigned NumDests, unsigned NumCmps, 328 const APInt &Low, const APInt &High); 329 330 /// Build a bit test cluster from Clusters[First..Last]. Returns false if it 331 /// decides it's not a good idea. 332 bool buildBitTests(CaseClusterVector &Clusters, unsigned First, unsigned Last, 333 const SwitchInst *SI, CaseCluster &BTCluster); 334 335 /// Find clusters of cases suitable for bit test lowering. 336 void findBitTestClusters(CaseClusterVector &Clusters, const SwitchInst *SI); 337 338 struct SwitchWorkListItem { 339 MachineBasicBlock *MBB; 340 CaseClusterIt FirstCluster; 341 CaseClusterIt LastCluster; 342 const ConstantInt *GE; 343 const ConstantInt *LT; 344 BranchProbability DefaultProb; 345 }; 346 typedef SmallVector<SwitchWorkListItem, 4> SwitchWorkList; 347 348 /// Determine the rank by weight of CC in [First,Last]. If CC has more weight 349 /// than each cluster in the range, its rank is 0. 350 static unsigned caseClusterRank(const CaseCluster &CC, CaseClusterIt First, 351 CaseClusterIt Last); 352 353 /// Emit comparison and split W into two subtrees. 354 void splitWorkItem(SwitchWorkList &WorkList, const SwitchWorkListItem &W, 355 Value *Cond, MachineBasicBlock *SwitchMBB); 356 357 /// Lower W. 358 void lowerWorkItem(SwitchWorkListItem W, Value *Cond, 359 MachineBasicBlock *SwitchMBB, 360 MachineBasicBlock *DefaultMBB); 361 362 363 /// A class which encapsulates all of the information needed to generate a 364 /// stack protector check and signals to isel via its state being initialized 365 /// that a stack protector needs to be generated. 366 /// 367 /// *NOTE* The following is a high level documentation of SelectionDAG Stack 368 /// Protector Generation. The reason that it is placed here is for a lack of 369 /// other good places to stick it. 370 /// 371 /// High Level Overview of SelectionDAG Stack Protector Generation: 372 /// 373 /// Previously, generation of stack protectors was done exclusively in the 374 /// pre-SelectionDAG Codegen LLVM IR Pass "Stack Protector". This necessitated 375 /// splitting basic blocks at the IR level to create the success/failure basic 376 /// blocks in the tail of the basic block in question. As a result of this, 377 /// calls that would have qualified for the sibling call optimization were no 378 /// longer eligible for optimization since said calls were no longer right in 379 /// the "tail position" (i.e. the immediate predecessor of a ReturnInst 380 /// instruction). 381 /// 382 /// Then it was noticed that since the sibling call optimization causes the 383 /// callee to reuse the caller's stack, if we could delay the generation of 384 /// the stack protector check until later in CodeGen after the sibling call 385 /// decision was made, we get both the tail call optimization and the stack 386 /// protector check! 387 /// 388 /// A few goals in solving this problem were: 389 /// 390 /// 1. Preserve the architecture independence of stack protector generation. 391 /// 392 /// 2. Preserve the normal IR level stack protector check for platforms like 393 /// OpenBSD for which we support platform-specific stack protector 394 /// generation. 395 /// 396 /// The main problem that guided the present solution is that one can not 397 /// solve this problem in an architecture independent manner at the IR level 398 /// only. This is because: 399 /// 400 /// 1. The decision on whether or not to perform a sibling call on certain 401 /// platforms (for instance i386) requires lower level information 402 /// related to available registers that can not be known at the IR level. 403 /// 404 /// 2. Even if the previous point were not true, the decision on whether to 405 /// perform a tail call is done in LowerCallTo in SelectionDAG which 406 /// occurs after the Stack Protector Pass. As a result, one would need to 407 /// put the relevant callinst into the stack protector check success 408 /// basic block (where the return inst is placed) and then move it back 409 /// later at SelectionDAG/MI time before the stack protector check if the 410 /// tail call optimization failed. The MI level option was nixed 411 /// immediately since it would require platform-specific pattern 412 /// matching. The SelectionDAG level option was nixed because 413 /// SelectionDAG only processes one IR level basic block at a time 414 /// implying one could not create a DAG Combine to move the callinst. 415 /// 416 /// To get around this problem a few things were realized: 417 /// 418 /// 1. While one can not handle multiple IR level basic blocks at the 419 /// SelectionDAG Level, one can generate multiple machine basic blocks 420 /// for one IR level basic block. This is how we handle bit tests and 421 /// switches. 422 /// 423 /// 2. At the MI level, tail calls are represented via a special return 424 /// MIInst called "tcreturn". Thus if we know the basic block in which we 425 /// wish to insert the stack protector check, we get the correct behavior 426 /// by always inserting the stack protector check right before the return 427 /// statement. This is a "magical transformation" since no matter where 428 /// the stack protector check intrinsic is, we always insert the stack 429 /// protector check code at the end of the BB. 430 /// 431 /// Given the aforementioned constraints, the following solution was devised: 432 /// 433 /// 1. On platforms that do not support SelectionDAG stack protector check 434 /// generation, allow for the normal IR level stack protector check 435 /// generation to continue. 436 /// 437 /// 2. On platforms that do support SelectionDAG stack protector check 438 /// generation: 439 /// 440 /// a. Use the IR level stack protector pass to decide if a stack 441 /// protector is required/which BB we insert the stack protector check 442 /// in by reusing the logic already therein. If we wish to generate a 443 /// stack protector check in a basic block, we place a special IR 444 /// intrinsic called llvm.stackprotectorcheck right before the BB's 445 /// returninst or if there is a callinst that could potentially be 446 /// sibling call optimized, before the call inst. 447 /// 448 /// b. Then when a BB with said intrinsic is processed, we codegen the BB 449 /// normally via SelectBasicBlock. In said process, when we visit the 450 /// stack protector check, we do not actually emit anything into the 451 /// BB. Instead, we just initialize the stack protector descriptor 452 /// class (which involves stashing information/creating the success 453 /// mbbb and the failure mbb if we have not created one for this 454 /// function yet) and export the guard variable that we are going to 455 /// compare. 456 /// 457 /// c. After we finish selecting the basic block, in FinishBasicBlock if 458 /// the StackProtectorDescriptor attached to the SelectionDAGBuilder is 459 /// initialized, we produce the validation code with one of these 460 /// techniques: 461 /// 1) with a call to a guard check function 462 /// 2) with inlined instrumentation 463 /// 464 /// 1) We insert a call to the check function before the terminator. 465 /// 466 /// 2) We first find a splice point in the parent basic block 467 /// before the terminator and then splice the terminator of said basic 468 /// block into the success basic block. Then we code-gen a new tail for 469 /// the parent basic block consisting of the two loads, the comparison, 470 /// and finally two branches to the success/failure basic blocks. We 471 /// conclude by code-gening the failure basic block if we have not 472 /// code-gened it already (all stack protector checks we generate in 473 /// the same function, use the same failure basic block). 474 class StackProtectorDescriptor { 475 public: 476 StackProtectorDescriptor() 477 : ParentMBB(nullptr), SuccessMBB(nullptr), FailureMBB(nullptr) {} 478 479 /// Returns true if all fields of the stack protector descriptor are 480 /// initialized implying that we should/are ready to emit a stack protector. 481 bool shouldEmitStackProtector() const { 482 return ParentMBB && SuccessMBB && FailureMBB; 483 } 484 485 bool shouldEmitFunctionBasedCheckStackProtector() const { 486 return ParentMBB && !SuccessMBB && !FailureMBB; 487 } 488 489 /// Initialize the stack protector descriptor structure for a new basic 490 /// block. 491 void initialize(const BasicBlock *BB, MachineBasicBlock *MBB, 492 bool FunctionBasedInstrumentation) { 493 // Make sure we are not initialized yet. 494 assert(!shouldEmitStackProtector() && "Stack Protector Descriptor is " 495 "already initialized!"); 496 ParentMBB = MBB; 497 if (!FunctionBasedInstrumentation) { 498 SuccessMBB = AddSuccessorMBB(BB, MBB, /* IsLikely */ true); 499 FailureMBB = AddSuccessorMBB(BB, MBB, /* IsLikely */ false, FailureMBB); 500 } 501 } 502 503 /// Reset state that changes when we handle different basic blocks. 504 /// 505 /// This currently includes: 506 /// 507 /// 1. The specific basic block we are generating a 508 /// stack protector for (ParentMBB). 509 /// 510 /// 2. The successor machine basic block that will contain the tail of 511 /// parent mbb after we create the stack protector check (SuccessMBB). This 512 /// BB is visited only on stack protector check success. 513 void resetPerBBState() { 514 ParentMBB = nullptr; 515 SuccessMBB = nullptr; 516 } 517 518 /// Reset state that only changes when we switch functions. 519 /// 520 /// This currently includes: 521 /// 522 /// 1. FailureMBB since we reuse the failure code path for all stack 523 /// protector checks created in an individual function. 524 /// 525 /// 2.The guard variable since the guard variable we are checking against is 526 /// always the same. 527 void resetPerFunctionState() { 528 FailureMBB = nullptr; 529 } 530 531 MachineBasicBlock *getParentMBB() { return ParentMBB; } 532 MachineBasicBlock *getSuccessMBB() { return SuccessMBB; } 533 MachineBasicBlock *getFailureMBB() { return FailureMBB; } 534 535 private: 536 /// The basic block for which we are generating the stack protector. 537 /// 538 /// As a result of stack protector generation, we will splice the 539 /// terminators of this basic block into the successor mbb SuccessMBB and 540 /// replace it with a compare/branch to the successor mbbs 541 /// SuccessMBB/FailureMBB depending on whether or not the stack protector 542 /// was violated. 543 MachineBasicBlock *ParentMBB; 544 545 /// A basic block visited on stack protector check success that contains the 546 /// terminators of ParentMBB. 547 MachineBasicBlock *SuccessMBB; 548 549 /// This basic block visited on stack protector check failure that will 550 /// contain a call to __stack_chk_fail(). 551 MachineBasicBlock *FailureMBB; 552 553 /// Add a successor machine basic block to ParentMBB. If the successor mbb 554 /// has not been created yet (i.e. if SuccMBB = 0), then the machine basic 555 /// block will be created. Assign a large weight if IsLikely is true. 556 MachineBasicBlock *AddSuccessorMBB(const BasicBlock *BB, 557 MachineBasicBlock *ParentMBB, 558 bool IsLikely, 559 MachineBasicBlock *SuccMBB = nullptr); 560 }; 561 562 private: 563 const TargetMachine &TM; 564 public: 565 /// Lowest valid SDNodeOrder. The special case 0 is reserved for scheduling 566 /// nodes without a corresponding SDNode. 567 static const unsigned LowestSDNodeOrder = 1; 568 569 SelectionDAG &DAG; 570 const DataLayout *DL; 571 AliasAnalysis *AA; 572 const TargetLibraryInfo *LibInfo; 573 574 /// SwitchCases - Vector of CaseBlock structures used to communicate 575 /// SwitchInst code generation information. 576 std::vector<CaseBlock> SwitchCases; 577 /// JTCases - Vector of JumpTable structures used to communicate 578 /// SwitchInst code generation information. 579 std::vector<JumpTableBlock> JTCases; 580 /// BitTestCases - Vector of BitTestBlock structures used to communicate 581 /// SwitchInst code generation information. 582 std::vector<BitTestBlock> BitTestCases; 583 /// A StackProtectorDescriptor structure used to communicate stack protector 584 /// information in between SelectBasicBlock and FinishBasicBlock. 585 StackProtectorDescriptor SPDescriptor; 586 587 // Emit PHI-node-operand constants only once even if used by multiple 588 // PHI nodes. 589 DenseMap<const Constant *, unsigned> ConstantsOut; 590 591 /// FuncInfo - Information about the function as a whole. 592 /// 593 FunctionLoweringInfo &FuncInfo; 594 595 /// GFI - Garbage collection metadata for the function. 596 GCFunctionInfo *GFI; 597 598 /// LPadToCallSiteMap - Map a landing pad to the call site indexes. 599 DenseMap<MachineBasicBlock*, SmallVector<unsigned, 4> > LPadToCallSiteMap; 600 601 /// HasTailCall - This is set to true if a call in the current 602 /// block has been translated as a tail call. In this case, 603 /// no subsequent DAG nodes should be created. 604 /// 605 bool HasTailCall; 606 607 LLVMContext *Context; 608 609 SelectionDAGBuilder(SelectionDAG &dag, FunctionLoweringInfo &funcinfo, 610 CodeGenOpt::Level ol) 611 : CurInst(nullptr), SDNodeOrder(LowestSDNodeOrder), TM(dag.getTarget()), 612 DAG(dag), FuncInfo(funcinfo), 613 HasTailCall(false) { 614 } 615 616 void init(GCFunctionInfo *gfi, AliasAnalysis &aa, 617 const TargetLibraryInfo *li); 618 619 /// clear - Clear out the current SelectionDAG and the associated 620 /// state and prepare this SelectionDAGBuilder object to be used 621 /// for a new block. This doesn't clear out information about 622 /// additional blocks that are needed to complete switch lowering 623 /// or PHI node updating; that information is cleared out as it is 624 /// consumed. 625 void clear(); 626 627 /// clearDanglingDebugInfo - Clear the dangling debug information 628 /// map. This function is separated from the clear so that debug 629 /// information that is dangling in a basic block can be properly 630 /// resolved in a different basic block. This allows the 631 /// SelectionDAG to resolve dangling debug information attached 632 /// to PHI nodes. 633 void clearDanglingDebugInfo(); 634 635 /// getRoot - Return the current virtual root of the Selection DAG, 636 /// flushing any PendingLoad items. This must be done before emitting 637 /// a store or any other node that may need to be ordered after any 638 /// prior load instructions. 639 /// 640 SDValue getRoot(); 641 642 /// getControlRoot - Similar to getRoot, but instead of flushing all the 643 /// PendingLoad items, flush all the PendingExports items. It is necessary 644 /// to do this before emitting a terminator instruction. 645 /// 646 SDValue getControlRoot(); 647 648 SDLoc getCurSDLoc() const { 649 return SDLoc(CurInst, SDNodeOrder); 650 } 651 652 DebugLoc getCurDebugLoc() const { 653 return CurInst ? CurInst->getDebugLoc() : DebugLoc(); 654 } 655 656 unsigned getSDNodeOrder() const { return SDNodeOrder; } 657 658 void CopyValueToVirtualRegister(const Value *V, unsigned Reg); 659 660 void visit(const Instruction &I); 661 662 void visit(unsigned Opcode, const User &I); 663 664 /// getCopyFromRegs - If there was virtual register allocated for the value V 665 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 666 SDValue getCopyFromRegs(const Value *V, Type *Ty); 667 668 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 669 // generate the debug data structures now that we've seen its definition. 670 void resolveDanglingDebugInfo(const Value *V, SDValue Val); 671 SDValue getValue(const Value *V); 672 bool findValue(const Value *V) const; 673 674 SDValue getNonRegisterValue(const Value *V); 675 SDValue getValueImpl(const Value *V); 676 677 void setValue(const Value *V, SDValue NewN) { 678 SDValue &N = NodeMap[V]; 679 assert(!N.getNode() && "Already set a value for this node!"); 680 N = NewN; 681 } 682 683 void setUnusedArgValue(const Value *V, SDValue NewN) { 684 SDValue &N = UnusedArgNodeMap[V]; 685 assert(!N.getNode() && "Already set a value for this node!"); 686 N = NewN; 687 } 688 689 void FindMergedConditions(const Value *Cond, MachineBasicBlock *TBB, 690 MachineBasicBlock *FBB, MachineBasicBlock *CurBB, 691 MachineBasicBlock *SwitchBB, 692 Instruction::BinaryOps Opc, BranchProbability TW, 693 BranchProbability FW); 694 void EmitBranchForMergedCondition(const Value *Cond, MachineBasicBlock *TBB, 695 MachineBasicBlock *FBB, 696 MachineBasicBlock *CurBB, 697 MachineBasicBlock *SwitchBB, 698 BranchProbability TW, BranchProbability FW); 699 bool ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases); 700 bool isExportableFromCurrentBlock(const Value *V, const BasicBlock *FromBB); 701 void CopyToExportRegsIfNeeded(const Value *V); 702 void ExportFromCurrentBlock(const Value *V); 703 void LowerCallTo(ImmutableCallSite CS, SDValue Callee, bool IsTailCall, 704 const BasicBlock *EHPadBB = nullptr); 705 706 // Lower range metadata from 0 to N to assert zext to an integer of nearest 707 // floor power of two. 708 SDValue lowerRangeToAssertZExt(SelectionDAG &DAG, const Instruction &I, 709 SDValue Op); 710 711 void populateCallLoweringInfo(TargetLowering::CallLoweringInfo &CLI, 712 ImmutableCallSite CS, unsigned ArgIdx, 713 unsigned NumArgs, SDValue Callee, 714 Type *ReturnTy, bool IsPatchPoint); 715 716 std::pair<SDValue, SDValue> 717 lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 718 const BasicBlock *EHPadBB = nullptr); 719 720 /// UpdateSplitBlock - When an MBB was split during scheduling, update the 721 /// references that need to refer to the last resulting block. 722 void UpdateSplitBlock(MachineBasicBlock *First, MachineBasicBlock *Last); 723 724 /// Describes a gc.statepoint or a gc.statepoint like thing for the purposes 725 /// of lowering into a STATEPOINT node. 726 struct StatepointLoweringInfo { 727 /// Bases[i] is the base pointer for Ptrs[i]. Together they denote the set 728 /// of gc pointers this STATEPOINT has to relocate. 729 SmallVector<const Value *, 16> Bases; 730 SmallVector<const Value *, 16> Ptrs; 731 732 /// The set of gc.relocate calls associated with this gc.statepoint. 733 SmallVector<const GCRelocateInst *, 16> GCRelocates; 734 735 /// The full list of gc arguments to the gc.statepoint being lowered. 736 ArrayRef<const Use> GCArgs; 737 738 /// The gc.statepoint instruction. 739 const Instruction *StatepointInstr = nullptr; 740 741 /// The list of gc transition arguments present in the gc.statepoint being 742 /// lowered. 743 ArrayRef<const Use> GCTransitionArgs; 744 745 /// The ID that the resulting STATEPOINT instruction has to report. 746 unsigned ID = -1; 747 748 /// Information regarding the underlying call instruction. 749 TargetLowering::CallLoweringInfo CLI; 750 751 /// The deoptimization state associated with this gc.statepoint call, if 752 /// any. 753 ArrayRef<const Use> DeoptState; 754 755 /// Flags associated with the meta arguments being lowered. 756 uint64_t StatepointFlags = -1; 757 758 /// The number of patchable bytes the call needs to get lowered into. 759 unsigned NumPatchBytes = -1; 760 761 /// The exception handling unwind destination, in case this represents an 762 /// invoke of gc.statepoint. 763 const BasicBlock *EHPadBB = nullptr; 764 765 explicit StatepointLoweringInfo(SelectionDAG &DAG) : CLI(DAG) {} 766 }; 767 768 /// Lower \p SLI into a STATEPOINT instruction. 769 SDValue LowerAsSTATEPOINT(StatepointLoweringInfo &SLI); 770 771 // This function is responsible for the whole statepoint lowering process. 772 // It uniformly handles invoke and call statepoints. 773 void LowerStatepoint(ImmutableStatepoint Statepoint, 774 const BasicBlock *EHPadBB = nullptr); 775 776 void LowerCallSiteWithDeoptBundle(ImmutableCallSite CS, SDValue Callee, 777 const BasicBlock *EHPadBB); 778 779 void LowerDeoptimizeCall(const CallInst *CI); 780 void LowerDeoptimizingReturn(); 781 782 void LowerCallSiteWithDeoptBundleImpl(ImmutableCallSite CS, SDValue Callee, 783 const BasicBlock *EHPadBB, 784 bool VarArgDisallowed, 785 bool ForceVoidReturnTy); 786 787 private: 788 // Terminator instructions. 789 void visitRet(const ReturnInst &I); 790 void visitBr(const BranchInst &I); 791 void visitSwitch(const SwitchInst &I); 792 void visitIndirectBr(const IndirectBrInst &I); 793 void visitUnreachable(const UnreachableInst &I); 794 void visitCleanupRet(const CleanupReturnInst &I); 795 void visitCatchSwitch(const CatchSwitchInst &I); 796 void visitCatchRet(const CatchReturnInst &I); 797 void visitCatchPad(const CatchPadInst &I); 798 void visitCleanupPad(const CleanupPadInst &CPI); 799 800 BranchProbability getEdgeProbability(const MachineBasicBlock *Src, 801 const MachineBasicBlock *Dst) const; 802 void addSuccessorWithProb( 803 MachineBasicBlock *Src, MachineBasicBlock *Dst, 804 BranchProbability Prob = BranchProbability::getUnknown()); 805 806 public: 807 void visitSwitchCase(CaseBlock &CB, 808 MachineBasicBlock *SwitchBB); 809 void visitSPDescriptorParent(StackProtectorDescriptor &SPD, 810 MachineBasicBlock *ParentBB); 811 void visitSPDescriptorFailure(StackProtectorDescriptor &SPD); 812 void visitBitTestHeader(BitTestBlock &B, MachineBasicBlock *SwitchBB); 813 void visitBitTestCase(BitTestBlock &BB, 814 MachineBasicBlock* NextMBB, 815 BranchProbability BranchProbToNext, 816 unsigned Reg, 817 BitTestCase &B, 818 MachineBasicBlock *SwitchBB); 819 void visitJumpTable(JumpTable &JT); 820 void visitJumpTableHeader(JumpTable &JT, JumpTableHeader &JTH, 821 MachineBasicBlock *SwitchBB); 822 823 private: 824 // These all get lowered before this pass. 825 void visitInvoke(const InvokeInst &I); 826 void visitResume(const ResumeInst &I); 827 828 void visitBinary(const User &I, unsigned OpCode); 829 void visitShift(const User &I, unsigned Opcode); 830 void visitAdd(const User &I) { visitBinary(I, ISD::ADD); } 831 void visitFAdd(const User &I) { visitBinary(I, ISD::FADD); } 832 void visitSub(const User &I) { visitBinary(I, ISD::SUB); } 833 void visitFSub(const User &I); 834 void visitMul(const User &I) { visitBinary(I, ISD::MUL); } 835 void visitFMul(const User &I) { visitBinary(I, ISD::FMUL); } 836 void visitURem(const User &I) { visitBinary(I, ISD::UREM); } 837 void visitSRem(const User &I) { visitBinary(I, ISD::SREM); } 838 void visitFRem(const User &I) { visitBinary(I, ISD::FREM); } 839 void visitUDiv(const User &I) { visitBinary(I, ISD::UDIV); } 840 void visitSDiv(const User &I); 841 void visitFDiv(const User &I) { visitBinary(I, ISD::FDIV); } 842 void visitAnd (const User &I) { visitBinary(I, ISD::AND); } 843 void visitOr (const User &I) { visitBinary(I, ISD::OR); } 844 void visitXor (const User &I) { visitBinary(I, ISD::XOR); } 845 void visitShl (const User &I) { visitShift(I, ISD::SHL); } 846 void visitLShr(const User &I) { visitShift(I, ISD::SRL); } 847 void visitAShr(const User &I) { visitShift(I, ISD::SRA); } 848 void visitICmp(const User &I); 849 void visitFCmp(const User &I); 850 // Visit the conversion instructions 851 void visitTrunc(const User &I); 852 void visitZExt(const User &I); 853 void visitSExt(const User &I); 854 void visitFPTrunc(const User &I); 855 void visitFPExt(const User &I); 856 void visitFPToUI(const User &I); 857 void visitFPToSI(const User &I); 858 void visitUIToFP(const User &I); 859 void visitSIToFP(const User &I); 860 void visitPtrToInt(const User &I); 861 void visitIntToPtr(const User &I); 862 void visitBitCast(const User &I); 863 void visitAddrSpaceCast(const User &I); 864 865 void visitExtractElement(const User &I); 866 void visitInsertElement(const User &I); 867 void visitShuffleVector(const User &I); 868 869 void visitExtractValue(const ExtractValueInst &I); 870 void visitInsertValue(const InsertValueInst &I); 871 void visitLandingPad(const LandingPadInst &I); 872 873 void visitGetElementPtr(const User &I); 874 void visitSelect(const User &I); 875 876 void visitAlloca(const AllocaInst &I); 877 void visitLoad(const LoadInst &I); 878 void visitStore(const StoreInst &I); 879 void visitMaskedLoad(const CallInst &I); 880 void visitMaskedStore(const CallInst &I); 881 void visitMaskedGather(const CallInst &I); 882 void visitMaskedScatter(const CallInst &I); 883 void visitAtomicCmpXchg(const AtomicCmpXchgInst &I); 884 void visitAtomicRMW(const AtomicRMWInst &I); 885 void visitFence(const FenceInst &I); 886 void visitPHI(const PHINode &I); 887 void visitCall(const CallInst &I); 888 bool visitMemCmpCall(const CallInst &I); 889 bool visitMemChrCall(const CallInst &I); 890 bool visitStrCpyCall(const CallInst &I, bool isStpcpy); 891 bool visitStrCmpCall(const CallInst &I); 892 bool visitStrLenCall(const CallInst &I); 893 bool visitStrNLenCall(const CallInst &I); 894 bool visitUnaryFloatCall(const CallInst &I, unsigned Opcode); 895 bool visitBinaryFloatCall(const CallInst &I, unsigned Opcode); 896 void visitAtomicLoad(const LoadInst &I); 897 void visitAtomicStore(const StoreInst &I); 898 void visitLoadFromSwiftError(const LoadInst &I); 899 void visitStoreToSwiftError(const StoreInst &I); 900 901 void visitInlineAsm(ImmutableCallSite CS); 902 const char *visitIntrinsicCall(const CallInst &I, unsigned Intrinsic); 903 void visitTargetIntrinsic(const CallInst &I, unsigned Intrinsic); 904 905 void visitVAStart(const CallInst &I); 906 void visitVAArg(const VAArgInst &I); 907 void visitVAEnd(const CallInst &I); 908 void visitVACopy(const CallInst &I); 909 void visitStackmap(const CallInst &I); 910 void visitPatchpoint(ImmutableCallSite CS, 911 const BasicBlock *EHPadBB = nullptr); 912 913 // These two are implemented in StatepointLowering.cpp 914 void visitGCRelocate(const GCRelocateInst &I); 915 void visitGCResult(const GCResultInst &I); 916 917 void visitUserOp1(const Instruction &I) { 918 llvm_unreachable("UserOp1 should not exist at instruction selection time!"); 919 } 920 void visitUserOp2(const Instruction &I) { 921 llvm_unreachable("UserOp2 should not exist at instruction selection time!"); 922 } 923 924 void processIntegerCallValue(const Instruction &I, 925 SDValue Value, bool IsSigned); 926 927 void HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB); 928 929 void emitInlineAsmError(ImmutableCallSite CS, const Twine &Message); 930 931 /// EmitFuncArgumentDbgValue - If V is an function argument then create 932 /// corresponding DBG_VALUE machine instruction for it now. At the end of 933 /// instruction selection, they will be inserted to the entry BB. 934 bool EmitFuncArgumentDbgValue(const Value *V, DILocalVariable *Variable, 935 DIExpression *Expr, DILocation *DL, 936 int64_t Offset, bool IsIndirect, 937 const SDValue &N); 938 939 /// Return the next block after MBB, or nullptr if there is none. 940 MachineBasicBlock *NextBlock(MachineBasicBlock *MBB); 941 942 /// Update the DAG and DAG builder with the relevant information after 943 /// a new root node has been created which could be a tail call. 944 void updateDAGForMaybeTailCall(SDValue MaybeTC); 945 }; 946 947 /// RegsForValue - This struct represents the registers (physical or virtual) 948 /// that a particular set of values is assigned, and the type information about 949 /// the value. The most common situation is to represent one value at a time, 950 /// but struct or array values are handled element-wise as multiple values. The 951 /// splitting of aggregates is performed recursively, so that we never have 952 /// aggregate-typed registers. The values at this point do not necessarily have 953 /// legal types, so each value may require one or more registers of some legal 954 /// type. 955 /// 956 struct RegsForValue { 957 /// ValueVTs - The value types of the values, which may not be legal, and 958 /// may need be promoted or synthesized from one or more registers. 959 /// 960 SmallVector<EVT, 4> ValueVTs; 961 962 /// RegVTs - The value types of the registers. This is the same size as 963 /// ValueVTs and it records, for each value, what the type of the assigned 964 /// register or registers are. (Individual values are never synthesized 965 /// from more than one type of register.) 966 /// 967 /// With virtual registers, the contents of RegVTs is redundant with TLI's 968 /// getRegisterType member function, however when with physical registers 969 /// it is necessary to have a separate record of the types. 970 /// 971 SmallVector<MVT, 4> RegVTs; 972 973 /// Regs - This list holds the registers assigned to the values. 974 /// Each legal or promoted value requires one register, and each 975 /// expanded value requires multiple registers. 976 /// 977 SmallVector<unsigned, 4> Regs; 978 979 RegsForValue(); 980 981 RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, EVT valuevt); 982 983 RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 984 const DataLayout &DL, unsigned Reg, Type *Ty); 985 986 /// append - Add the specified values to this one. 987 void append(const RegsForValue &RHS) { 988 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end()); 989 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end()); 990 Regs.append(RHS.Regs.begin(), RHS.Regs.end()); 991 } 992 993 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from 994 /// this value and returns the result as a ValueVTs value. This uses 995 /// Chain/Flag as the input and updates them for the output Chain/Flag. 996 /// If the Flag pointer is NULL, no flag is used. 997 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo, 998 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 999 const Value *V = nullptr) const; 1000 1001 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the specified 1002 /// value into the registers specified by this object. This uses Chain/Flag 1003 /// as the input and updates them for the output Chain/Flag. If the Flag 1004 /// pointer is nullptr, no flag is used. If V is not nullptr, then it is used 1005 /// in printing better diagnostic messages on error. 1006 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, const SDLoc &dl, 1007 SDValue &Chain, SDValue *Flag, const Value *V = nullptr, 1008 ISD::NodeType PreferredExtendType = ISD::ANY_EXTEND) const; 1009 1010 /// AddInlineAsmOperands - Add this value to the specified inlineasm node 1011 /// operand list. This adds the code marker, matching input operand index 1012 /// (if applicable), and includes the number of values added into it. 1013 void AddInlineAsmOperands(unsigned Kind, bool HasMatching, 1014 unsigned MatchingIdx, const SDLoc &dl, 1015 SelectionDAG &DAG, std::vector<SDValue> &Ops) const; 1016 }; 1017 1018 } // end namespace llvm 1019 1020 #endif 1021