SelectionDAGBuilder.h 32 KB

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