1 //===- SelectionDAGBuilder.h - Selection-DAG building -----------*- C++ -*-===// 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 implements routines for translating from LLVM IR into SelectionDAG IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_LIB_CODEGEN_SELECTIONDAG_SELECTIONDAGBUILDER_H 14 #define LLVM_LIB_CODEGEN_SELECTIONDAG_SELECTIONDAGBUILDER_H 15 16 #include "StatepointLowering.h" 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/DenseMap.h" 19 #include "llvm/ADT/MapVector.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/CodeGen/AssignmentTrackingAnalysis.h" 22 #include "llvm/CodeGen/CodeGenCommonISel.h" 23 #include "llvm/CodeGen/ISDOpcodes.h" 24 #include "llvm/CodeGen/SelectionDAGNodes.h" 25 #include "llvm/CodeGen/SwitchLoweringUtils.h" 26 #include "llvm/CodeGen/TargetLowering.h" 27 #include "llvm/CodeGen/ValueTypes.h" 28 #include "llvm/CodeGenTypes/MachineValueType.h" 29 #include "llvm/IR/DebugLoc.h" 30 #include "llvm/IR/Instruction.h" 31 #include "llvm/Support/BranchProbability.h" 32 #include "llvm/Support/CodeGen.h" 33 #include "llvm/Support/ErrorHandling.h" 34 #include <algorithm> 35 #include <cassert> 36 #include <cstdint> 37 #include <optional> 38 #include <utility> 39 #include <vector> 40 41 namespace llvm { 42 43 class AAResults; 44 class AllocaInst; 45 class AtomicCmpXchgInst; 46 class AtomicRMWInst; 47 class AssumptionCache; 48 class BasicBlock; 49 class BranchInst; 50 class CallInst; 51 class CallBrInst; 52 class CatchPadInst; 53 class CatchReturnInst; 54 class CatchSwitchInst; 55 class CleanupPadInst; 56 class CleanupReturnInst; 57 class Constant; 58 class ConstrainedFPIntrinsic; 59 class DataLayout; 60 class DIExpression; 61 class DILocalVariable; 62 class DILocation; 63 class FenceInst; 64 class FunctionLoweringInfo; 65 class GCFunctionInfo; 66 class GCRelocateInst; 67 class GCResultInst; 68 class GCStatepointInst; 69 class IndirectBrInst; 70 class InvokeInst; 71 class LandingPadInst; 72 class LLVMContext; 73 class LoadInst; 74 class MachineBasicBlock; 75 class PHINode; 76 class ResumeInst; 77 class ReturnInst; 78 class SDDbgValue; 79 class SelectionDAG; 80 class StoreInst; 81 class SwiftErrorValueTracking; 82 class SwitchInst; 83 class TargetLibraryInfo; 84 class TargetMachine; 85 class Type; 86 class VAArgInst; 87 class UnreachableInst; 88 class Use; 89 class User; 90 class Value; 91 92 //===----------------------------------------------------------------------===// 93 /// SelectionDAGBuilder - This is the common target-independent lowering 94 /// implementation that is parameterized by a TargetLowering object. 95 /// 96 class SelectionDAGBuilder { 97 /// The current instruction being visited. 98 const Instruction *CurInst = nullptr; 99 100 DenseMap<const Value*, SDValue> NodeMap; 101 102 /// Maps argument value for unused arguments. This is used 103 /// to preserve debug information for incoming arguments. 104 DenseMap<const Value*, SDValue> UnusedArgNodeMap; 105 106 /// Helper type for DanglingDebugInfoMap. 107 class DanglingDebugInfo { 108 unsigned SDNodeOrder = 0; 109 110 public: 111 DILocalVariable *Variable; 112 DIExpression *Expression; 113 DebugLoc dl; 114 DanglingDebugInfo() = default; DanglingDebugInfo(DILocalVariable * Var,DIExpression * Expr,DebugLoc DL,unsigned SDNO)115 DanglingDebugInfo(DILocalVariable *Var, DIExpression *Expr, DebugLoc DL, 116 unsigned SDNO) 117 : SDNodeOrder(SDNO), Variable(Var), Expression(Expr), 118 dl(std::move(DL)) {} 119 getVariable()120 DILocalVariable *getVariable() const { return Variable; } getExpression()121 DIExpression *getExpression() const { return Expression; } getDebugLoc()122 DebugLoc getDebugLoc() const { return dl; } getSDNodeOrder()123 unsigned getSDNodeOrder() const { return SDNodeOrder; } 124 125 /// Helper for printing DanglingDebugInfo. This hoop-jumping is to 126 /// store a Value pointer, so that we can print a whole DDI as one object. 127 /// Call SelectionDAGBuilder::printDDI instead of using directly. 128 struct Print { PrintPrint129 Print(const Value *V, const DanglingDebugInfo &DDI) : V(V), DDI(DDI) {} 130 const Value *V; 131 const DanglingDebugInfo &DDI; 132 friend raw_ostream &operator<<(raw_ostream &OS, 133 const DanglingDebugInfo::Print &P) { 134 OS << "DDI(var=" << *P.DDI.getVariable(); 135 if (P.V) 136 OS << ", val=" << *P.V; 137 else 138 OS << ", val=nullptr"; 139 140 OS << ", expr=" << *P.DDI.getExpression() 141 << ", order=" << P.DDI.getSDNodeOrder() 142 << ", loc=" << P.DDI.getDebugLoc() << ")"; 143 return OS; 144 } 145 }; 146 }; 147 148 /// Returns an object that defines `raw_ostream &operator<<` for printing. 149 /// Usage example: 150 //// errs() << printDDI(MyDanglingInfo) << " is dangling\n"; printDDI(const Value * V,const DanglingDebugInfo & DDI)151 DanglingDebugInfo::Print printDDI(const Value *V, 152 const DanglingDebugInfo &DDI) { 153 return DanglingDebugInfo::Print(V, DDI); 154 } 155 156 /// Helper type for DanglingDebugInfoMap. 157 typedef std::vector<DanglingDebugInfo> DanglingDebugInfoVector; 158 159 /// Keeps track of dbg_values for which we have not yet seen the referent. 160 /// We defer handling these until we do see it. 161 MapVector<const Value*, DanglingDebugInfoVector> DanglingDebugInfoMap; 162 163 /// Cache the module flag for whether we should use debug-info assignment 164 /// tracking. 165 bool AssignmentTrackingEnabled = false; 166 167 public: 168 /// Loads are not emitted to the program immediately. We bunch them up and 169 /// then emit token factor nodes when possible. This allows us to get simple 170 /// disambiguation between loads without worrying about alias analysis. 171 SmallVector<SDValue, 8> PendingLoads; 172 173 /// State used while lowering a statepoint sequence (gc_statepoint, 174 /// gc_relocate, and gc_result). See StatepointLowering.hpp/cpp for details. 175 StatepointLoweringState StatepointLowering; 176 177 private: 178 /// CopyToReg nodes that copy values to virtual registers for export to other 179 /// blocks need to be emitted before any terminator instruction, but they have 180 /// no other ordering requirements. We bunch them up and the emit a single 181 /// tokenfactor for them just before terminator instructions. 182 SmallVector<SDValue, 8> PendingExports; 183 184 /// Similar to loads, nodes corresponding to constrained FP intrinsics are 185 /// bunched up and emitted when necessary. These can be moved across each 186 /// other and any (normal) memory operation (load or store), but not across 187 /// calls or instructions having unspecified side effects. As a special 188 /// case, constrained FP intrinsics using fpexcept.strict may not be deleted 189 /// even if otherwise unused, so they need to be chained before any 190 /// terminator instruction (like PendingExports). We track the latter 191 /// set of nodes in a separate list. 192 SmallVector<SDValue, 8> PendingConstrainedFP; 193 SmallVector<SDValue, 8> PendingConstrainedFPStrict; 194 195 /// Update root to include all chains from the Pending list. 196 SDValue updateRoot(SmallVectorImpl<SDValue> &Pending); 197 198 /// A unique monotonically increasing number used to order the SDNodes we 199 /// create. 200 unsigned SDNodeOrder; 201 202 /// Emit comparison and split W into two subtrees. 203 void splitWorkItem(SwitchCG::SwitchWorkList &WorkList, 204 const SwitchCG::SwitchWorkListItem &W, Value *Cond, 205 MachineBasicBlock *SwitchMBB); 206 207 /// Lower W. 208 void lowerWorkItem(SwitchCG::SwitchWorkListItem W, Value *Cond, 209 MachineBasicBlock *SwitchMBB, 210 MachineBasicBlock *DefaultMBB); 211 212 /// Peel the top probability case if it exceeds the threshold 213 MachineBasicBlock * 214 peelDominantCaseCluster(const SwitchInst &SI, 215 SwitchCG::CaseClusterVector &Clusters, 216 BranchProbability &PeeledCaseProb); 217 218 private: 219 const TargetMachine &TM; 220 221 public: 222 /// Lowest valid SDNodeOrder. The special case 0 is reserved for scheduling 223 /// nodes without a corresponding SDNode. 224 static const unsigned LowestSDNodeOrder = 1; 225 226 SelectionDAG &DAG; 227 BatchAAResults *BatchAA = nullptr; 228 AssumptionCache *AC = nullptr; 229 const TargetLibraryInfo *LibInfo = nullptr; 230 231 class SDAGSwitchLowering : public SwitchCG::SwitchLowering { 232 public: SDAGSwitchLowering(SelectionDAGBuilder * sdb,FunctionLoweringInfo & funcinfo)233 SDAGSwitchLowering(SelectionDAGBuilder *sdb, FunctionLoweringInfo &funcinfo) 234 : SwitchCG::SwitchLowering(funcinfo), SDB(sdb) {} 235 236 void addSuccessorWithProb( 237 MachineBasicBlock *Src, MachineBasicBlock *Dst, 238 BranchProbability Prob = BranchProbability::getUnknown()) override { 239 SDB->addSuccessorWithProb(Src, Dst, Prob); 240 } 241 242 private: 243 SelectionDAGBuilder *SDB = nullptr; 244 }; 245 246 // Data related to deferred switch lowerings. Used to construct additional 247 // Basic Blocks in SelectionDAGISel::FinishBasicBlock. 248 std::unique_ptr<SDAGSwitchLowering> SL; 249 250 /// A StackProtectorDescriptor structure used to communicate stack protector 251 /// information in between SelectBasicBlock and FinishBasicBlock. 252 StackProtectorDescriptor SPDescriptor; 253 254 // Emit PHI-node-operand constants only once even if used by multiple 255 // PHI nodes. 256 DenseMap<const Constant *, Register> ConstantsOut; 257 258 /// Information about the function as a whole. 259 FunctionLoweringInfo &FuncInfo; 260 261 /// Information about the swifterror values used throughout the function. 262 SwiftErrorValueTracking &SwiftError; 263 264 /// Garbage collection metadata for the function. 265 GCFunctionInfo *GFI = nullptr; 266 267 /// Map a landing pad to the call site indexes. 268 DenseMap<MachineBasicBlock *, SmallVector<unsigned, 4>> LPadToCallSiteMap; 269 270 /// This is set to true if a call in the current block has been translated as 271 /// a tail call. In this case, no subsequent DAG nodes should be created. 272 bool HasTailCall = false; 273 274 LLVMContext *Context = nullptr; 275 SelectionDAGBuilder(SelectionDAG & dag,FunctionLoweringInfo & funcinfo,SwiftErrorValueTracking & swifterror,CodeGenOptLevel ol)276 SelectionDAGBuilder(SelectionDAG &dag, FunctionLoweringInfo &funcinfo, 277 SwiftErrorValueTracking &swifterror, CodeGenOptLevel ol) 278 : SDNodeOrder(LowestSDNodeOrder), TM(dag.getTarget()), DAG(dag), 279 SL(std::make_unique<SDAGSwitchLowering>(this, funcinfo)), 280 FuncInfo(funcinfo), SwiftError(swifterror) {} 281 282 void init(GCFunctionInfo *gfi, BatchAAResults *BatchAA, AssumptionCache *AC, 283 const TargetLibraryInfo *li); 284 285 /// Clear out the current SelectionDAG and the associated state and prepare 286 /// this SelectionDAGBuilder object to be used for a new block. This doesn't 287 /// clear out information about additional blocks that are needed to complete 288 /// switch lowering or PHI node updating; that information is cleared out as 289 /// it is consumed. 290 void clear(); 291 292 /// Clear the dangling debug information map. This function is separated from 293 /// the clear so that debug information that is dangling in a basic block can 294 /// be properly resolved in a different basic block. This allows the 295 /// SelectionDAG to resolve dangling debug information attached to PHI nodes. 296 void clearDanglingDebugInfo(); 297 298 /// Return the current virtual root of the Selection DAG, flushing any 299 /// PendingLoad items. This must be done before emitting a store or any other 300 /// memory node that may need to be ordered after any prior load instructions. 301 SDValue getMemoryRoot(); 302 303 /// Similar to getMemoryRoot, but also flushes PendingConstrainedFP(Strict) 304 /// items. This must be done before emitting any call other any other node 305 /// that may need to be ordered after FP instructions due to other side 306 /// effects. 307 SDValue getRoot(); 308 309 /// Similar to getRoot, but instead of flushing all the PendingLoad items, 310 /// flush all the PendingExports (and PendingConstrainedFPStrict) items. 311 /// It is necessary to do this before emitting a terminator instruction. 312 SDValue getControlRoot(); 313 getCurSDLoc()314 SDLoc getCurSDLoc() const { 315 return SDLoc(CurInst, SDNodeOrder); 316 } 317 getCurDebugLoc()318 DebugLoc getCurDebugLoc() const { 319 return CurInst ? CurInst->getDebugLoc() : DebugLoc(); 320 } 321 322 void CopyValueToVirtualRegister(const Value *V, Register Reg, 323 ISD::NodeType ExtendType = ISD::ANY_EXTEND); 324 325 void visit(const Instruction &I); 326 void visitDbgInfo(const Instruction &I); 327 328 void visit(unsigned Opcode, const User &I); 329 330 /// If there was virtual register allocated for the value V emit CopyFromReg 331 /// of the specified type Ty. Return empty SDValue() otherwise. 332 SDValue getCopyFromRegs(const Value *V, Type *Ty); 333 334 /// Register a dbg_value which relies on a Value which we have not yet seen. 335 void addDanglingDebugInfo(SmallVectorImpl<Value *> &Values, 336 DILocalVariable *Var, DIExpression *Expr, 337 bool IsVariadic, DebugLoc DL, unsigned Order); 338 339 /// If we have dangling debug info that describes \p Variable, or an 340 /// overlapping part of variable considering the \p Expr, then this method 341 /// will drop that debug info as it isn't valid any longer. 342 void dropDanglingDebugInfo(const DILocalVariable *Variable, 343 const DIExpression *Expr); 344 345 /// If we saw an earlier dbg_value referring to V, generate the debug data 346 /// structures now that we've seen its definition. 347 void resolveDanglingDebugInfo(const Value *V, SDValue Val); 348 349 /// For the given dangling debuginfo record, perform last-ditch efforts to 350 /// resolve the debuginfo to something that is represented in this DAG. If 351 /// this cannot be done, produce an Undef debug value record. 352 void salvageUnresolvedDbgValue(const Value *V, DanglingDebugInfo &DDI); 353 354 /// For a given list of Values, attempt to create and record a SDDbgValue in 355 /// the SelectionDAG. 356 bool handleDebugValue(ArrayRef<const Value *> Values, DILocalVariable *Var, 357 DIExpression *Expr, DebugLoc DbgLoc, unsigned Order, 358 bool IsVariadic); 359 360 /// Create a record for a kill location debug intrinsic. 361 void handleKillDebugValue(DILocalVariable *Var, DIExpression *Expr, 362 DebugLoc DbgLoc, unsigned Order); 363 364 void handleDebugDeclare(Value *Address, DILocalVariable *Variable, 365 DIExpression *Expression, DebugLoc DL); 366 367 /// Evict any dangling debug information, attempting to salvage it first. 368 void resolveOrClearDbgInfo(); 369 370 SDValue getValue(const Value *V); 371 372 SDValue getNonRegisterValue(const Value *V); 373 SDValue getValueImpl(const Value *V); 374 setValue(const Value * V,SDValue NewN)375 void setValue(const Value *V, SDValue NewN) { 376 SDValue &N = NodeMap[V]; 377 assert(!N.getNode() && "Already set a value for this node!"); 378 N = NewN; 379 } 380 setUnusedArgValue(const Value * V,SDValue NewN)381 void setUnusedArgValue(const Value *V, SDValue NewN) { 382 SDValue &N = UnusedArgNodeMap[V]; 383 assert(!N.getNode() && "Already set a value for this node!"); 384 N = NewN; 385 } 386 387 bool shouldKeepJumpConditionsTogether( 388 const FunctionLoweringInfo &FuncInfo, const BranchInst &I, 389 Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs, 390 TargetLoweringBase::CondMergingParams Params) const; 391 392 void FindMergedConditions(const Value *Cond, MachineBasicBlock *TBB, 393 MachineBasicBlock *FBB, MachineBasicBlock *CurBB, 394 MachineBasicBlock *SwitchBB, 395 Instruction::BinaryOps Opc, BranchProbability TProb, 396 BranchProbability FProb, bool InvertCond); 397 void EmitBranchForMergedCondition(const Value *Cond, MachineBasicBlock *TBB, 398 MachineBasicBlock *FBB, 399 MachineBasicBlock *CurBB, 400 MachineBasicBlock *SwitchBB, 401 BranchProbability TProb, BranchProbability FProb, 402 bool InvertCond); 403 bool ShouldEmitAsBranches(const std::vector<SwitchCG::CaseBlock> &Cases); 404 bool isExportableFromCurrentBlock(const Value *V, const BasicBlock *FromBB); 405 void CopyToExportRegsIfNeeded(const Value *V); 406 void ExportFromCurrentBlock(const Value *V); 407 void LowerCallTo(const CallBase &CB, SDValue Callee, bool IsTailCall, 408 bool IsMustTailCall, const BasicBlock *EHPadBB = nullptr, 409 const TargetLowering::PtrAuthInfo *PAI = nullptr); 410 411 // Lower range metadata from 0 to N to assert zext to an integer of nearest 412 // floor power of two. 413 SDValue lowerRangeToAssertZExt(SelectionDAG &DAG, const Instruction &I, 414 SDValue Op); 415 416 void populateCallLoweringInfo(TargetLowering::CallLoweringInfo &CLI, 417 const CallBase *Call, unsigned ArgIdx, 418 unsigned NumArgs, SDValue Callee, 419 Type *ReturnTy, AttributeSet RetAttrs, 420 bool IsPatchPoint); 421 422 std::pair<SDValue, SDValue> 423 lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 424 const BasicBlock *EHPadBB = nullptr); 425 426 /// When an MBB was split during scheduling, update the 427 /// references that need to refer to the last resulting block. 428 void UpdateSplitBlock(MachineBasicBlock *First, MachineBasicBlock *Last); 429 430 /// Describes a gc.statepoint or a gc.statepoint like thing for the purposes 431 /// of lowering into a STATEPOINT node. 432 struct StatepointLoweringInfo { 433 /// Bases[i] is the base pointer for Ptrs[i]. Together they denote the set 434 /// of gc pointers this STATEPOINT has to relocate. 435 SmallVector<const Value *, 16> Bases; 436 SmallVector<const Value *, 16> Ptrs; 437 438 /// The set of gc.relocate calls associated with this gc.statepoint. 439 SmallVector<const GCRelocateInst *, 16> GCRelocates; 440 441 /// The full list of gc-live arguments to the gc.statepoint being lowered. 442 ArrayRef<const Use> GCLives; 443 444 /// The gc.statepoint instruction. 445 const Instruction *StatepointInstr = nullptr; 446 447 /// The list of gc transition arguments present in the gc.statepoint being 448 /// lowered. 449 ArrayRef<const Use> GCTransitionArgs; 450 451 /// The ID that the resulting STATEPOINT instruction has to report. 452 uint64_t ID = -1; 453 454 /// Information regarding the underlying call instruction. 455 TargetLowering::CallLoweringInfo CLI; 456 457 /// The deoptimization state associated with this gc.statepoint call, if 458 /// any. 459 ArrayRef<const Use> DeoptState; 460 461 /// Flags associated with the meta arguments being lowered. 462 uint64_t StatepointFlags = -1; 463 464 /// The number of patchable bytes the call needs to get lowered into. 465 unsigned NumPatchBytes = -1; 466 467 /// The exception handling unwind destination, in case this represents an 468 /// invoke of gc.statepoint. 469 const BasicBlock *EHPadBB = nullptr; 470 StatepointLoweringInfoStatepointLoweringInfo471 explicit StatepointLoweringInfo(SelectionDAG &DAG) : CLI(DAG) {} 472 }; 473 474 /// Lower \p SLI into a STATEPOINT instruction. 475 SDValue LowerAsSTATEPOINT(StatepointLoweringInfo &SI); 476 477 // This function is responsible for the whole statepoint lowering process. 478 // It uniformly handles invoke and call statepoints. 479 void LowerStatepoint(const GCStatepointInst &I, 480 const BasicBlock *EHPadBB = nullptr); 481 482 void LowerCallSiteWithDeoptBundle(const CallBase *Call, SDValue Callee, 483 const BasicBlock *EHPadBB); 484 485 void LowerDeoptimizeCall(const CallInst *CI); 486 void LowerDeoptimizingReturn(); 487 488 void LowerCallSiteWithDeoptBundleImpl(const CallBase *Call, SDValue Callee, 489 const BasicBlock *EHPadBB, 490 bool VarArgDisallowed, 491 bool ForceVoidReturnTy); 492 493 void LowerCallSiteWithPtrAuthBundle(const CallBase &CB, 494 const BasicBlock *EHPadBB); 495 496 /// Returns the type of FrameIndex and TargetFrameIndex nodes. getFrameIndexTy()497 MVT getFrameIndexTy() { 498 return DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout()); 499 } 500 501 private: 502 // Terminator instructions. 503 void visitRet(const ReturnInst &I); 504 void visitBr(const BranchInst &I); 505 void visitSwitch(const SwitchInst &I); 506 void visitIndirectBr(const IndirectBrInst &I); 507 void visitUnreachable(const UnreachableInst &I); 508 void visitCleanupRet(const CleanupReturnInst &I); 509 void visitCatchSwitch(const CatchSwitchInst &I); 510 void visitCatchRet(const CatchReturnInst &I); 511 void visitCatchPad(const CatchPadInst &I); 512 void visitCleanupPad(const CleanupPadInst &CPI); 513 514 BranchProbability getEdgeProbability(const MachineBasicBlock *Src, 515 const MachineBasicBlock *Dst) const; 516 void addSuccessorWithProb( 517 MachineBasicBlock *Src, MachineBasicBlock *Dst, 518 BranchProbability Prob = BranchProbability::getUnknown()); 519 520 public: 521 void visitSwitchCase(SwitchCG::CaseBlock &CB, MachineBasicBlock *SwitchBB); 522 void visitSPDescriptorParent(StackProtectorDescriptor &SPD, 523 MachineBasicBlock *ParentBB); 524 void visitSPDescriptorFailure(StackProtectorDescriptor &SPD); 525 void visitBitTestHeader(SwitchCG::BitTestBlock &B, 526 MachineBasicBlock *SwitchBB); 527 void visitBitTestCase(SwitchCG::BitTestBlock &BB, MachineBasicBlock *NextMBB, 528 BranchProbability BranchProbToNext, Register Reg, 529 SwitchCG::BitTestCase &B, MachineBasicBlock *SwitchBB); 530 void visitJumpTable(SwitchCG::JumpTable &JT); 531 void visitJumpTableHeader(SwitchCG::JumpTable &JT, 532 SwitchCG::JumpTableHeader &JTH, 533 MachineBasicBlock *SwitchBB); 534 535 private: 536 // These all get lowered before this pass. 537 void visitInvoke(const InvokeInst &I); 538 void visitCallBr(const CallBrInst &I); 539 void visitCallBrLandingPad(const CallInst &I); 540 void visitResume(const ResumeInst &I); 541 542 void visitUnary(const User &I, unsigned Opcode); visitFNeg(const User & I)543 void visitFNeg(const User &I) { visitUnary(I, ISD::FNEG); } 544 545 void visitBinary(const User &I, unsigned Opcode); 546 void visitShift(const User &I, unsigned Opcode); visitAdd(const User & I)547 void visitAdd(const User &I) { visitBinary(I, ISD::ADD); } visitFAdd(const User & I)548 void visitFAdd(const User &I) { visitBinary(I, ISD::FADD); } visitSub(const User & I)549 void visitSub(const User &I) { visitBinary(I, ISD::SUB); } visitFSub(const User & I)550 void visitFSub(const User &I) { visitBinary(I, ISD::FSUB); } visitMul(const User & I)551 void visitMul(const User &I) { visitBinary(I, ISD::MUL); } visitFMul(const User & I)552 void visitFMul(const User &I) { visitBinary(I, ISD::FMUL); } visitURem(const User & I)553 void visitURem(const User &I) { visitBinary(I, ISD::UREM); } visitSRem(const User & I)554 void visitSRem(const User &I) { visitBinary(I, ISD::SREM); } visitFRem(const User & I)555 void visitFRem(const User &I) { visitBinary(I, ISD::FREM); } visitUDiv(const User & I)556 void visitUDiv(const User &I) { visitBinary(I, ISD::UDIV); } 557 void visitSDiv(const User &I); visitFDiv(const User & I)558 void visitFDiv(const User &I) { visitBinary(I, ISD::FDIV); } visitAnd(const User & I)559 void visitAnd (const User &I) { visitBinary(I, ISD::AND); } visitOr(const User & I)560 void visitOr (const User &I) { visitBinary(I, ISD::OR); } visitXor(const User & I)561 void visitXor (const User &I) { visitBinary(I, ISD::XOR); } visitShl(const User & I)562 void visitShl (const User &I) { visitShift(I, ISD::SHL); } visitLShr(const User & I)563 void visitLShr(const User &I) { visitShift(I, ISD::SRL); } visitAShr(const User & I)564 void visitAShr(const User &I) { visitShift(I, ISD::SRA); } 565 void visitICmp(const ICmpInst &I); 566 void visitFCmp(const FCmpInst &I); 567 // Visit the conversion instructions 568 void visitTrunc(const User &I); 569 void visitZExt(const User &I); 570 void visitSExt(const User &I); 571 void visitFPTrunc(const User &I); 572 void visitFPExt(const User &I); 573 void visitFPToUI(const User &I); 574 void visitFPToSI(const User &I); 575 void visitUIToFP(const User &I); 576 void visitSIToFP(const User &I); 577 void visitPtrToInt(const User &I); 578 void visitIntToPtr(const User &I); 579 void visitBitCast(const User &I); 580 void visitAddrSpaceCast(const User &I); 581 582 void visitExtractElement(const User &I); 583 void visitInsertElement(const User &I); 584 void visitShuffleVector(const User &I); 585 586 void visitExtractValue(const ExtractValueInst &I); 587 void visitInsertValue(const InsertValueInst &I); 588 void visitLandingPad(const LandingPadInst &LP); 589 590 void visitGetElementPtr(const User &I); 591 void visitSelect(const User &I); 592 593 void visitAlloca(const AllocaInst &I); 594 void visitLoad(const LoadInst &I); 595 void visitStore(const StoreInst &I); 596 void visitMaskedLoad(const CallInst &I, bool IsExpanding = false); 597 void visitMaskedStore(const CallInst &I, bool IsCompressing = false); 598 void visitMaskedGather(const CallInst &I); 599 void visitMaskedScatter(const CallInst &I); 600 void visitAtomicCmpXchg(const AtomicCmpXchgInst &I); 601 void visitAtomicRMW(const AtomicRMWInst &I); 602 void visitFence(const FenceInst &I); 603 void visitPHI(const PHINode &I); 604 void visitCall(const CallInst &I); 605 bool visitMemCmpBCmpCall(const CallInst &I); 606 bool visitMemPCpyCall(const CallInst &I); 607 bool visitMemChrCall(const CallInst &I); 608 bool visitStrCpyCall(const CallInst &I, bool isStpcpy); 609 bool visitStrCmpCall(const CallInst &I); 610 bool visitStrLenCall(const CallInst &I); 611 bool visitStrNLenCall(const CallInst &I); 612 bool visitUnaryFloatCall(const CallInst &I, unsigned Opcode); 613 bool visitBinaryFloatCall(const CallInst &I, unsigned Opcode); 614 void visitAtomicLoad(const LoadInst &I); 615 void visitAtomicStore(const StoreInst &I); 616 void visitLoadFromSwiftError(const LoadInst &I); 617 void visitStoreToSwiftError(const StoreInst &I); 618 void visitFreeze(const FreezeInst &I); 619 620 void visitInlineAsm(const CallBase &Call, 621 const BasicBlock *EHPadBB = nullptr); 622 623 bool visitEntryValueDbgValue(ArrayRef<const Value *> Values, 624 DILocalVariable *Variable, DIExpression *Expr, 625 DebugLoc DbgLoc); 626 void visitIntrinsicCall(const CallInst &I, unsigned Intrinsic); 627 void visitTargetIntrinsic(const CallInst &I, unsigned Intrinsic); 628 void visitConstrainedFPIntrinsic(const ConstrainedFPIntrinsic &FPI); 629 void visitConvergenceControl(const CallInst &I, unsigned Intrinsic); 630 void visitVectorHistogram(const CallInst &I, unsigned IntrinsicID); 631 void visitVectorExtractLastActive(const CallInst &I, unsigned Intrinsic); 632 void visitVPLoad(const VPIntrinsic &VPIntrin, EVT VT, 633 const SmallVectorImpl<SDValue> &OpValues); 634 void visitVPStore(const VPIntrinsic &VPIntrin, 635 const SmallVectorImpl<SDValue> &OpValues); 636 void visitVPGather(const VPIntrinsic &VPIntrin, EVT VT, 637 const SmallVectorImpl<SDValue> &OpValues); 638 void visitVPScatter(const VPIntrinsic &VPIntrin, 639 const SmallVectorImpl<SDValue> &OpValues); 640 void visitVPStridedLoad(const VPIntrinsic &VPIntrin, EVT VT, 641 const SmallVectorImpl<SDValue> &OpValues); 642 void visitVPStridedStore(const VPIntrinsic &VPIntrin, 643 const SmallVectorImpl<SDValue> &OpValues); 644 void visitVPCmp(const VPCmpIntrinsic &VPIntrin); 645 void visitVectorPredicationIntrinsic(const VPIntrinsic &VPIntrin); 646 647 void visitVAStart(const CallInst &I); 648 void visitVAArg(const VAArgInst &I); 649 void visitVAEnd(const CallInst &I); 650 void visitVACopy(const CallInst &I); 651 void visitStackmap(const CallInst &I); 652 void visitPatchpoint(const CallBase &CB, const BasicBlock *EHPadBB = nullptr); 653 654 // These two are implemented in StatepointLowering.cpp 655 void visitGCRelocate(const GCRelocateInst &Relocate); 656 void visitGCResult(const GCResultInst &I); 657 658 void visitVectorReduce(const CallInst &I, unsigned Intrinsic); 659 void visitVectorReverse(const CallInst &I); 660 void visitVectorSplice(const CallInst &I); 661 void visitVectorInterleave(const CallInst &I, unsigned Factor); 662 void visitVectorDeinterleave(const CallInst &I, unsigned Factor); 663 void visitStepVector(const CallInst &I); 664 visitUserOp1(const Instruction & I)665 void visitUserOp1(const Instruction &I) { 666 llvm_unreachable("UserOp1 should not exist at instruction selection time!"); 667 } visitUserOp2(const Instruction & I)668 void visitUserOp2(const Instruction &I) { 669 llvm_unreachable("UserOp2 should not exist at instruction selection time!"); 670 } 671 672 void processIntegerCallValue(const Instruction &I, 673 SDValue Value, bool IsSigned); 674 675 void HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB); 676 677 void emitInlineAsmError(const CallBase &Call, const Twine &Message); 678 679 /// An enum that states to emit func argument dbg value the kind of intrinsic 680 /// it originally had. This controls the internal behavior of 681 /// EmitFuncArgumentDbgValue. 682 enum class FuncArgumentDbgValueKind { 683 Value, // This was originally a llvm.dbg.value. 684 Declare, // This was originally a llvm.dbg.declare. 685 }; 686 687 /// If V is an function argument then create corresponding DBG_VALUE machine 688 /// instruction for it now. At the end of instruction selection, they will be 689 /// inserted to the entry BB. 690 bool EmitFuncArgumentDbgValue(const Value *V, DILocalVariable *Variable, 691 DIExpression *Expr, DILocation *DL, 692 FuncArgumentDbgValueKind Kind, 693 const SDValue &N); 694 695 /// Return the next block after MBB, or nullptr if there is none. 696 MachineBasicBlock *NextBlock(MachineBasicBlock *MBB); 697 698 /// Update the DAG and DAG builder with the relevant information after 699 /// a new root node has been created which could be a tail call. 700 void updateDAGForMaybeTailCall(SDValue MaybeTC); 701 702 /// Return the appropriate SDDbgValue based on N. 703 SDDbgValue *getDbgValue(SDValue N, DILocalVariable *Variable, 704 DIExpression *Expr, const DebugLoc &dl, 705 unsigned DbgSDNodeOrder); 706 707 SDValue lowerStartEH(SDValue Chain, const BasicBlock *EHPadBB, 708 MCSymbol *&BeginLabel); 709 SDValue lowerEndEH(SDValue Chain, const InvokeInst *II, 710 const BasicBlock *EHPadBB, MCSymbol *BeginLabel); 711 }; 712 713 /// This struct represents the registers (physical or virtual) 714 /// that a particular set of values is assigned, and the type information about 715 /// the value. The most common situation is to represent one value at a time, 716 /// but struct or array values are handled element-wise as multiple values. The 717 /// splitting of aggregates is performed recursively, so that we never have 718 /// aggregate-typed registers. The values at this point do not necessarily have 719 /// legal types, so each value may require one or more registers of some legal 720 /// type. 721 /// 722 struct RegsForValue { 723 /// The value types of the values, which may not be legal, and 724 /// may need be promoted or synthesized from one or more registers. 725 SmallVector<EVT, 4> ValueVTs; 726 727 /// The value types of the registers. This is the same size as ValueVTs and it 728 /// records, for each value, what the type of the assigned register or 729 /// registers are. (Individual values are never synthesized from more than one 730 /// type of register.) 731 /// 732 /// With virtual registers, the contents of RegVTs is redundant with TLI's 733 /// getRegisterType member function, however when with physical registers 734 /// it is necessary to have a separate record of the types. 735 SmallVector<MVT, 4> RegVTs; 736 737 /// This list holds the registers assigned to the values. 738 /// Each legal or promoted value requires one register, and each 739 /// expanded value requires multiple registers. 740 SmallVector<Register, 4> Regs; 741 742 /// This list holds the number of registers for each value. 743 SmallVector<unsigned, 4> RegCount; 744 745 /// Records if this value needs to be treated in an ABI dependant manner, 746 /// different to normal type legalization. 747 std::optional<CallingConv::ID> CallConv; 748 749 RegsForValue() = default; 750 RegsForValue(const SmallVector<Register, 4> ®s, MVT regvt, EVT valuevt, 751 std::optional<CallingConv::ID> CC = std::nullopt); 752 RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 753 const DataLayout &DL, Register Reg, Type *Ty, 754 std::optional<CallingConv::ID> CC); 755 isABIMangledRegsForValue756 bool isABIMangled() const { return CallConv.has_value(); } 757 758 /// Add the specified values to this one. appendRegsForValue759 void append(const RegsForValue &RHS) { 760 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end()); 761 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end()); 762 Regs.append(RHS.Regs.begin(), RHS.Regs.end()); 763 RegCount.push_back(RHS.Regs.size()); 764 } 765 766 /// Emit a series of CopyFromReg nodes that copies from this value and returns 767 /// the result as a ValueVTs value. This uses Chain/Flag as the input and 768 /// updates them for the output Chain/Flag. If the Flag pointer is NULL, no 769 /// flag is used. 770 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo, 771 const SDLoc &dl, SDValue &Chain, SDValue *Glue, 772 const Value *V = nullptr) const; 773 774 /// Emit a series of CopyToReg nodes that copies the specified value into the 775 /// registers specified by this object. This uses Chain/Flag as the input and 776 /// updates them for the output Chain/Flag. If the Flag pointer is nullptr, no 777 /// flag is used. If V is not nullptr, then it is used in printing better 778 /// diagnostic messages on error. 779 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, const SDLoc &dl, 780 SDValue &Chain, SDValue *Glue, const Value *V = nullptr, 781 ISD::NodeType PreferredExtendType = ISD::ANY_EXTEND) const; 782 783 /// Add this value to the specified inlineasm node operand list. This adds the 784 /// code marker, matching input operand index (if applicable), and includes 785 /// the number of values added into it. 786 void AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching, 787 unsigned MatchingIdx, const SDLoc &dl, 788 SelectionDAG &DAG, std::vector<SDValue> &Ops) const; 789 790 /// Check if the total RegCount is greater than one. occupiesMultipleRegsRegsForValue791 bool occupiesMultipleRegs() const { 792 return std::accumulate(RegCount.begin(), RegCount.end(), 0) > 1; 793 } 794 795 /// Return a list of registers and their sizes. 796 SmallVector<std::pair<Register, TypeSize>, 4> getRegsAndSizes() const; 797 }; 798 799 } // end namespace llvm 800 801 #endif // LLVM_LIB_CODEGEN_SELECTIONDAG_SELECTIONDAGBUILDER_H 802