SelectionDAGBuilder.h 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  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/APInt.h"
  16. #include "llvm/ADT/ArrayRef.h"
  17. #include "llvm/ADT/DenseMap.h"
  18. #include "llvm/ADT/MapVector.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/Analysis/AliasAnalysis.h"
  21. #include "llvm/CodeGen/ISDOpcodes.h"
  22. #include "llvm/CodeGen/SelectionDAG.h"
  23. #include "llvm/CodeGen/SelectionDAGNodes.h"
  24. #include "llvm/CodeGen/SwitchLoweringUtils.h"
  25. #include "llvm/CodeGen/TargetLowering.h"
  26. #include "llvm/CodeGen/ValueTypes.h"
  27. #include "llvm/IR/CallSite.h"
  28. #include "llvm/IR/DebugLoc.h"
  29. #include "llvm/IR/Instruction.h"
  30. #include "llvm/IR/Statepoint.h"
  31. #include "llvm/Support/BranchProbability.h"
  32. #include "llvm/Support/CodeGen.h"
  33. #include "llvm/Support/ErrorHandling.h"
  34. #include "llvm/Support/MachineValueType.h"
  35. #include <algorithm>
  36. #include <cassert>
  37. #include <cstdint>
  38. #include <utility>
  39. #include <vector>
  40. namespace llvm {
  41. class AllocaInst;
  42. class AtomicCmpXchgInst;
  43. class AtomicRMWInst;
  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 ConstantInt;
  55. class ConstrainedFPIntrinsic;
  56. class DbgValueInst;
  57. class DataLayout;
  58. class DIExpression;
  59. class DILocalVariable;
  60. class DILocation;
  61. class FenceInst;
  62. class FunctionLoweringInfo;
  63. class GCFunctionInfo;
  64. class GCRelocateInst;
  65. class GCResultInst;
  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 StoreInst;
  77. class SwiftErrorValueTracking;
  78. class SwitchInst;
  79. class TargetLibraryInfo;
  80. class TargetMachine;
  81. class Type;
  82. class VAArgInst;
  83. class UnreachableInst;
  84. class Use;
  85. class User;
  86. class Value;
  87. //===----------------------------------------------------------------------===//
  88. /// SelectionDAGBuilder - This is the common target-independent lowering
  89. /// implementation that is parameterized by a TargetLowering object.
  90. ///
  91. class SelectionDAGBuilder {
  92. /// The current instruction being visited.
  93. const Instruction *CurInst = nullptr;
  94. DenseMap<const Value*, SDValue> NodeMap;
  95. /// Maps argument value for unused arguments. This is used
  96. /// to preserve debug information for incoming arguments.
  97. DenseMap<const Value*, SDValue> UnusedArgNodeMap;
  98. /// Helper type for DanglingDebugInfoMap.
  99. class DanglingDebugInfo {
  100. const DbgValueInst* DI = nullptr;
  101. DebugLoc dl;
  102. unsigned SDNodeOrder = 0;
  103. public:
  104. DanglingDebugInfo() = default;
  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. /// Helper type for DanglingDebugInfoMap.
  112. typedef std::vector<DanglingDebugInfo> DanglingDebugInfoVector;
  113. /// Keeps track of dbg_values for which we have not yet seen the referent.
  114. /// We defer handling these until we do see it.
  115. MapVector<const Value*, DanglingDebugInfoVector> DanglingDebugInfoMap;
  116. public:
  117. /// Loads are not emitted to the program immediately. We bunch them up and
  118. /// then emit token factor nodes when possible. This allows us to get simple
  119. /// disambiguation between loads without worrying about alias analysis.
  120. SmallVector<SDValue, 8> PendingLoads;
  121. /// State used while lowering a statepoint sequence (gc_statepoint,
  122. /// gc_relocate, and gc_result). See StatepointLowering.hpp/cpp for details.
  123. StatepointLoweringState StatepointLowering;
  124. private:
  125. /// CopyToReg nodes that copy values to virtual registers for export to other
  126. /// blocks need to be emitted before any terminator instruction, but they have
  127. /// no other ordering requirements. We bunch them up and the emit a single
  128. /// tokenfactor for them just before terminator instructions.
  129. SmallVector<SDValue, 8> PendingExports;
  130. /// A unique monotonically increasing number used to order the SDNodes we
  131. /// create.
  132. unsigned SDNodeOrder;
  133. /// Determine the rank by weight of CC in [First,Last]. If CC has more weight
  134. /// than each cluster in the range, its rank is 0.
  135. unsigned caseClusterRank(const SwitchCG::CaseCluster &CC,
  136. SwitchCG::CaseClusterIt First,
  137. SwitchCG::CaseClusterIt Last);
  138. /// Emit comparison and split W into two subtrees.
  139. void splitWorkItem(SwitchCG::SwitchWorkList &WorkList,
  140. const SwitchCG::SwitchWorkListItem &W, Value *Cond,
  141. MachineBasicBlock *SwitchMBB);
  142. /// Lower W.
  143. void lowerWorkItem(SwitchCG::SwitchWorkListItem W, Value *Cond,
  144. MachineBasicBlock *SwitchMBB,
  145. MachineBasicBlock *DefaultMBB);
  146. /// Peel the top probability case if it exceeds the threshold
  147. MachineBasicBlock *
  148. peelDominantCaseCluster(const SwitchInst &SI,
  149. SwitchCG::CaseClusterVector &Clusters,
  150. BranchProbability &PeeledCaseProb);
  151. /// A class which encapsulates all of the information needed to generate a
  152. /// stack protector check and signals to isel via its state being initialized
  153. /// that a stack protector needs to be generated.
  154. ///
  155. /// *NOTE* The following is a high level documentation of SelectionDAG Stack
  156. /// Protector Generation. The reason that it is placed here is for a lack of
  157. /// other good places to stick it.
  158. ///
  159. /// High Level Overview of SelectionDAG Stack Protector Generation:
  160. ///
  161. /// Previously, generation of stack protectors was done exclusively in the
  162. /// pre-SelectionDAG Codegen LLVM IR Pass "Stack Protector". This necessitated
  163. /// splitting basic blocks at the IR level to create the success/failure basic
  164. /// blocks in the tail of the basic block in question. As a result of this,
  165. /// calls that would have qualified for the sibling call optimization were no
  166. /// longer eligible for optimization since said calls were no longer right in
  167. /// the "tail position" (i.e. the immediate predecessor of a ReturnInst
  168. /// instruction).
  169. ///
  170. /// Then it was noticed that since the sibling call optimization causes the
  171. /// callee to reuse the caller's stack, if we could delay the generation of
  172. /// the stack protector check until later in CodeGen after the sibling call
  173. /// decision was made, we get both the tail call optimization and the stack
  174. /// protector check!
  175. ///
  176. /// A few goals in solving this problem were:
  177. ///
  178. /// 1. Preserve the architecture independence of stack protector generation.
  179. ///
  180. /// 2. Preserve the normal IR level stack protector check for platforms like
  181. /// OpenBSD for which we support platform-specific stack protector
  182. /// generation.
  183. ///
  184. /// The main problem that guided the present solution is that one can not
  185. /// solve this problem in an architecture independent manner at the IR level
  186. /// only. This is because:
  187. ///
  188. /// 1. The decision on whether or not to perform a sibling call on certain
  189. /// platforms (for instance i386) requires lower level information
  190. /// related to available registers that can not be known at the IR level.
  191. ///
  192. /// 2. Even if the previous point were not true, the decision on whether to
  193. /// perform a tail call is done in LowerCallTo in SelectionDAG which
  194. /// occurs after the Stack Protector Pass. As a result, one would need to
  195. /// put the relevant callinst into the stack protector check success
  196. /// basic block (where the return inst is placed) and then move it back
  197. /// later at SelectionDAG/MI time before the stack protector check if the
  198. /// tail call optimization failed. The MI level option was nixed
  199. /// immediately since it would require platform-specific pattern
  200. /// matching. The SelectionDAG level option was nixed because
  201. /// SelectionDAG only processes one IR level basic block at a time
  202. /// implying one could not create a DAG Combine to move the callinst.
  203. ///
  204. /// To get around this problem a few things were realized:
  205. ///
  206. /// 1. While one can not handle multiple IR level basic blocks at the
  207. /// SelectionDAG Level, one can generate multiple machine basic blocks
  208. /// for one IR level basic block. This is how we handle bit tests and
  209. /// switches.
  210. ///
  211. /// 2. At the MI level, tail calls are represented via a special return
  212. /// MIInst called "tcreturn". Thus if we know the basic block in which we
  213. /// wish to insert the stack protector check, we get the correct behavior
  214. /// by always inserting the stack protector check right before the return
  215. /// statement. This is a "magical transformation" since no matter where
  216. /// the stack protector check intrinsic is, we always insert the stack
  217. /// protector check code at the end of the BB.
  218. ///
  219. /// Given the aforementioned constraints, the following solution was devised:
  220. ///
  221. /// 1. On platforms that do not support SelectionDAG stack protector check
  222. /// generation, allow for the normal IR level stack protector check
  223. /// generation to continue.
  224. ///
  225. /// 2. On platforms that do support SelectionDAG stack protector check
  226. /// generation:
  227. ///
  228. /// a. Use the IR level stack protector pass to decide if a stack
  229. /// protector is required/which BB we insert the stack protector check
  230. /// in by reusing the logic already therein. If we wish to generate a
  231. /// stack protector check in a basic block, we place a special IR
  232. /// intrinsic called llvm.stackprotectorcheck right before the BB's
  233. /// returninst or if there is a callinst that could potentially be
  234. /// sibling call optimized, before the call inst.
  235. ///
  236. /// b. Then when a BB with said intrinsic is processed, we codegen the BB
  237. /// normally via SelectBasicBlock. In said process, when we visit the
  238. /// stack protector check, we do not actually emit anything into the
  239. /// BB. Instead, we just initialize the stack protector descriptor
  240. /// class (which involves stashing information/creating the success
  241. /// mbbb and the failure mbb if we have not created one for this
  242. /// function yet) and export the guard variable that we are going to
  243. /// compare.
  244. ///
  245. /// c. After we finish selecting the basic block, in FinishBasicBlock if
  246. /// the StackProtectorDescriptor attached to the SelectionDAGBuilder is
  247. /// initialized, we produce the validation code with one of these
  248. /// techniques:
  249. /// 1) with a call to a guard check function
  250. /// 2) with inlined instrumentation
  251. ///
  252. /// 1) We insert a call to the check function before the terminator.
  253. ///
  254. /// 2) We first find a splice point in the parent basic block
  255. /// before the terminator and then splice the terminator of said basic
  256. /// block into the success basic block. Then we code-gen a new tail for
  257. /// the parent basic block consisting of the two loads, the comparison,
  258. /// and finally two branches to the success/failure basic blocks. We
  259. /// conclude by code-gening the failure basic block if we have not
  260. /// code-gened it already (all stack protector checks we generate in
  261. /// the same function, use the same failure basic block).
  262. class StackProtectorDescriptor {
  263. public:
  264. StackProtectorDescriptor() = default;
  265. /// Returns true if all fields of the stack protector descriptor are
  266. /// initialized implying that we should/are ready to emit a stack protector.
  267. bool shouldEmitStackProtector() const {
  268. return ParentMBB && SuccessMBB && FailureMBB;
  269. }
  270. bool shouldEmitFunctionBasedCheckStackProtector() const {
  271. return ParentMBB && !SuccessMBB && !FailureMBB;
  272. }
  273. /// Initialize the stack protector descriptor structure for a new basic
  274. /// block.
  275. void initialize(const BasicBlock *BB, MachineBasicBlock *MBB,
  276. bool FunctionBasedInstrumentation) {
  277. // Make sure we are not initialized yet.
  278. assert(!shouldEmitStackProtector() && "Stack Protector Descriptor is "
  279. "already initialized!");
  280. ParentMBB = MBB;
  281. if (!FunctionBasedInstrumentation) {
  282. SuccessMBB = AddSuccessorMBB(BB, MBB, /* IsLikely */ true);
  283. FailureMBB = AddSuccessorMBB(BB, MBB, /* IsLikely */ false, FailureMBB);
  284. }
  285. }
  286. /// Reset state that changes when we handle different basic blocks.
  287. ///
  288. /// This currently includes:
  289. ///
  290. /// 1. The specific basic block we are generating a
  291. /// stack protector for (ParentMBB).
  292. ///
  293. /// 2. The successor machine basic block that will contain the tail of
  294. /// parent mbb after we create the stack protector check (SuccessMBB). This
  295. /// BB is visited only on stack protector check success.
  296. void resetPerBBState() {
  297. ParentMBB = nullptr;
  298. SuccessMBB = nullptr;
  299. }
  300. /// Reset state that only changes when we switch functions.
  301. ///
  302. /// This currently includes:
  303. ///
  304. /// 1. FailureMBB since we reuse the failure code path for all stack
  305. /// protector checks created in an individual function.
  306. ///
  307. /// 2.The guard variable since the guard variable we are checking against is
  308. /// always the same.
  309. void resetPerFunctionState() {
  310. FailureMBB = nullptr;
  311. }
  312. MachineBasicBlock *getParentMBB() { return ParentMBB; }
  313. MachineBasicBlock *getSuccessMBB() { return SuccessMBB; }
  314. MachineBasicBlock *getFailureMBB() { return FailureMBB; }
  315. private:
  316. /// The basic block for which we are generating the stack protector.
  317. ///
  318. /// As a result of stack protector generation, we will splice the
  319. /// terminators of this basic block into the successor mbb SuccessMBB and
  320. /// replace it with a compare/branch to the successor mbbs
  321. /// SuccessMBB/FailureMBB depending on whether or not the stack protector
  322. /// was violated.
  323. MachineBasicBlock *ParentMBB = nullptr;
  324. /// A basic block visited on stack protector check success that contains the
  325. /// terminators of ParentMBB.
  326. MachineBasicBlock *SuccessMBB = nullptr;
  327. /// This basic block visited on stack protector check failure that will
  328. /// contain a call to __stack_chk_fail().
  329. MachineBasicBlock *FailureMBB = nullptr;
  330. /// Add a successor machine basic block to ParentMBB. If the successor mbb
  331. /// has not been created yet (i.e. if SuccMBB = 0), then the machine basic
  332. /// block will be created. Assign a large weight if IsLikely is true.
  333. MachineBasicBlock *AddSuccessorMBB(const BasicBlock *BB,
  334. MachineBasicBlock *ParentMBB,
  335. bool IsLikely,
  336. MachineBasicBlock *SuccMBB = nullptr);
  337. };
  338. private:
  339. const TargetMachine &TM;
  340. public:
  341. /// Lowest valid SDNodeOrder. The special case 0 is reserved for scheduling
  342. /// nodes without a corresponding SDNode.
  343. static const unsigned LowestSDNodeOrder = 1;
  344. SelectionDAG &DAG;
  345. const DataLayout *DL = nullptr;
  346. AliasAnalysis *AA = nullptr;
  347. const TargetLibraryInfo *LibInfo;
  348. class SDAGSwitchLowering : public SwitchCG::SwitchLowering {
  349. public:
  350. SDAGSwitchLowering(SelectionDAGBuilder *sdb, FunctionLoweringInfo &funcinfo)
  351. : SwitchCG::SwitchLowering(funcinfo), SDB(sdb) {}
  352. virtual void addSuccessorWithProb(
  353. MachineBasicBlock *Src, MachineBasicBlock *Dst,
  354. BranchProbability Prob = BranchProbability::getUnknown()) override {
  355. SDB->addSuccessorWithProb(Src, Dst, Prob);
  356. }
  357. private:
  358. SelectionDAGBuilder *SDB;
  359. };
  360. std::unique_ptr<SDAGSwitchLowering> SL;
  361. /// A StackProtectorDescriptor structure used to communicate stack protector
  362. /// information in between SelectBasicBlock and FinishBasicBlock.
  363. StackProtectorDescriptor SPDescriptor;
  364. // Emit PHI-node-operand constants only once even if used by multiple
  365. // PHI nodes.
  366. DenseMap<const Constant *, unsigned> ConstantsOut;
  367. /// Information about the function as a whole.
  368. FunctionLoweringInfo &FuncInfo;
  369. /// Information about the swifterror values used throughout the function.
  370. SwiftErrorValueTracking &SwiftError;
  371. /// Garbage collection metadata for the function.
  372. GCFunctionInfo *GFI;
  373. /// Map a landing pad to the call site indexes.
  374. DenseMap<MachineBasicBlock *, SmallVector<unsigned, 4>> LPadToCallSiteMap;
  375. /// This is set to true if a call in the current block has been translated as
  376. /// a tail call. In this case, no subsequent DAG nodes should be created.
  377. bool HasTailCall = false;
  378. LLVMContext *Context;
  379. SelectionDAGBuilder(SelectionDAG &dag, FunctionLoweringInfo &funcinfo,
  380. SwiftErrorValueTracking &swifterror, CodeGenOpt::Level ol)
  381. : SDNodeOrder(LowestSDNodeOrder), TM(dag.getTarget()), DAG(dag),
  382. SL(std::make_unique<SDAGSwitchLowering>(this, funcinfo)), FuncInfo(funcinfo),
  383. SwiftError(swifterror) {}
  384. void init(GCFunctionInfo *gfi, AliasAnalysis *AA,
  385. const TargetLibraryInfo *li);
  386. /// Clear out the current SelectionDAG and the associated state and prepare
  387. /// this SelectionDAGBuilder object to be used for a new block. This doesn't
  388. /// clear out information about additional blocks that are needed to complete
  389. /// switch lowering or PHI node updating; that information is cleared out as
  390. /// it is consumed.
  391. void clear();
  392. /// Clear the dangling debug information map. This function is separated from
  393. /// the clear so that debug information that is dangling in a basic block can
  394. /// be properly resolved in a different basic block. This allows the
  395. /// SelectionDAG to resolve dangling debug information attached to PHI nodes.
  396. void clearDanglingDebugInfo();
  397. /// Return the current virtual root of the Selection DAG, flushing any
  398. /// PendingLoad items. This must be done before emitting a store or any other
  399. /// node that may need to be ordered after any prior load instructions.
  400. SDValue getRoot();
  401. /// Similar to getRoot, but instead of flushing all the PendingLoad items,
  402. /// flush all the PendingExports items. It is necessary to do this before
  403. /// emitting a terminator instruction.
  404. SDValue getControlRoot();
  405. SDLoc getCurSDLoc() const {
  406. return SDLoc(CurInst, SDNodeOrder);
  407. }
  408. DebugLoc getCurDebugLoc() const {
  409. return CurInst ? CurInst->getDebugLoc() : DebugLoc();
  410. }
  411. void CopyValueToVirtualRegister(const Value *V, unsigned Reg);
  412. void visit(const Instruction &I);
  413. void visit(unsigned Opcode, const User &I);
  414. /// If there was virtual register allocated for the value V emit CopyFromReg
  415. /// of the specified type Ty. Return empty SDValue() otherwise.
  416. SDValue getCopyFromRegs(const Value *V, Type *Ty);
  417. /// If we have dangling debug info that describes \p Variable, or an
  418. /// overlapping part of variable considering the \p Expr, then this method
  419. /// will drop that debug info as it isn't valid any longer.
  420. void dropDanglingDebugInfo(const DILocalVariable *Variable,
  421. const DIExpression *Expr);
  422. /// If we saw an earlier dbg_value referring to V, generate the debug data
  423. /// structures now that we've seen its definition.
  424. void resolveDanglingDebugInfo(const Value *V, SDValue Val);
  425. /// For the given dangling debuginfo record, perform last-ditch efforts to
  426. /// resolve the debuginfo to something that is represented in this DAG. If
  427. /// this cannot be done, produce an Undef debug value record.
  428. void salvageUnresolvedDbgValue(DanglingDebugInfo &DDI);
  429. /// For a given Value, attempt to create and record a SDDbgValue in the
  430. /// SelectionDAG.
  431. bool handleDebugValue(const Value *V, DILocalVariable *Var,
  432. DIExpression *Expr, DebugLoc CurDL,
  433. DebugLoc InstDL, unsigned Order);
  434. /// Evict any dangling debug information, attempting to salvage it first.
  435. void resolveOrClearDbgInfo();
  436. SDValue getValue(const Value *V);
  437. bool findValue(const Value *V) const;
  438. /// Return the SDNode for the specified IR value if it exists.
  439. SDNode *getNodeForIRValue(const Value *V) {
  440. if (NodeMap.find(V) == NodeMap.end())
  441. return nullptr;
  442. return NodeMap[V].getNode();
  443. }
  444. SDValue getNonRegisterValue(const Value *V);
  445. SDValue getValueImpl(const Value *V);
  446. void setValue(const Value *V, SDValue NewN) {
  447. SDValue &N = NodeMap[V];
  448. assert(!N.getNode() && "Already set a value for this node!");
  449. N = NewN;
  450. }
  451. void setUnusedArgValue(const Value *V, SDValue NewN) {
  452. SDValue &N = UnusedArgNodeMap[V];
  453. assert(!N.getNode() && "Already set a value for this node!");
  454. N = NewN;
  455. }
  456. void FindMergedConditions(const Value *Cond, MachineBasicBlock *TBB,
  457. MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
  458. MachineBasicBlock *SwitchBB,
  459. Instruction::BinaryOps Opc, BranchProbability TProb,
  460. BranchProbability FProb, bool InvertCond);
  461. void EmitBranchForMergedCondition(const Value *Cond, MachineBasicBlock *TBB,
  462. MachineBasicBlock *FBB,
  463. MachineBasicBlock *CurBB,
  464. MachineBasicBlock *SwitchBB,
  465. BranchProbability TProb, BranchProbability FProb,
  466. bool InvertCond);
  467. bool ShouldEmitAsBranches(const std::vector<SwitchCG::CaseBlock> &Cases);
  468. bool isExportableFromCurrentBlock(const Value *V, const BasicBlock *FromBB);
  469. void CopyToExportRegsIfNeeded(const Value *V);
  470. void ExportFromCurrentBlock(const Value *V);
  471. void LowerCallTo(ImmutableCallSite CS, SDValue Callee, bool IsTailCall,
  472. const BasicBlock *EHPadBB = nullptr);
  473. // Lower range metadata from 0 to N to assert zext to an integer of nearest
  474. // floor power of two.
  475. SDValue lowerRangeToAssertZExt(SelectionDAG &DAG, const Instruction &I,
  476. SDValue Op);
  477. void populateCallLoweringInfo(TargetLowering::CallLoweringInfo &CLI,
  478. const CallBase *Call, unsigned ArgIdx,
  479. unsigned NumArgs, SDValue Callee,
  480. Type *ReturnTy, bool IsPatchPoint);
  481. std::pair<SDValue, SDValue>
  482. lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
  483. const BasicBlock *EHPadBB = nullptr);
  484. /// When an MBB was split during scheduling, update the
  485. /// references that need to refer to the last resulting block.
  486. void UpdateSplitBlock(MachineBasicBlock *First, MachineBasicBlock *Last);
  487. /// Describes a gc.statepoint or a gc.statepoint like thing for the purposes
  488. /// of lowering into a STATEPOINT node.
  489. struct StatepointLoweringInfo {
  490. /// Bases[i] is the base pointer for Ptrs[i]. Together they denote the set
  491. /// of gc pointers this STATEPOINT has to relocate.
  492. SmallVector<const Value *, 16> Bases;
  493. SmallVector<const Value *, 16> Ptrs;
  494. /// The set of gc.relocate calls associated with this gc.statepoint.
  495. SmallVector<const GCRelocateInst *, 16> GCRelocates;
  496. /// The full list of gc arguments to the gc.statepoint being lowered.
  497. ArrayRef<const Use> GCArgs;
  498. /// The gc.statepoint instruction.
  499. const Instruction *StatepointInstr = nullptr;
  500. /// The list of gc transition arguments present in the gc.statepoint being
  501. /// lowered.
  502. ArrayRef<const Use> GCTransitionArgs;
  503. /// The ID that the resulting STATEPOINT instruction has to report.
  504. unsigned ID = -1;
  505. /// Information regarding the underlying call instruction.
  506. TargetLowering::CallLoweringInfo CLI;
  507. /// The deoptimization state associated with this gc.statepoint call, if
  508. /// any.
  509. ArrayRef<const Use> DeoptState;
  510. /// Flags associated with the meta arguments being lowered.
  511. uint64_t StatepointFlags = -1;
  512. /// The number of patchable bytes the call needs to get lowered into.
  513. unsigned NumPatchBytes = -1;
  514. /// The exception handling unwind destination, in case this represents an
  515. /// invoke of gc.statepoint.
  516. const BasicBlock *EHPadBB = nullptr;
  517. explicit StatepointLoweringInfo(SelectionDAG &DAG) : CLI(DAG) {}
  518. };
  519. /// Lower \p SLI into a STATEPOINT instruction.
  520. SDValue LowerAsSTATEPOINT(StatepointLoweringInfo &SI);
  521. // This function is responsible for the whole statepoint lowering process.
  522. // It uniformly handles invoke and call statepoints.
  523. void LowerStatepoint(ImmutableStatepoint ISP,
  524. const BasicBlock *EHPadBB = nullptr);
  525. void LowerCallSiteWithDeoptBundle(const CallBase *Call, SDValue Callee,
  526. const BasicBlock *EHPadBB);
  527. void LowerDeoptimizeCall(const CallInst *CI);
  528. void LowerDeoptimizingReturn();
  529. void LowerCallSiteWithDeoptBundleImpl(const CallBase *Call, SDValue Callee,
  530. const BasicBlock *EHPadBB,
  531. bool VarArgDisallowed,
  532. bool ForceVoidReturnTy);
  533. /// Returns the type of FrameIndex and TargetFrameIndex nodes.
  534. MVT getFrameIndexTy() {
  535. return DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout());
  536. }
  537. private:
  538. // Terminator instructions.
  539. void visitRet(const ReturnInst &I);
  540. void visitBr(const BranchInst &I);
  541. void visitSwitch(const SwitchInst &I);
  542. void visitIndirectBr(const IndirectBrInst &I);
  543. void visitUnreachable(const UnreachableInst &I);
  544. void visitCleanupRet(const CleanupReturnInst &I);
  545. void visitCatchSwitch(const CatchSwitchInst &I);
  546. void visitCatchRet(const CatchReturnInst &I);
  547. void visitCatchPad(const CatchPadInst &I);
  548. void visitCleanupPad(const CleanupPadInst &CPI);
  549. BranchProbability getEdgeProbability(const MachineBasicBlock *Src,
  550. const MachineBasicBlock *Dst) const;
  551. void addSuccessorWithProb(
  552. MachineBasicBlock *Src, MachineBasicBlock *Dst,
  553. BranchProbability Prob = BranchProbability::getUnknown());
  554. public:
  555. void visitSwitchCase(SwitchCG::CaseBlock &CB, MachineBasicBlock *SwitchBB);
  556. void visitSPDescriptorParent(StackProtectorDescriptor &SPD,
  557. MachineBasicBlock *ParentBB);
  558. void visitSPDescriptorFailure(StackProtectorDescriptor &SPD);
  559. void visitBitTestHeader(SwitchCG::BitTestBlock &B,
  560. MachineBasicBlock *SwitchBB);
  561. void visitBitTestCase(SwitchCG::BitTestBlock &BB, MachineBasicBlock *NextMBB,
  562. BranchProbability BranchProbToNext, unsigned Reg,
  563. SwitchCG::BitTestCase &B, MachineBasicBlock *SwitchBB);
  564. void visitJumpTable(SwitchCG::JumpTable &JT);
  565. void visitJumpTableHeader(SwitchCG::JumpTable &JT,
  566. SwitchCG::JumpTableHeader &JTH,
  567. MachineBasicBlock *SwitchBB);
  568. private:
  569. // These all get lowered before this pass.
  570. void visitInvoke(const InvokeInst &I);
  571. void visitCallBr(const CallBrInst &I);
  572. void visitResume(const ResumeInst &I);
  573. void visitUnary(const User &I, unsigned Opcode);
  574. void visitFNeg(const User &I) { visitUnary(I, ISD::FNEG); }
  575. void visitBinary(const User &I, unsigned Opcode);
  576. void visitShift(const User &I, unsigned Opcode);
  577. void visitAdd(const User &I) { visitBinary(I, ISD::ADD); }
  578. void visitFAdd(const User &I) { visitBinary(I, ISD::FADD); }
  579. void visitSub(const User &I) { visitBinary(I, ISD::SUB); }
  580. void visitFSub(const User &I);
  581. void visitMul(const User &I) { visitBinary(I, ISD::MUL); }
  582. void visitFMul(const User &I) { visitBinary(I, ISD::FMUL); }
  583. void visitURem(const User &I) { visitBinary(I, ISD::UREM); }
  584. void visitSRem(const User &I) { visitBinary(I, ISD::SREM); }
  585. void visitFRem(const User &I) { visitBinary(I, ISD::FREM); }
  586. void visitUDiv(const User &I) { visitBinary(I, ISD::UDIV); }
  587. void visitSDiv(const User &I);
  588. void visitFDiv(const User &I) { visitBinary(I, ISD::FDIV); }
  589. void visitAnd (const User &I) { visitBinary(I, ISD::AND); }
  590. void visitOr (const User &I) { visitBinary(I, ISD::OR); }
  591. void visitXor (const User &I) { visitBinary(I, ISD::XOR); }
  592. void visitShl (const User &I) { visitShift(I, ISD::SHL); }
  593. void visitLShr(const User &I) { visitShift(I, ISD::SRL); }
  594. void visitAShr(const User &I) { visitShift(I, ISD::SRA); }
  595. void visitICmp(const User &I);
  596. void visitFCmp(const User &I);
  597. // Visit the conversion instructions
  598. void visitTrunc(const User &I);
  599. void visitZExt(const User &I);
  600. void visitSExt(const User &I);
  601. void visitFPTrunc(const User &I);
  602. void visitFPExt(const User &I);
  603. void visitFPToUI(const User &I);
  604. void visitFPToSI(const User &I);
  605. void visitUIToFP(const User &I);
  606. void visitSIToFP(const User &I);
  607. void visitPtrToInt(const User &I);
  608. void visitIntToPtr(const User &I);
  609. void visitBitCast(const User &I);
  610. void visitAddrSpaceCast(const User &I);
  611. void visitExtractElement(const User &I);
  612. void visitInsertElement(const User &I);
  613. void visitShuffleVector(const User &I);
  614. void visitExtractValue(const User &I);
  615. void visitInsertValue(const User &I);
  616. void visitLandingPad(const LandingPadInst &LP);
  617. void visitGetElementPtr(const User &I);
  618. void visitSelect(const User &I);
  619. void visitAlloca(const AllocaInst &I);
  620. void visitLoad(const LoadInst &I);
  621. void visitStore(const StoreInst &I);
  622. void visitMaskedLoad(const CallInst &I, bool IsExpanding = false);
  623. void visitMaskedStore(const CallInst &I, bool IsCompressing = false);
  624. void visitMaskedGather(const CallInst &I);
  625. void visitMaskedScatter(const CallInst &I);
  626. void visitAtomicCmpXchg(const AtomicCmpXchgInst &I);
  627. void visitAtomicRMW(const AtomicRMWInst &I);
  628. void visitFence(const FenceInst &I);
  629. void visitPHI(const PHINode &I);
  630. void visitCall(const CallInst &I);
  631. bool visitMemCmpCall(const CallInst &I);
  632. bool visitMemPCpyCall(const CallInst &I);
  633. bool visitMemChrCall(const CallInst &I);
  634. bool visitStrCpyCall(const CallInst &I, bool isStpcpy);
  635. bool visitStrCmpCall(const CallInst &I);
  636. bool visitStrLenCall(const CallInst &I);
  637. bool visitStrNLenCall(const CallInst &I);
  638. bool visitUnaryFloatCall(const CallInst &I, unsigned Opcode);
  639. bool visitBinaryFloatCall(const CallInst &I, unsigned Opcode);
  640. void visitAtomicLoad(const LoadInst &I);
  641. void visitAtomicStore(const StoreInst &I);
  642. void visitLoadFromSwiftError(const LoadInst &I);
  643. void visitStoreToSwiftError(const StoreInst &I);
  644. void visitInlineAsm(ImmutableCallSite CS);
  645. void visitIntrinsicCall(const CallInst &I, unsigned Intrinsic);
  646. void visitTargetIntrinsic(const CallInst &I, unsigned Intrinsic);
  647. void visitConstrainedFPIntrinsic(const ConstrainedFPIntrinsic &FPI);
  648. void visitVAStart(const CallInst &I);
  649. void visitVAArg(const VAArgInst &I);
  650. void visitVAEnd(const CallInst &I);
  651. void visitVACopy(const CallInst &I);
  652. void visitStackmap(const CallInst &I);
  653. void visitPatchpoint(ImmutableCallSite CS,
  654. const BasicBlock *EHPadBB = nullptr);
  655. // These two are implemented in StatepointLowering.cpp
  656. void visitGCRelocate(const GCRelocateInst &Relocate);
  657. void visitGCResult(const GCResultInst &I);
  658. void visitVectorReduce(const CallInst &I, unsigned Intrinsic);
  659. void visitUserOp1(const Instruction &I) {
  660. llvm_unreachable("UserOp1 should not exist at instruction selection time!");
  661. }
  662. void visitUserOp2(const Instruction &I) {
  663. llvm_unreachable("UserOp2 should not exist at instruction selection time!");
  664. }
  665. void processIntegerCallValue(const Instruction &I,
  666. SDValue Value, bool IsSigned);
  667. void HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB);
  668. void emitInlineAsmError(ImmutableCallSite CS, const Twine &Message);
  669. /// If V is an function argument then create corresponding DBG_VALUE machine
  670. /// instruction for it now. At the end of instruction selection, they will be
  671. /// inserted to the entry BB.
  672. bool EmitFuncArgumentDbgValue(const Value *V, DILocalVariable *Variable,
  673. DIExpression *Expr, DILocation *DL,
  674. bool IsDbgDeclare, const SDValue &N);
  675. /// Return the next block after MBB, or nullptr if there is none.
  676. MachineBasicBlock *NextBlock(MachineBasicBlock *MBB);
  677. /// Update the DAG and DAG builder with the relevant information after
  678. /// a new root node has been created which could be a tail call.
  679. void updateDAGForMaybeTailCall(SDValue MaybeTC);
  680. /// Return the appropriate SDDbgValue based on N.
  681. SDDbgValue *getDbgValue(SDValue N, DILocalVariable *Variable,
  682. DIExpression *Expr, const DebugLoc &dl,
  683. unsigned DbgSDNodeOrder);
  684. /// Lowers CallInst to an external symbol.
  685. void lowerCallToExternalSymbol(const CallInst &I, const char *FunctionName);
  686. };
  687. /// This struct represents the registers (physical or virtual)
  688. /// that a particular set of values is assigned, and the type information about
  689. /// the value. The most common situation is to represent one value at a time,
  690. /// but struct or array values are handled element-wise as multiple values. The
  691. /// splitting of aggregates is performed recursively, so that we never have
  692. /// aggregate-typed registers. The values at this point do not necessarily have
  693. /// legal types, so each value may require one or more registers of some legal
  694. /// type.
  695. ///
  696. struct RegsForValue {
  697. /// The value types of the values, which may not be legal, and
  698. /// may need be promoted or synthesized from one or more registers.
  699. SmallVector<EVT, 4> ValueVTs;
  700. /// The value types of the registers. This is the same size as ValueVTs and it
  701. /// records, for each value, what the type of the assigned register or
  702. /// registers are. (Individual values are never synthesized from more than one
  703. /// type of register.)
  704. ///
  705. /// With virtual registers, the contents of RegVTs is redundant with TLI's
  706. /// getRegisterType member function, however when with physical registers
  707. /// it is necessary to have a separate record of the types.
  708. SmallVector<MVT, 4> RegVTs;
  709. /// This list holds the registers assigned to the values.
  710. /// Each legal or promoted value requires one register, and each
  711. /// expanded value requires multiple registers.
  712. SmallVector<unsigned, 4> Regs;
  713. /// This list holds the number of registers for each value.
  714. SmallVector<unsigned, 4> RegCount;
  715. /// Records if this value needs to be treated in an ABI dependant manner,
  716. /// different to normal type legalization.
  717. Optional<CallingConv::ID> CallConv;
  718. RegsForValue() = default;
  719. RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt, EVT valuevt,
  720. Optional<CallingConv::ID> CC = None);
  721. RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
  722. const DataLayout &DL, unsigned Reg, Type *Ty,
  723. Optional<CallingConv::ID> CC);
  724. bool isABIMangled() const {
  725. return CallConv.hasValue();
  726. }
  727. /// Add the specified values to this one.
  728. void append(const RegsForValue &RHS) {
  729. ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
  730. RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
  731. Regs.append(RHS.Regs.begin(), RHS.Regs.end());
  732. RegCount.push_back(RHS.Regs.size());
  733. }
  734. /// Emit a series of CopyFromReg nodes that copies from this value and returns
  735. /// the result as a ValueVTs value. This uses Chain/Flag as the input and
  736. /// updates them for the output Chain/Flag. If the Flag pointer is NULL, no
  737. /// flag is used.
  738. SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
  739. const SDLoc &dl, SDValue &Chain, SDValue *Flag,
  740. const Value *V = nullptr) const;
  741. /// Emit a series of CopyToReg nodes that copies the specified value into the
  742. /// registers specified by this object. This uses Chain/Flag as the input and
  743. /// updates them for the output Chain/Flag. If the Flag pointer is nullptr, no
  744. /// flag is used. If V is not nullptr, then it is used in printing better
  745. /// diagnostic messages on error.
  746. void getCopyToRegs(SDValue Val, SelectionDAG &DAG, const SDLoc &dl,
  747. SDValue &Chain, SDValue *Flag, const Value *V = nullptr,
  748. ISD::NodeType PreferredExtendType = ISD::ANY_EXTEND) const;
  749. /// Add this value to the specified inlineasm node operand list. This adds the
  750. /// code marker, matching input operand index (if applicable), and includes
  751. /// the number of values added into it.
  752. void AddInlineAsmOperands(unsigned Code, bool HasMatching,
  753. unsigned MatchingIdx, const SDLoc &dl,
  754. SelectionDAG &DAG, std::vector<SDValue> &Ops) const;
  755. /// Check if the total RegCount is greater than one.
  756. bool occupiesMultipleRegs() const {
  757. return std::accumulate(RegCount.begin(), RegCount.end(), 0) > 1;
  758. }
  759. /// Return a list of registers and their sizes.
  760. SmallVector<std::pair<unsigned, unsigned>, 4> getRegsAndSizes() const;
  761. };
  762. } // end namespace llvm
  763. #endif // LLVM_LIB_CODEGEN_SELECTIONDAG_SELECTIONDAGBUILDER_H