xref: /freebsd/contrib/llvm-project/llvm/include/llvm/CodeGen/SelectionDAG.h (revision 700637cbb5e582861067a11aaca4d053546871d2)
1 //===- llvm/CodeGen/SelectionDAG.h - InstSelection DAG ----------*- 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 file declares the SelectionDAG class, and transitively defines the
10 // SDNode class and subclasses.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CODEGEN_SELECTIONDAG_H
15 #define LLVM_CODEGEN_SELECTIONDAG_H
16 
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/ilist.h"
24 #include "llvm/ADT/iterator.h"
25 #include "llvm/ADT/iterator_range.h"
26 #include "llvm/CodeGen/DAGCombine.h"
27 #include "llvm/CodeGen/ISDOpcodes.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineMemOperand.h"
30 #include "llvm/CodeGen/MachinePassManager.h"
31 #include "llvm/CodeGen/SelectionDAGNodes.h"
32 #include "llvm/CodeGen/ValueTypes.h"
33 #include "llvm/CodeGenTypes/MachineValueType.h"
34 #include "llvm/IR/ConstantRange.h"
35 #include "llvm/IR/DebugLoc.h"
36 #include "llvm/IR/Metadata.h"
37 #include "llvm/IR/RuntimeLibcalls.h"
38 #include "llvm/Support/Allocator.h"
39 #include "llvm/Support/ArrayRecycler.h"
40 #include "llvm/Support/CodeGen.h"
41 #include "llvm/Support/Compiler.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/RecyclingAllocator.h"
44 #include <cassert>
45 #include <cstdint>
46 #include <functional>
47 #include <map>
48 #include <set>
49 #include <string>
50 #include <tuple>
51 #include <utility>
52 #include <vector>
53 
54 namespace llvm {
55 
56 class DIExpression;
57 class DILabel;
58 class DIVariable;
59 class Function;
60 class Pass;
61 class Type;
62 template <class GraphType> struct GraphTraits;
63 template <typename T, unsigned int N> class SmallSetVector;
64 template <typename T, typename Enable> struct FoldingSetTrait;
65 class BatchAAResults;
66 class BlockAddress;
67 class BlockFrequencyInfo;
68 class Constant;
69 class ConstantFP;
70 class ConstantInt;
71 class DataLayout;
72 struct fltSemantics;
73 class FunctionLoweringInfo;
74 class FunctionVarLocs;
75 class GlobalValue;
76 struct KnownBits;
77 class LLVMContext;
78 class MachineBasicBlock;
79 class MachineConstantPoolValue;
80 class MachineModuleInfo;
81 class MCSymbol;
82 class OptimizationRemarkEmitter;
83 class ProfileSummaryInfo;
84 class SDDbgValue;
85 class SDDbgOperand;
86 class SDDbgLabel;
87 class SelectionDAG;
88 class SelectionDAGTargetInfo;
89 class TargetLibraryInfo;
90 class TargetLowering;
91 class TargetMachine;
92 class TargetSubtargetInfo;
93 class Value;
94 
95 template <typename T> class GenericSSAContext;
96 using SSAContext = GenericSSAContext<Function>;
97 template <typename T> class GenericUniformityInfo;
98 using UniformityInfo = GenericUniformityInfo<SSAContext>;
99 
100 class SDVTListNode : public FoldingSetNode {
101   friend struct FoldingSetTrait<SDVTListNode>;
102 
103   /// A reference to an Interned FoldingSetNodeID for this node.
104   /// The Allocator in SelectionDAG holds the data.
105   /// SDVTList contains all types which are frequently accessed in SelectionDAG.
106   /// The size of this list is not expected to be big so it won't introduce
107   /// a memory penalty.
108   FoldingSetNodeIDRef FastID;
109   const EVT *VTs;
110   unsigned int NumVTs;
111   /// The hash value for SDVTList is fixed, so cache it to avoid
112   /// hash calculation.
113   unsigned HashValue;
114 
115 public:
116   SDVTListNode(const FoldingSetNodeIDRef ID, const EVT *VT, unsigned int Num) :
117       FastID(ID), VTs(VT), NumVTs(Num) {
118     HashValue = ID.ComputeHash();
119   }
120 
121   SDVTList getSDVTList() {
122     SDVTList result = {VTs, NumVTs};
123     return result;
124   }
125 };
126 
127 /// Specialize FoldingSetTrait for SDVTListNode
128 /// to avoid computing temp FoldingSetNodeID and hash value.
129 template<> struct FoldingSetTrait<SDVTListNode> : DefaultFoldingSetTrait<SDVTListNode> {
130   static void Profile(const SDVTListNode &X, FoldingSetNodeID& ID) {
131     ID = X.FastID;
132   }
133 
134   static bool Equals(const SDVTListNode &X, const FoldingSetNodeID &ID,
135                      unsigned IDHash, FoldingSetNodeID &TempID) {
136     if (X.HashValue != IDHash)
137       return false;
138     return ID == X.FastID;
139   }
140 
141   static unsigned ComputeHash(const SDVTListNode &X, FoldingSetNodeID &TempID) {
142     return X.HashValue;
143   }
144 };
145 
146 template <> struct ilist_alloc_traits<SDNode> {
147   static void deleteNode(SDNode *) {
148     llvm_unreachable("ilist_traits<SDNode> shouldn't see a deleteNode call!");
149   }
150 };
151 
152 /// Keeps track of dbg_value information through SDISel.  We do
153 /// not build SDNodes for these so as not to perturb the generated code;
154 /// instead the info is kept off to the side in this structure. Each SDNode may
155 /// have one or more associated dbg_value entries. This information is kept in
156 /// DbgValMap.
157 /// Byval parameters are handled separately because they don't use alloca's,
158 /// which busts the normal mechanism.  There is good reason for handling all
159 /// parameters separately:  they may not have code generated for them, they
160 /// should always go at the beginning of the function regardless of other code
161 /// motion, and debug info for them is potentially useful even if the parameter
162 /// is unused.  Right now only byval parameters are handled separately.
163 class SDDbgInfo {
164   BumpPtrAllocator Alloc;
165   SmallVector<SDDbgValue*, 32> DbgValues;
166   SmallVector<SDDbgValue*, 32> ByvalParmDbgValues;
167   SmallVector<SDDbgLabel*, 4> DbgLabels;
168   using DbgValMapType = DenseMap<const SDNode *, SmallVector<SDDbgValue *, 2>>;
169   DbgValMapType DbgValMap;
170 
171 public:
172   SDDbgInfo() = default;
173   SDDbgInfo(const SDDbgInfo &) = delete;
174   SDDbgInfo &operator=(const SDDbgInfo &) = delete;
175 
176   LLVM_ABI void add(SDDbgValue *V, bool isParameter);
177 
178   void add(SDDbgLabel *L) { DbgLabels.push_back(L); }
179 
180   /// Invalidate all DbgValues attached to the node and remove
181   /// it from the Node-to-DbgValues map.
182   LLVM_ABI void erase(const SDNode *Node);
183 
184   void clear() {
185     DbgValMap.clear();
186     DbgValues.clear();
187     ByvalParmDbgValues.clear();
188     DbgLabels.clear();
189     Alloc.Reset();
190   }
191 
192   BumpPtrAllocator &getAlloc() { return Alloc; }
193 
194   bool empty() const {
195     return DbgValues.empty() && ByvalParmDbgValues.empty() && DbgLabels.empty();
196   }
197 
198   ArrayRef<SDDbgValue*> getSDDbgValues(const SDNode *Node) const {
199     auto I = DbgValMap.find(Node);
200     if (I != DbgValMap.end())
201       return I->second;
202     return ArrayRef<SDDbgValue*>();
203   }
204 
205   using DbgIterator = SmallVectorImpl<SDDbgValue*>::iterator;
206   using DbgLabelIterator = SmallVectorImpl<SDDbgLabel*>::iterator;
207 
208   DbgIterator DbgBegin() { return DbgValues.begin(); }
209   DbgIterator DbgEnd()   { return DbgValues.end(); }
210   DbgIterator ByvalParmDbgBegin() { return ByvalParmDbgValues.begin(); }
211   DbgIterator ByvalParmDbgEnd()   { return ByvalParmDbgValues.end(); }
212   DbgLabelIterator DbgLabelBegin() { return DbgLabels.begin(); }
213   DbgLabelIterator DbgLabelEnd()   { return DbgLabels.end(); }
214 };
215 
216 LLVM_ABI void checkForCycles(const SelectionDAG *DAG, bool force = false);
217 
218 /// This is used to represent a portion of an LLVM function in a low-level
219 /// Data Dependence DAG representation suitable for instruction selection.
220 /// This DAG is constructed as the first step of instruction selection in order
221 /// to allow implementation of machine specific optimizations
222 /// and code simplifications.
223 ///
224 /// The representation used by the SelectionDAG is a target-independent
225 /// representation, which has some similarities to the GCC RTL representation,
226 /// but is significantly more simple, powerful, and is a graph form instead of a
227 /// linear form.
228 ///
229 class SelectionDAG {
230   const TargetMachine &TM;
231   const SelectionDAGTargetInfo *TSI = nullptr;
232   const TargetLowering *TLI = nullptr;
233   const TargetLibraryInfo *LibInfo = nullptr;
234   const FunctionVarLocs *FnVarLocs = nullptr;
235   MachineFunction *MF;
236   MachineFunctionAnalysisManager *MFAM = nullptr;
237   Pass *SDAGISelPass = nullptr;
238   LLVMContext *Context;
239   CodeGenOptLevel OptLevel;
240 
241   bool DivergentTarget = false;
242 
243   UniformityInfo *UA = nullptr;
244   FunctionLoweringInfo * FLI = nullptr;
245 
246   /// The function-level optimization remark emitter.  Used to emit remarks
247   /// whenever manipulating the DAG.
248   OptimizationRemarkEmitter *ORE;
249 
250   ProfileSummaryInfo *PSI = nullptr;
251   BlockFrequencyInfo *BFI = nullptr;
252   MachineModuleInfo *MMI = nullptr;
253 
254   /// Extended EVTs used for single value VTLists.
255   std::set<EVT, EVT::compareRawBits> EVTs;
256 
257   /// List of non-single value types.
258   FoldingSet<SDVTListNode> VTListMap;
259 
260   /// Pool allocation for misc. objects that are created once per SelectionDAG.
261   BumpPtrAllocator Allocator;
262 
263   /// The starting token.
264   SDNode EntryNode;
265 
266   /// The root of the entire DAG.
267   SDValue Root;
268 
269   /// A linked list of nodes in the current DAG.
270   ilist<SDNode> AllNodes;
271 
272   /// The AllocatorType for allocating SDNodes. We use
273   /// pool allocation with recycling.
274   using NodeAllocatorType = RecyclingAllocator<BumpPtrAllocator, SDNode,
275                                                sizeof(LargestSDNode),
276                                                alignof(MostAlignedSDNode)>;
277 
278   /// Pool allocation for nodes.
279   NodeAllocatorType NodeAllocator;
280 
281   /// This structure is used to memoize nodes, automatically performing
282   /// CSE with existing nodes when a duplicate is requested.
283   FoldingSet<SDNode> CSEMap;
284 
285   /// Pool allocation for machine-opcode SDNode operands.
286   BumpPtrAllocator OperandAllocator;
287   ArrayRecycler<SDUse> OperandRecycler;
288 
289   /// Tracks dbg_value and dbg_label information through SDISel.
290   SDDbgInfo *DbgInfo;
291 
292   using CallSiteInfo = MachineFunction::CallSiteInfo;
293   using CalledGlobalInfo = MachineFunction::CalledGlobalInfo;
294 
295   struct NodeExtraInfo {
296     CallSiteInfo CSInfo;
297     MDNode *HeapAllocSite = nullptr;
298     MDNode *PCSections = nullptr;
299     MDNode *MMRA = nullptr;
300     CalledGlobalInfo CalledGlobal{};
301     bool NoMerge = false;
302   };
303   /// Out-of-line extra information for SDNodes.
304   DenseMap<const SDNode *, NodeExtraInfo> SDEI;
305 
306   /// PersistentId counter to be used when inserting the next
307   /// SDNode to this SelectionDAG. We do not place that under
308   /// `#if LLVM_ENABLE_ABI_BREAKING_CHECKS` intentionally because
309   /// it adds unneeded complexity without noticeable
310   /// benefits (see discussion with @thakis in D120714).
311   uint16_t NextPersistentId = 0;
312 
313 public:
314   /// Clients of various APIs that cause global effects on
315   /// the DAG can optionally implement this interface.  This allows the clients
316   /// to handle the various sorts of updates that happen.
317   ///
318   /// A DAGUpdateListener automatically registers itself with DAG when it is
319   /// constructed, and removes itself when destroyed in RAII fashion.
320   struct LLVM_ABI DAGUpdateListener {
321     DAGUpdateListener *const Next;
322     SelectionDAG &DAG;
323 
324     explicit DAGUpdateListener(SelectionDAG &D)
325       : Next(D.UpdateListeners), DAG(D) {
326       DAG.UpdateListeners = this;
327     }
328 
329     virtual ~DAGUpdateListener() {
330       assert(DAG.UpdateListeners == this &&
331              "DAGUpdateListeners must be destroyed in LIFO order");
332       DAG.UpdateListeners = Next;
333     }
334 
335     /// The node N that was deleted and, if E is not null, an
336     /// equivalent node E that replaced it.
337     virtual void NodeDeleted(SDNode *N, SDNode *E);
338 
339     /// The node N that was updated.
340     virtual void NodeUpdated(SDNode *N);
341 
342     /// The node N that was inserted.
343     virtual void NodeInserted(SDNode *N);
344   };
345 
346   struct LLVM_ABI DAGNodeDeletedListener : public DAGUpdateListener {
347     std::function<void(SDNode *, SDNode *)> Callback;
348 
349     DAGNodeDeletedListener(SelectionDAG &DAG,
350                            std::function<void(SDNode *, SDNode *)> Callback)
351         : DAGUpdateListener(DAG), Callback(std::move(Callback)) {}
352 
353     void NodeDeleted(SDNode *N, SDNode *E) override { Callback(N, E); }
354 
355    private:
356     virtual void anchor();
357   };
358 
359   struct LLVM_ABI DAGNodeInsertedListener : public DAGUpdateListener {
360     std::function<void(SDNode *)> Callback;
361 
362     DAGNodeInsertedListener(SelectionDAG &DAG,
363                             std::function<void(SDNode *)> Callback)
364         : DAGUpdateListener(DAG), Callback(std::move(Callback)) {}
365 
366     void NodeInserted(SDNode *N) override { Callback(N); }
367 
368   private:
369     virtual void anchor();
370   };
371 
372   /// Help to insert SDNodeFlags automatically in transforming. Use
373   /// RAII to save and resume flags in current scope.
374   class FlagInserter {
375     SelectionDAG &DAG;
376     SDNodeFlags Flags;
377     FlagInserter *LastInserter;
378 
379   public:
380     FlagInserter(SelectionDAG &SDAG, SDNodeFlags Flags)
381         : DAG(SDAG), Flags(Flags),
382           LastInserter(SDAG.getFlagInserter()) {
383       SDAG.setFlagInserter(this);
384     }
385     FlagInserter(SelectionDAG &SDAG, SDNode *N)
386         : FlagInserter(SDAG, N->getFlags()) {}
387 
388     FlagInserter(const FlagInserter &) = delete;
389     FlagInserter &operator=(const FlagInserter &) = delete;
390     ~FlagInserter() { DAG.setFlagInserter(LastInserter); }
391 
392     SDNodeFlags getFlags() const { return Flags; }
393   };
394 
395   /// When true, additional steps are taken to
396   /// ensure that getConstant() and similar functions return DAG nodes that
397   /// have legal types. This is important after type legalization since
398   /// any illegally typed nodes generated after this point will not experience
399   /// type legalization.
400   bool NewNodesMustHaveLegalTypes = false;
401 
402 private:
403   /// DAGUpdateListener is a friend so it can manipulate the listener stack.
404   friend struct DAGUpdateListener;
405 
406   /// Linked list of registered DAGUpdateListener instances.
407   /// This stack is maintained by DAGUpdateListener RAII.
408   DAGUpdateListener *UpdateListeners = nullptr;
409 
410   /// Implementation of setSubgraphColor.
411   /// Return whether we had to truncate the search.
412   bool setSubgraphColorHelper(SDNode *N, const char *Color,
413                               DenseSet<SDNode *> &visited,
414                               int level, bool &printed);
415 
416   template <typename SDNodeT, typename... ArgTypes>
417   SDNodeT *newSDNode(ArgTypes &&... Args) {
418     return new (NodeAllocator.template Allocate<SDNodeT>())
419         SDNodeT(std::forward<ArgTypes>(Args)...);
420   }
421 
422   /// Build a synthetic SDNodeT with the given args and extract its subclass
423   /// data as an integer (e.g. for use in a folding set).
424   ///
425   /// The args to this function are the same as the args to SDNodeT's
426   /// constructor, except the second arg (assumed to be a const DebugLoc&) is
427   /// omitted.
428   template <typename SDNodeT, typename... ArgTypes>
429   static uint16_t getSyntheticNodeSubclassData(unsigned IROrder,
430                                                ArgTypes &&... Args) {
431     // The compiler can reduce this expression to a constant iff we pass an
432     // empty DebugLoc.  Thankfully, the debug location doesn't have any bearing
433     // on the subclass data.
434     return SDNodeT(IROrder, DebugLoc(), std::forward<ArgTypes>(Args)...)
435         .getRawSubclassData();
436   }
437 
438   template <typename SDNodeTy>
439   static uint16_t getSyntheticNodeSubclassData(unsigned Opc, unsigned Order,
440                                                 SDVTList VTs, EVT MemoryVT,
441                                                 MachineMemOperand *MMO) {
442     return SDNodeTy(Opc, Order, DebugLoc(), VTs, MemoryVT, MMO)
443          .getRawSubclassData();
444   }
445 
446   void createOperands(SDNode *Node, ArrayRef<SDValue> Vals);
447 
448   void removeOperands(SDNode *Node) {
449     if (!Node->OperandList)
450       return;
451     OperandRecycler.deallocate(
452         ArrayRecycler<SDUse>::Capacity::get(Node->NumOperands),
453         Node->OperandList);
454     Node->NumOperands = 0;
455     Node->OperandList = nullptr;
456   }
457   void CreateTopologicalOrder(std::vector<SDNode*>& Order);
458 
459 public:
460   // Maximum depth for recursive analysis such as computeKnownBits, etc.
461   static constexpr unsigned MaxRecursionDepth = 6;
462 
463   // Returns the maximum steps for SDNode->hasPredecessor() like searches.
464   LLVM_ABI static unsigned getHasPredecessorMaxSteps();
465 
466   LLVM_ABI explicit SelectionDAG(const TargetMachine &TM, CodeGenOptLevel);
467   SelectionDAG(const SelectionDAG &) = delete;
468   SelectionDAG &operator=(const SelectionDAG &) = delete;
469   LLVM_ABI ~SelectionDAG();
470 
471   /// Prepare this SelectionDAG to process code in the given MachineFunction.
472   LLVM_ABI void init(MachineFunction &NewMF, OptimizationRemarkEmitter &NewORE,
473                      Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
474                      UniformityInfo *UA, ProfileSummaryInfo *PSIin,
475                      BlockFrequencyInfo *BFIin, MachineModuleInfo &MMI,
476                      FunctionVarLocs const *FnVarLocs, bool HasDivergency);
477 
478   void init(MachineFunction &NewMF, OptimizationRemarkEmitter &NewORE,
479             MachineFunctionAnalysisManager &AM,
480             const TargetLibraryInfo *LibraryInfo, UniformityInfo *UA,
481             ProfileSummaryInfo *PSIin, BlockFrequencyInfo *BFIin,
482             MachineModuleInfo &MMI, FunctionVarLocs const *FnVarLocs,
483             bool HasDivergency) {
484     init(NewMF, NewORE, nullptr, LibraryInfo, UA, PSIin, BFIin, MMI, FnVarLocs,
485          HasDivergency);
486     MFAM = &AM;
487   }
488 
489   void setFunctionLoweringInfo(FunctionLoweringInfo * FuncInfo) {
490     FLI = FuncInfo;
491   }
492 
493   /// Clear state and free memory necessary to make this
494   /// SelectionDAG ready to process a new block.
495   LLVM_ABI void clear();
496 
497   MachineFunction &getMachineFunction() const { return *MF; }
498   const Pass *getPass() const { return SDAGISelPass; }
499   MachineFunctionAnalysisManager *getMFAM() { return MFAM; }
500 
501   CodeGenOptLevel getOptLevel() const { return OptLevel; }
502   const DataLayout &getDataLayout() const { return MF->getDataLayout(); }
503   const TargetMachine &getTarget() const { return TM; }
504   const TargetSubtargetInfo &getSubtarget() const { return MF->getSubtarget(); }
505   template <typename STC> const STC &getSubtarget() const {
506     return MF->getSubtarget<STC>();
507   }
508   const TargetLowering &getTargetLoweringInfo() const { return *TLI; }
509   const TargetLibraryInfo &getLibInfo() const { return *LibInfo; }
510   const SelectionDAGTargetInfo &getSelectionDAGInfo() const { return *TSI; }
511   const UniformityInfo *getUniformityInfo() const { return UA; }
512   /// Returns the result of the AssignmentTrackingAnalysis pass if it's
513   /// available, otherwise return nullptr.
514   const FunctionVarLocs *getFunctionVarLocs() const { return FnVarLocs; }
515   LLVMContext *getContext() const { return Context; }
516   OptimizationRemarkEmitter &getORE() const { return *ORE; }
517   ProfileSummaryInfo *getPSI() const { return PSI; }
518   BlockFrequencyInfo *getBFI() const { return BFI; }
519   MachineModuleInfo *getMMI() const { return MMI; }
520 
521   FlagInserter *getFlagInserter() { return Inserter; }
522   void setFlagInserter(FlagInserter *FI) { Inserter = FI; }
523 
524   /// Just dump dot graph to a user-provided path and title.
525   /// This doesn't open the dot viewer program and
526   /// helps visualization when outside debugging session.
527   /// FileName expects absolute path. If provided
528   /// without any path separators then the file
529   /// will be created in the current directory.
530   /// Error will be emitted if the path is insane.
531 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
532   LLVM_DUMP_METHOD void dumpDotGraph(const Twine &FileName, const Twine &Title);
533 #endif
534 
535   /// Pop up a GraphViz/gv window with the DAG rendered using 'dot'.
536   LLVM_ABI void viewGraph(const std::string &Title);
537   LLVM_ABI void viewGraph();
538 
539 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
540   std::map<const SDNode *, std::string> NodeGraphAttrs;
541 #endif
542 
543   /// Clear all previously defined node graph attributes.
544   /// Intended to be used from a debugging tool (eg. gdb).
545   LLVM_ABI void clearGraphAttrs();
546 
547   /// Set graph attributes for a node. (eg. "color=red".)
548   LLVM_ABI void setGraphAttrs(const SDNode *N, const char *Attrs);
549 
550   /// Get graph attributes for a node. (eg. "color=red".)
551   /// Used from getNodeAttributes.
552   LLVM_ABI std::string getGraphAttrs(const SDNode *N) const;
553 
554   /// Convenience for setting node color attribute.
555   LLVM_ABI void setGraphColor(const SDNode *N, const char *Color);
556 
557   /// Convenience for setting subgraph color attribute.
558   LLVM_ABI void setSubgraphColor(SDNode *N, const char *Color);
559 
560   using allnodes_const_iterator = ilist<SDNode>::const_iterator;
561 
562   allnodes_const_iterator allnodes_begin() const { return AllNodes.begin(); }
563   allnodes_const_iterator allnodes_end() const { return AllNodes.end(); }
564 
565   using allnodes_iterator = ilist<SDNode>::iterator;
566 
567   allnodes_iterator allnodes_begin() { return AllNodes.begin(); }
568   allnodes_iterator allnodes_end() { return AllNodes.end(); }
569 
570   ilist<SDNode>::size_type allnodes_size() const {
571     return AllNodes.size();
572   }
573 
574   iterator_range<allnodes_iterator> allnodes() {
575     return make_range(allnodes_begin(), allnodes_end());
576   }
577   iterator_range<allnodes_const_iterator> allnodes() const {
578     return make_range(allnodes_begin(), allnodes_end());
579   }
580 
581   /// Return the root tag of the SelectionDAG.
582   const SDValue &getRoot() const { return Root; }
583 
584   /// Return the token chain corresponding to the entry of the function.
585   SDValue getEntryNode() const {
586     return SDValue(const_cast<SDNode *>(&EntryNode), 0);
587   }
588 
589   /// Set the current root tag of the SelectionDAG.
590   ///
591   const SDValue &setRoot(SDValue N) {
592     assert((!N.getNode() || N.getValueType() == MVT::Other) &&
593            "DAG root value is not a chain!");
594     if (N.getNode())
595       checkForCycles(N.getNode(), this);
596     Root = N;
597     if (N.getNode())
598       checkForCycles(this);
599     return Root;
600   }
601 
602 #if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
603   void VerifyDAGDivergence();
604 #endif
605 
606   /// This iterates over the nodes in the SelectionDAG, folding
607   /// certain types of nodes together, or eliminating superfluous nodes.  The
608   /// Level argument controls whether Combine is allowed to produce nodes and
609   /// types that are illegal on the target.
610   LLVM_ABI void Combine(CombineLevel Level, BatchAAResults *BatchAA,
611                         CodeGenOptLevel OptLevel);
612 
613   /// This transforms the SelectionDAG into a SelectionDAG that
614   /// only uses types natively supported by the target.
615   /// Returns "true" if it made any changes.
616   ///
617   /// Note that this is an involved process that may invalidate pointers into
618   /// the graph.
619   LLVM_ABI bool LegalizeTypes();
620 
621   /// This transforms the SelectionDAG into a SelectionDAG that is
622   /// compatible with the target instruction selector, as indicated by the
623   /// TargetLowering object.
624   ///
625   /// Note that this is an involved process that may invalidate pointers into
626   /// the graph.
627   LLVM_ABI void Legalize();
628 
629   /// Transforms a SelectionDAG node and any operands to it into a node
630   /// that is compatible with the target instruction selector, as indicated by
631   /// the TargetLowering object.
632   ///
633   /// \returns true if \c N is a valid, legal node after calling this.
634   ///
635   /// This essentially runs a single recursive walk of the \c Legalize process
636   /// over the given node (and its operands). This can be used to incrementally
637   /// legalize the DAG. All of the nodes which are directly replaced,
638   /// potentially including N, are added to the output parameter \c
639   /// UpdatedNodes so that the delta to the DAG can be understood by the
640   /// caller.
641   ///
642   /// When this returns false, N has been legalized in a way that make the
643   /// pointer passed in no longer valid. It may have even been deleted from the
644   /// DAG, and so it shouldn't be used further. When this returns true, the
645   /// N passed in is a legal node, and can be immediately processed as such.
646   /// This may still have done some work on the DAG, and will still populate
647   /// UpdatedNodes with any new nodes replacing those originally in the DAG.
648   LLVM_ABI bool LegalizeOp(SDNode *N,
649                            SmallSetVector<SDNode *, 16> &UpdatedNodes);
650 
651   /// This transforms the SelectionDAG into a SelectionDAG
652   /// that only uses vector math operations supported by the target.  This is
653   /// necessary as a separate step from Legalize because unrolling a vector
654   /// operation can introduce illegal types, which requires running
655   /// LegalizeTypes again.
656   ///
657   /// This returns true if it made any changes; in that case, LegalizeTypes
658   /// is called again before Legalize.
659   ///
660   /// Note that this is an involved process that may invalidate pointers into
661   /// the graph.
662   LLVM_ABI bool LegalizeVectors();
663 
664   /// This method deletes all unreachable nodes in the SelectionDAG.
665   LLVM_ABI void RemoveDeadNodes();
666 
667   /// Remove the specified node from the system.  This node must
668   /// have no referrers.
669   LLVM_ABI void DeleteNode(SDNode *N);
670 
671   /// Return an SDVTList that represents the list of values specified.
672   LLVM_ABI SDVTList getVTList(EVT VT);
673   LLVM_ABI SDVTList getVTList(EVT VT1, EVT VT2);
674   LLVM_ABI SDVTList getVTList(EVT VT1, EVT VT2, EVT VT3);
675   LLVM_ABI SDVTList getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4);
676   LLVM_ABI SDVTList getVTList(ArrayRef<EVT> VTs);
677 
678   //===--------------------------------------------------------------------===//
679   // Node creation methods.
680 
681   /// Create a ConstantSDNode wrapping a constant value.
682   /// If VT is a vector type, the constant is splatted into a BUILD_VECTOR.
683   ///
684   /// If only legal types can be produced, this does the necessary
685   /// transformations (e.g., if the vector element type is illegal).
686   /// @{
687   LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
688                                bool isTarget = false, bool isOpaque = false);
689   LLVM_ABI SDValue getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
690                                bool isTarget = false, bool isOpaque = false);
691 
692   LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT,
693                                      bool isTarget = false,
694                                      bool isOpaque = false);
695 
696   LLVM_ABI SDValue getAllOnesConstant(const SDLoc &DL, EVT VT,
697                                       bool IsTarget = false,
698                                       bool IsOpaque = false);
699 
700   LLVM_ABI SDValue getConstant(const ConstantInt &Val, const SDLoc &DL, EVT VT,
701                                bool isTarget = false, bool isOpaque = false);
702   LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL,
703                                      bool isTarget = false);
704   LLVM_ABI SDValue getShiftAmountConstant(uint64_t Val, EVT VT,
705                                           const SDLoc &DL);
706   LLVM_ABI SDValue getShiftAmountConstant(const APInt &Val, EVT VT,
707                                           const SDLoc &DL);
708   LLVM_ABI SDValue getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
709                                         bool isTarget = false);
710 
711   SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT,
712                             bool isOpaque = false) {
713     return getConstant(Val, DL, VT, true, isOpaque);
714   }
715   SDValue getTargetConstant(const APInt &Val, const SDLoc &DL, EVT VT,
716                             bool isOpaque = false) {
717     return getConstant(Val, DL, VT, true, isOpaque);
718   }
719   SDValue getTargetConstant(const ConstantInt &Val, const SDLoc &DL, EVT VT,
720                             bool isOpaque = false) {
721     return getConstant(Val, DL, VT, true, isOpaque);
722   }
723   SDValue getSignedTargetConstant(int64_t Val, const SDLoc &DL, EVT VT,
724                                   bool isOpaque = false) {
725     return getSignedConstant(Val, DL, VT, true, isOpaque);
726   }
727 
728   /// Create a true or false constant of type \p VT using the target's
729   /// BooleanContent for type \p OpVT.
730   LLVM_ABI SDValue getBoolConstant(bool V, const SDLoc &DL, EVT VT, EVT OpVT);
731   /// @}
732 
733   /// Create a ConstantFPSDNode wrapping a constant value.
734   /// If VT is a vector type, the constant is splatted into a BUILD_VECTOR.
735   ///
736   /// If only legal types can be produced, this does the necessary
737   /// transformations (e.g., if the vector element type is illegal).
738   /// The forms that take a double should only be used for simple constants
739   /// that can be exactly represented in VT.  No checks are made.
740   /// @{
741   LLVM_ABI SDValue getConstantFP(double Val, const SDLoc &DL, EVT VT,
742                                  bool isTarget = false);
743   LLVM_ABI SDValue getConstantFP(const APFloat &Val, const SDLoc &DL, EVT VT,
744                                  bool isTarget = false);
745   LLVM_ABI SDValue getConstantFP(const ConstantFP &V, const SDLoc &DL, EVT VT,
746                                  bool isTarget = false);
747   SDValue getTargetConstantFP(double Val, const SDLoc &DL, EVT VT) {
748     return getConstantFP(Val, DL, VT, true);
749   }
750   SDValue getTargetConstantFP(const APFloat &Val, const SDLoc &DL, EVT VT) {
751     return getConstantFP(Val, DL, VT, true);
752   }
753   SDValue getTargetConstantFP(const ConstantFP &Val, const SDLoc &DL, EVT VT) {
754     return getConstantFP(Val, DL, VT, true);
755   }
756   /// @}
757 
758   LLVM_ABI SDValue getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
759                                     EVT VT, int64_t offset = 0,
760                                     bool isTargetGA = false,
761                                     unsigned TargetFlags = 0);
762   SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT,
763                                  int64_t offset = 0, unsigned TargetFlags = 0) {
764     return getGlobalAddress(GV, DL, VT, offset, true, TargetFlags);
765   }
766   LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget = false);
767   SDValue getTargetFrameIndex(int FI, EVT VT) {
768     return getFrameIndex(FI, VT, true);
769   }
770   LLVM_ABI SDValue getJumpTable(int JTI, EVT VT, bool isTarget = false,
771                                 unsigned TargetFlags = 0);
772   SDValue getTargetJumpTable(int JTI, EVT VT, unsigned TargetFlags = 0) {
773     return getJumpTable(JTI, VT, true, TargetFlags);
774   }
775   LLVM_ABI SDValue getJumpTableDebugInfo(int JTI, SDValue Chain,
776                                          const SDLoc &DL);
777   LLVM_ABI SDValue getConstantPool(const Constant *C, EVT VT,
778                                    MaybeAlign Align = std::nullopt,
779                                    int Offs = 0, bool isT = false,
780                                    unsigned TargetFlags = 0);
781   SDValue getTargetConstantPool(const Constant *C, EVT VT,
782                                 MaybeAlign Align = std::nullopt, int Offset = 0,
783                                 unsigned TargetFlags = 0) {
784     return getConstantPool(C, VT, Align, Offset, true, TargetFlags);
785   }
786   LLVM_ABI SDValue getConstantPool(MachineConstantPoolValue *C, EVT VT,
787                                    MaybeAlign Align = std::nullopt,
788                                    int Offs = 0, bool isT = false,
789                                    unsigned TargetFlags = 0);
790   SDValue getTargetConstantPool(MachineConstantPoolValue *C, EVT VT,
791                                 MaybeAlign Align = std::nullopt, int Offset = 0,
792                                 unsigned TargetFlags = 0) {
793     return getConstantPool(C, VT, Align, Offset, true, TargetFlags);
794   }
795   // When generating a branch to a BB, we don't in general know enough
796   // to provide debug info for the BB at that time, so keep this one around.
797   LLVM_ABI SDValue getBasicBlock(MachineBasicBlock *MBB);
798   LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT);
799   LLVM_ABI SDValue getTargetExternalSymbol(const char *Sym, EVT VT,
800                                            unsigned TargetFlags = 0);
801   LLVM_ABI SDValue getMCSymbol(MCSymbol *Sym, EVT VT);
802 
803   LLVM_ABI SDValue getValueType(EVT);
804   LLVM_ABI SDValue getRegister(Register Reg, EVT VT);
805   LLVM_ABI SDValue getRegisterMask(const uint32_t *RegMask);
806   LLVM_ABI SDValue getEHLabel(const SDLoc &dl, SDValue Root, MCSymbol *Label);
807   LLVM_ABI SDValue getLabelNode(unsigned Opcode, const SDLoc &dl, SDValue Root,
808                                 MCSymbol *Label);
809   LLVM_ABI SDValue getBlockAddress(const BlockAddress *BA, EVT VT,
810                                    int64_t Offset = 0, bool isTarget = false,
811                                    unsigned TargetFlags = 0);
812   SDValue getTargetBlockAddress(const BlockAddress *BA, EVT VT,
813                                 int64_t Offset = 0, unsigned TargetFlags = 0) {
814     return getBlockAddress(BA, VT, Offset, true, TargetFlags);
815   }
816 
817   SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, Register Reg,
818                        SDValue N) {
819     return getNode(ISD::CopyToReg, dl, MVT::Other, Chain,
820                    getRegister(Reg, N.getValueType()), N);
821   }
822 
823   // This version of the getCopyToReg method takes an extra operand, which
824   // indicates that there is potentially an incoming glue value (if Glue is not
825   // null) and that there should be a glue result.
826   SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, Register Reg, SDValue N,
827                        SDValue Glue) {
828     SDVTList VTs = getVTList(MVT::Other, MVT::Glue);
829     SDValue Ops[] = { Chain, getRegister(Reg, N.getValueType()), N, Glue };
830     return getNode(ISD::CopyToReg, dl, VTs,
831                    ArrayRef(Ops, Glue.getNode() ? 4 : 3));
832   }
833 
834   // Similar to last getCopyToReg() except parameter Reg is a SDValue
835   SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, SDValue Reg, SDValue N,
836                        SDValue Glue) {
837     SDVTList VTs = getVTList(MVT::Other, MVT::Glue);
838     SDValue Ops[] = { Chain, Reg, N, Glue };
839     return getNode(ISD::CopyToReg, dl, VTs,
840                    ArrayRef(Ops, Glue.getNode() ? 4 : 3));
841   }
842 
843   SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT) {
844     SDVTList VTs = getVTList(VT, MVT::Other);
845     SDValue Ops[] = { Chain, getRegister(Reg, VT) };
846     return getNode(ISD::CopyFromReg, dl, VTs, Ops);
847   }
848 
849   // This version of the getCopyFromReg method takes an extra operand, which
850   // indicates that there is potentially an incoming glue value (if Glue is not
851   // null) and that there should be a glue result.
852   SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT,
853                          SDValue Glue) {
854     SDVTList VTs = getVTList(VT, MVT::Other, MVT::Glue);
855     SDValue Ops[] = { Chain, getRegister(Reg, VT), Glue };
856     return getNode(ISD::CopyFromReg, dl, VTs,
857                    ArrayRef(Ops, Glue.getNode() ? 3 : 2));
858   }
859 
860   LLVM_ABI SDValue getCondCode(ISD::CondCode Cond);
861 
862   /// Return an ISD::VECTOR_SHUFFLE node. The number of elements in VT,
863   /// which must be a vector type, must match the number of mask elements
864   /// NumElts. An integer mask element equal to -1 is treated as undefined.
865   LLVM_ABI SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
866                                     SDValue N2, ArrayRef<int> Mask);
867 
868   /// Return an ISD::BUILD_VECTOR node. The number of elements in VT,
869   /// which must be a vector type, must match the number of operands in Ops.
870   /// The operands must have the same type as (or, for integers, a type wider
871   /// than) VT's element type.
872   SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef<SDValue> Ops) {
873     // VerifySDNode (via InsertNode) checks BUILD_VECTOR later.
874     return getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
875   }
876 
877   /// Return an ISD::BUILD_VECTOR node. The number of elements in VT,
878   /// which must be a vector type, must match the number of operands in Ops.
879   /// The operands must have the same type as (or, for integers, a type wider
880   /// than) VT's element type.
881   SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef<SDUse> Ops) {
882     // VerifySDNode (via InsertNode) checks BUILD_VECTOR later.
883     return getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
884   }
885 
886   /// Return a splat ISD::BUILD_VECTOR node, consisting of Op splatted to all
887   /// elements. VT must be a vector type. Op's type must be the same as (or,
888   /// for integers, a type wider than) VT's element type.
889   SDValue getSplatBuildVector(EVT VT, const SDLoc &DL, SDValue Op) {
890     // VerifySDNode (via InsertNode) checks BUILD_VECTOR later.
891     if (Op.isUndef()) {
892       assert((VT.getVectorElementType() == Op.getValueType() ||
893               (VT.isInteger() &&
894                VT.getVectorElementType().bitsLE(Op.getValueType()))) &&
895              "A splatted value must have a width equal or (for integers) "
896              "greater than the vector element type!");
897       return getNode(ISD::UNDEF, SDLoc(), VT);
898     }
899 
900     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Op);
901     return getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
902   }
903 
904   // Return a splat ISD::SPLAT_VECTOR node, consisting of Op splatted to all
905   // elements.
906   SDValue getSplatVector(EVT VT, const SDLoc &DL, SDValue Op) {
907     if (Op.isUndef()) {
908       assert((VT.getVectorElementType() == Op.getValueType() ||
909               (VT.isInteger() &&
910                VT.getVectorElementType().bitsLE(Op.getValueType()))) &&
911              "A splatted value must have a width equal or (for integers) "
912              "greater than the vector element type!");
913       return getNode(ISD::UNDEF, SDLoc(), VT);
914     }
915     return getNode(ISD::SPLAT_VECTOR, DL, VT, Op);
916   }
917 
918   /// Returns a node representing a splat of one value into all lanes
919   /// of the provided vector type.  This is a utility which returns
920   /// either a BUILD_VECTOR or SPLAT_VECTOR depending on the
921   /// scalability of the desired vector type.
922   SDValue getSplat(EVT VT, const SDLoc &DL, SDValue Op) {
923     assert(VT.isVector() && "Can't splat to non-vector type");
924     return VT.isScalableVector() ?
925       getSplatVector(VT, DL, Op) : getSplatBuildVector(VT, DL, Op);
926   }
927 
928   /// Returns a vector of type ResVT whose elements contain the linear sequence
929   ///   <0, Step, Step * 2, Step * 3, ...>
930   LLVM_ABI SDValue getStepVector(const SDLoc &DL, EVT ResVT,
931                                  const APInt &StepVal);
932 
933   /// Returns a vector of type ResVT whose elements contain the linear sequence
934   ///   <0, 1, 2, 3, ...>
935   LLVM_ABI SDValue getStepVector(const SDLoc &DL, EVT ResVT);
936 
937   /// Returns an ISD::VECTOR_SHUFFLE node semantically equivalent to
938   /// the shuffle node in input but with swapped operands.
939   ///
940   /// Example: shuffle A, B, <0,5,2,7> -> shuffle B, A, <4,1,6,3>
941   LLVM_ABI SDValue getCommutedVectorShuffle(const ShuffleVectorSDNode &SV);
942 
943   /// Extract element at \p Idx from \p Vec.  See EXTRACT_VECTOR_ELT
944   /// description for result type handling.
945   SDValue getExtractVectorElt(const SDLoc &DL, EVT VT, SDValue Vec,
946                               unsigned Idx) {
947     return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Vec,
948                    getVectorIdxConstant(Idx, DL));
949   }
950 
951   /// Insert \p Elt into \p Vec at offset \p Idx.  See INSERT_VECTOR_ELT
952   /// description for element type handling.
953   SDValue getInsertVectorElt(const SDLoc &DL, SDValue Vec, SDValue Elt,
954                              unsigned Idx) {
955     return getNode(ISD::INSERT_VECTOR_ELT, DL, Vec.getValueType(), Vec, Elt,
956                    getVectorIdxConstant(Idx, DL));
957   }
958 
959   /// Insert \p SubVec at the \p Idx element of \p Vec.
960   SDValue getInsertSubvector(const SDLoc &DL, SDValue Vec, SDValue SubVec,
961                              unsigned Idx) {
962     return getNode(ISD::INSERT_SUBVECTOR, DL, Vec.getValueType(), Vec, SubVec,
963                    getVectorIdxConstant(Idx, DL));
964   }
965 
966   /// Return the \p VT typed sub-vector of \p Vec at \p Idx
967   SDValue getExtractSubvector(const SDLoc &DL, EVT VT, SDValue Vec,
968                               unsigned Idx) {
969     return getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
970                    getVectorIdxConstant(Idx, DL));
971   }
972 
973   /// Convert Op, which must be of float type, to the
974   /// float type VT, by either extending or rounding (by truncation).
975   LLVM_ABI SDValue getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT);
976 
977   /// Convert Op, which must be a STRICT operation of float type, to the
978   /// float type VT, by either extending or rounding (by truncation).
979   LLVM_ABI std::pair<SDValue, SDValue>
980   getStrictFPExtendOrRound(SDValue Op, SDValue Chain, const SDLoc &DL, EVT VT);
981 
982   /// Convert *_EXTEND_VECTOR_INREG to *_EXTEND opcode.
983   static unsigned getOpcode_EXTEND(unsigned Opcode) {
984     switch (Opcode) {
985     case ISD::ANY_EXTEND:
986     case ISD::ANY_EXTEND_VECTOR_INREG:
987       return ISD::ANY_EXTEND;
988     case ISD::ZERO_EXTEND:
989     case ISD::ZERO_EXTEND_VECTOR_INREG:
990       return ISD::ZERO_EXTEND;
991     case ISD::SIGN_EXTEND:
992     case ISD::SIGN_EXTEND_VECTOR_INREG:
993       return ISD::SIGN_EXTEND;
994     }
995     llvm_unreachable("Unknown opcode");
996   }
997 
998   /// Convert *_EXTEND to *_EXTEND_VECTOR_INREG opcode.
999   static unsigned getOpcode_EXTEND_VECTOR_INREG(unsigned Opcode) {
1000     switch (Opcode) {
1001     case ISD::ANY_EXTEND:
1002     case ISD::ANY_EXTEND_VECTOR_INREG:
1003       return ISD::ANY_EXTEND_VECTOR_INREG;
1004     case ISD::ZERO_EXTEND:
1005     case ISD::ZERO_EXTEND_VECTOR_INREG:
1006       return ISD::ZERO_EXTEND_VECTOR_INREG;
1007     case ISD::SIGN_EXTEND:
1008     case ISD::SIGN_EXTEND_VECTOR_INREG:
1009       return ISD::SIGN_EXTEND_VECTOR_INREG;
1010     }
1011     llvm_unreachable("Unknown opcode");
1012   }
1013 
1014   /// Convert Op, which must be of integer type, to the
1015   /// integer type VT, by either any-extending or truncating it.
1016   LLVM_ABI SDValue getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT);
1017 
1018   /// Convert Op, which must be of integer type, to the
1019   /// integer type VT, by either sign-extending or truncating it.
1020   LLVM_ABI SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT);
1021 
1022   /// Convert Op, which must be of integer type, to the
1023   /// integer type VT, by either zero-extending or truncating it.
1024   LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT);
1025 
1026   /// Convert Op, which must be of integer type, to the
1027   /// integer type VT, by either any/sign/zero-extending (depending on IsAny /
1028   /// IsSigned) or truncating it.
1029   SDValue getExtOrTrunc(SDValue Op, const SDLoc &DL,
1030                         EVT VT, unsigned Opcode) {
1031     switch(Opcode) {
1032       case ISD::ANY_EXTEND:
1033         return getAnyExtOrTrunc(Op, DL, VT);
1034       case ISD::ZERO_EXTEND:
1035         return getZExtOrTrunc(Op, DL, VT);
1036       case ISD::SIGN_EXTEND:
1037         return getSExtOrTrunc(Op, DL, VT);
1038     }
1039     llvm_unreachable("Unsupported opcode");
1040   }
1041 
1042   /// Convert Op, which must be of integer type, to the
1043   /// integer type VT, by either sign/zero-extending (depending on IsSigned) or
1044   /// truncating it.
1045   SDValue getExtOrTrunc(bool IsSigned, SDValue Op, const SDLoc &DL, EVT VT) {
1046     return IsSigned ? getSExtOrTrunc(Op, DL, VT) : getZExtOrTrunc(Op, DL, VT);
1047   }
1048 
1049   /// Convert Op, which must be of integer type, to the
1050   /// integer type VT, by first bitcasting (from potential vector) to
1051   /// corresponding scalar type then either any-extending or truncating it.
1052   LLVM_ABI SDValue getBitcastedAnyExtOrTrunc(SDValue Op, const SDLoc &DL,
1053                                              EVT VT);
1054 
1055   /// Convert Op, which must be of integer type, to the
1056   /// integer type VT, by first bitcasting (from potential vector) to
1057   /// corresponding scalar type then either sign-extending or truncating it.
1058   LLVM_ABI SDValue getBitcastedSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT);
1059 
1060   /// Convert Op, which must be of integer type, to the
1061   /// integer type VT, by first bitcasting (from potential vector) to
1062   /// corresponding scalar type then either zero-extending or truncating it.
1063   LLVM_ABI SDValue getBitcastedZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT);
1064 
1065   /// Return the expression required to zero extend the Op
1066   /// value assuming it was the smaller SrcTy value.
1067   LLVM_ABI SDValue getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT);
1068 
1069   /// Return the expression required to zero extend the Op
1070   /// value assuming it was the smaller SrcTy value.
1071   LLVM_ABI SDValue getVPZeroExtendInReg(SDValue Op, SDValue Mask, SDValue EVL,
1072                                         const SDLoc &DL, EVT VT);
1073 
1074   /// Convert Op, which must be of integer type, to the integer type VT, by
1075   /// either truncating it or performing either zero or sign extension as
1076   /// appropriate extension for the pointer's semantics.
1077   LLVM_ABI SDValue getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT);
1078 
1079   /// Return the expression required to extend the Op as a pointer value
1080   /// assuming it was the smaller SrcTy value. This may be either a zero extend
1081   /// or a sign extend.
1082   LLVM_ABI SDValue getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT);
1083 
1084   /// Convert Op, which must be of integer type, to the integer type VT,
1085   /// by using an extension appropriate for the target's
1086   /// BooleanContent for type OpVT or truncating it.
1087   LLVM_ABI SDValue getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1088                                      EVT OpVT);
1089 
1090   /// Create negative operation as (SUB 0, Val).
1091   LLVM_ABI SDValue getNegative(SDValue Val, const SDLoc &DL, EVT VT);
1092 
1093   /// Create a bitwise NOT operation as (XOR Val, -1).
1094   LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT);
1095 
1096   /// Create a logical NOT operation as (XOR Val, BooleanOne).
1097   LLVM_ABI SDValue getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT);
1098 
1099   /// Create a vector-predicated logical NOT operation as (VP_XOR Val,
1100   /// BooleanOne, Mask, EVL).
1101   LLVM_ABI SDValue getVPLogicalNOT(const SDLoc &DL, SDValue Val, SDValue Mask,
1102                                    SDValue EVL, EVT VT);
1103 
1104   /// Convert a vector-predicated Op, which must be an integer vector, to the
1105   /// vector-type VT, by performing either vector-predicated zext or truncating
1106   /// it. The Op will be returned as-is if Op and VT are vectors containing
1107   /// integer with same width.
1108   LLVM_ABI SDValue getVPZExtOrTrunc(const SDLoc &DL, EVT VT, SDValue Op,
1109                                     SDValue Mask, SDValue EVL);
1110 
1111   /// Convert a vector-predicated Op, which must be of integer type, to the
1112   /// vector-type integer type VT, by either truncating it or performing either
1113   /// vector-predicated zero or sign extension as appropriate extension for the
1114   /// pointer's semantics. This function just redirects to getVPZExtOrTrunc
1115   /// right now.
1116   LLVM_ABI SDValue getVPPtrExtOrTrunc(const SDLoc &DL, EVT VT, SDValue Op,
1117                                       SDValue Mask, SDValue EVL);
1118 
1119   /// Returns sum of the base pointer and offset.
1120   /// Unlike getObjectPtrOffset this does not set NoUnsignedWrap by default.
1121   LLVM_ABI SDValue
1122   getMemBasePlusOffset(SDValue Base, TypeSize Offset, const SDLoc &DL,
1123                        const SDNodeFlags Flags = SDNodeFlags());
1124   LLVM_ABI SDValue
1125   getMemBasePlusOffset(SDValue Base, SDValue Offset, const SDLoc &DL,
1126                        const SDNodeFlags Flags = SDNodeFlags());
1127 
1128   /// Create an add instruction with appropriate flags when used for
1129   /// addressing some offset of an object. i.e. if a load is split into multiple
1130   /// components, create an add nuw from the base pointer to the offset.
1131   SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Ptr, TypeSize Offset) {
1132     return getMemBasePlusOffset(Ptr, Offset, SL, SDNodeFlags::NoUnsignedWrap);
1133   }
1134 
1135   SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Ptr, SDValue Offset) {
1136     // The object itself can't wrap around the address space, so it shouldn't be
1137     // possible for the adds of the offsets to the split parts to overflow.
1138     return getMemBasePlusOffset(Ptr, Offset, SL, SDNodeFlags::NoUnsignedWrap);
1139   }
1140 
1141   /// Return a new CALLSEQ_START node, that starts new call frame, in which
1142   /// InSize bytes are set up inside CALLSEQ_START..CALLSEQ_END sequence and
1143   /// OutSize specifies part of the frame set up prior to the sequence.
1144   SDValue getCALLSEQ_START(SDValue Chain, uint64_t InSize, uint64_t OutSize,
1145                            const SDLoc &DL) {
1146     SDVTList VTs = getVTList(MVT::Other, MVT::Glue);
1147     SDValue Ops[] = { Chain,
1148                       getIntPtrConstant(InSize, DL, true),
1149                       getIntPtrConstant(OutSize, DL, true) };
1150     return getNode(ISD::CALLSEQ_START, DL, VTs, Ops);
1151   }
1152 
1153   /// Return a new CALLSEQ_END node, which always must have a
1154   /// glue result (to ensure it's not CSE'd).
1155   /// CALLSEQ_END does not have a useful SDLoc.
1156   SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2,
1157                          SDValue InGlue, const SDLoc &DL) {
1158     SDVTList NodeTys = getVTList(MVT::Other, MVT::Glue);
1159     SmallVector<SDValue, 4> Ops;
1160     Ops.push_back(Chain);
1161     Ops.push_back(Op1);
1162     Ops.push_back(Op2);
1163     if (InGlue.getNode())
1164       Ops.push_back(InGlue);
1165     return getNode(ISD::CALLSEQ_END, DL, NodeTys, Ops);
1166   }
1167 
1168   SDValue getCALLSEQ_END(SDValue Chain, uint64_t Size1, uint64_t Size2,
1169                          SDValue Glue, const SDLoc &DL) {
1170     return getCALLSEQ_END(
1171         Chain, getIntPtrConstant(Size1, DL, /*isTarget=*/true),
1172         getIntPtrConstant(Size2, DL, /*isTarget=*/true), Glue, DL);
1173   }
1174 
1175   /// Return true if the result of this operation is always undefined.
1176   LLVM_ABI bool isUndef(unsigned Opcode, ArrayRef<SDValue> Ops);
1177 
1178   /// Return an UNDEF node. UNDEF does not have a useful SDLoc.
1179   SDValue getUNDEF(EVT VT) {
1180     return getNode(ISD::UNDEF, SDLoc(), VT);
1181   }
1182 
1183   /// Return a POISON node. POISON does not have a useful SDLoc.
1184   SDValue getPOISON(EVT VT) { return getNode(ISD::POISON, SDLoc(), VT); }
1185 
1186   /// Return a node that represents the runtime scaling 'MulImm * RuntimeVL'.
1187   LLVM_ABI SDValue getVScale(const SDLoc &DL, EVT VT, APInt MulImm,
1188                              bool ConstantFold = true);
1189 
1190   LLVM_ABI SDValue getElementCount(const SDLoc &DL, EVT VT, ElementCount EC,
1191                                    bool ConstantFold = true);
1192 
1193   /// Return a GLOBAL_OFFSET_TABLE node. This does not have a useful SDLoc.
1194   SDValue getGLOBAL_OFFSET_TABLE(EVT VT) {
1195     return getNode(ISD::GLOBAL_OFFSET_TABLE, SDLoc(), VT);
1196   }
1197 
1198   /// Gets or creates the specified node.
1199   ///
1200   LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
1201                            ArrayRef<SDUse> Ops);
1202   LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
1203                            ArrayRef<SDValue> Ops, const SDNodeFlags Flags);
1204   LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL,
1205                            ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops);
1206   LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
1207                            ArrayRef<SDValue> Ops, const SDNodeFlags Flags);
1208 
1209   // Use flags from current flag inserter.
1210   LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
1211                            ArrayRef<SDValue> Ops);
1212   LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
1213                            ArrayRef<SDValue> Ops);
1214   LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
1215                            SDValue Operand);
1216   LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N1,
1217                            SDValue N2);
1218   LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N1,
1219                            SDValue N2, SDValue N3);
1220 
1221   // Specialize based on number of operands.
1222   LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT);
1223   LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
1224                            SDValue Operand, const SDNodeFlags Flags);
1225   LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N1,
1226                            SDValue N2, const SDNodeFlags Flags);
1227   LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N1,
1228                            SDValue N2, SDValue N3, const SDNodeFlags Flags);
1229   LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N1,
1230                            SDValue N2, SDValue N3, SDValue N4);
1231   LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N1,
1232                            SDValue N2, SDValue N3, SDValue N4,
1233                            const SDNodeFlags Flags);
1234   LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N1,
1235                            SDValue N2, SDValue N3, SDValue N4, SDValue N5);
1236   LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N1,
1237                            SDValue N2, SDValue N3, SDValue N4, SDValue N5,
1238                            const SDNodeFlags Flags);
1239 
1240   // Specialize again based on number of operands for nodes with a VTList
1241   // rather than a single VT.
1242   LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList);
1243   LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
1244                            SDValue N);
1245   LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
1246                            SDValue N1, SDValue N2);
1247   LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
1248                            SDValue N1, SDValue N2, SDValue N3);
1249   LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
1250                            SDValue N1, SDValue N2, SDValue N3, SDValue N4);
1251   LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
1252                            SDValue N1, SDValue N2, SDValue N3, SDValue N4,
1253                            SDValue N5);
1254 
1255   /// Compute a TokenFactor to force all the incoming stack arguments to be
1256   /// loaded from the stack. This is used in tail call lowering to protect
1257   /// stack arguments from being clobbered.
1258   LLVM_ABI SDValue getStackArgumentTokenFactor(SDValue Chain);
1259 
1260   /* \p CI if not null is the memset call being lowered.
1261    * \p OverrideTailCall is an optional parameter that can be used to override
1262    * the tail call optimization decision. */
1263   LLVM_ABI SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
1264                              SDValue Src, SDValue Size, Align Alignment,
1265                              bool isVol, bool AlwaysInline, const CallInst *CI,
1266                              std::optional<bool> OverrideTailCall,
1267                              MachinePointerInfo DstPtrInfo,
1268                              MachinePointerInfo SrcPtrInfo,
1269                              const AAMDNodes &AAInfo = AAMDNodes(),
1270                              BatchAAResults *BatchAA = nullptr);
1271 
1272   /* \p CI if not null is the memset call being lowered.
1273    * \p OverrideTailCall is an optional parameter that can be used to override
1274    * the tail call optimization decision. */
1275   LLVM_ABI SDValue getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
1276                               SDValue Src, SDValue Size, Align Alignment,
1277                               bool isVol, const CallInst *CI,
1278                               std::optional<bool> OverrideTailCall,
1279                               MachinePointerInfo DstPtrInfo,
1280                               MachinePointerInfo SrcPtrInfo,
1281                               const AAMDNodes &AAInfo = AAMDNodes(),
1282                               BatchAAResults *BatchAA = nullptr);
1283 
1284   LLVM_ABI SDValue getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
1285                              SDValue Src, SDValue Size, Align Alignment,
1286                              bool isVol, bool AlwaysInline, const CallInst *CI,
1287                              MachinePointerInfo DstPtrInfo,
1288                              const AAMDNodes &AAInfo = AAMDNodes());
1289 
1290   LLVM_ABI SDValue getAtomicMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
1291                                    SDValue Src, SDValue Size, Type *SizeTy,
1292                                    unsigned ElemSz, bool isTailCall,
1293                                    MachinePointerInfo DstPtrInfo,
1294                                    MachinePointerInfo SrcPtrInfo);
1295 
1296   LLVM_ABI SDValue getAtomicMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
1297                                     SDValue Src, SDValue Size, Type *SizeTy,
1298                                     unsigned ElemSz, bool isTailCall,
1299                                     MachinePointerInfo DstPtrInfo,
1300                                     MachinePointerInfo SrcPtrInfo);
1301 
1302   LLVM_ABI SDValue getAtomicMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
1303                                    SDValue Value, SDValue Size, Type *SizeTy,
1304                                    unsigned ElemSz, bool isTailCall,
1305                                    MachinePointerInfo DstPtrInfo);
1306 
1307   /// Helper function to make it easier to build SetCC's if you just have an
1308   /// ISD::CondCode instead of an SDValue.
1309   SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS,
1310                    ISD::CondCode Cond, SDValue Chain = SDValue(),
1311                    bool IsSignaling = false) {
1312     assert(LHS.getValueType().isVector() == RHS.getValueType().isVector() &&
1313            "Vector/scalar operand type mismatch for setcc");
1314     assert(LHS.getValueType().isVector() == VT.isVector() &&
1315            "Vector/scalar result type mismatch for setcc");
1316     assert(Cond != ISD::SETCC_INVALID &&
1317            "Cannot create a setCC of an invalid node.");
1318     if (Chain)
1319       return getNode(IsSignaling ? ISD::STRICT_FSETCCS : ISD::STRICT_FSETCC, DL,
1320                      {VT, MVT::Other}, {Chain, LHS, RHS, getCondCode(Cond)});
1321     return getNode(ISD::SETCC, DL, VT, LHS, RHS, getCondCode(Cond));
1322   }
1323 
1324   /// Helper function to make it easier to build VP_SETCCs if you just have an
1325   /// ISD::CondCode instead of an SDValue.
1326   SDValue getSetCCVP(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS,
1327                      ISD::CondCode Cond, SDValue Mask, SDValue EVL) {
1328     assert(LHS.getValueType().isVector() && RHS.getValueType().isVector() &&
1329            "Cannot compare scalars");
1330     assert(Cond != ISD::SETCC_INVALID &&
1331            "Cannot create a setCC of an invalid node.");
1332     return getNode(ISD::VP_SETCC, DL, VT, LHS, RHS, getCondCode(Cond), Mask,
1333                    EVL);
1334   }
1335 
1336   /// Helper function to make it easier to build Select's if you just have
1337   /// operands and don't want to check for vector.
1338   SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS,
1339                     SDValue RHS, SDNodeFlags Flags = SDNodeFlags()) {
1340     assert(LHS.getValueType() == VT && RHS.getValueType() == VT &&
1341            "Cannot use select on differing types");
1342     auto Opcode = Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
1343     return getNode(Opcode, DL, VT, Cond, LHS, RHS, Flags);
1344   }
1345 
1346   /// Helper function to make it easier to build SelectCC's if you just have an
1347   /// ISD::CondCode instead of an SDValue.
1348   SDValue getSelectCC(const SDLoc &DL, SDValue LHS, SDValue RHS, SDValue True,
1349                       SDValue False, ISD::CondCode Cond) {
1350     return getNode(ISD::SELECT_CC, DL, True.getValueType(), LHS, RHS, True,
1351                    False, getCondCode(Cond));
1352   }
1353 
1354   /// Try to simplify a select/vselect into 1 of its operands or a constant.
1355   LLVM_ABI SDValue simplifySelect(SDValue Cond, SDValue TVal, SDValue FVal);
1356 
1357   /// Try to simplify a shift into 1 of its operands or a constant.
1358   LLVM_ABI SDValue simplifyShift(SDValue X, SDValue Y);
1359 
1360   /// Try to simplify a floating-point binary operation into 1 of its operands
1361   /// or a constant.
1362   LLVM_ABI SDValue simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
1363                                    SDNodeFlags Flags);
1364 
1365   /// VAArg produces a result and token chain, and takes a pointer
1366   /// and a source value as input.
1367   LLVM_ABI SDValue getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr,
1368                             SDValue SV, unsigned Align);
1369 
1370   /// Gets a node for an atomic cmpxchg op. There are two
1371   /// valid Opcodes. ISD::ATOMIC_CMO_SWAP produces the value loaded and a
1372   /// chain result. ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS produces the value loaded,
1373   /// a success flag (initially i1), and a chain.
1374   LLVM_ABI SDValue getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, EVT MemVT,
1375                                     SDVTList VTs, SDValue Chain, SDValue Ptr,
1376                                     SDValue Cmp, SDValue Swp,
1377                                     MachineMemOperand *MMO);
1378 
1379   /// Gets a node for an atomic op, produces result (if relevant)
1380   /// and chain and takes 2 operands.
1381   LLVM_ABI SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
1382                              SDValue Chain, SDValue Ptr, SDValue Val,
1383                              MachineMemOperand *MMO);
1384 
1385   /// Gets a node for an atomic op, produces result and chain and takes N
1386   /// operands.
1387   LLVM_ABI SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
1388                              SDVTList VTList, ArrayRef<SDValue> Ops,
1389                              MachineMemOperand *MMO,
1390                              ISD::LoadExtType ExtType = ISD::NON_EXTLOAD);
1391 
1392   LLVM_ABI SDValue getAtomicLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
1393                                  EVT MemVT, EVT VT, SDValue Chain, SDValue Ptr,
1394                                  MachineMemOperand *MMO);
1395 
1396   /// Creates a MemIntrinsicNode that may produce a
1397   /// result and takes a list of operands. Opcode may be INTRINSIC_VOID,
1398   /// INTRINSIC_W_CHAIN, or a target-specific memory-referencing opcode
1399   // (see `SelectionDAGTargetInfo::isTargetMemoryOpcode`).
1400   LLVM_ABI SDValue getMemIntrinsicNode(
1401       unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
1402       EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
1403       MachineMemOperand::Flags Flags = MachineMemOperand::MOLoad |
1404                                        MachineMemOperand::MOStore,
1405       LocationSize Size = LocationSize::precise(0),
1406       const AAMDNodes &AAInfo = AAMDNodes());
1407 
1408   inline SDValue getMemIntrinsicNode(
1409       unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
1410       EVT MemVT, MachinePointerInfo PtrInfo,
1411       MaybeAlign Alignment = std::nullopt,
1412       MachineMemOperand::Flags Flags = MachineMemOperand::MOLoad |
1413                                        MachineMemOperand::MOStore,
1414       LocationSize Size = LocationSize::precise(0),
1415       const AAMDNodes &AAInfo = AAMDNodes()) {
1416     // Ensure that codegen never sees alignment 0
1417     return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, PtrInfo,
1418                                Alignment.value_or(getEVTAlign(MemVT)), Flags,
1419                                Size, AAInfo);
1420   }
1421 
1422   LLVM_ABI SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
1423                                        SDVTList VTList, ArrayRef<SDValue> Ops,
1424                                        EVT MemVT, MachineMemOperand *MMO);
1425 
1426   /// Creates a LifetimeSDNode that starts (`IsStart==true`) or ends
1427   /// (`IsStart==false`) the lifetime of the portion of `FrameIndex` between
1428   /// offsets `Offset` and `Offset + Size`.
1429   LLVM_ABI SDValue getLifetimeNode(bool IsStart, const SDLoc &dl, SDValue Chain,
1430                                    int FrameIndex, int64_t Size,
1431                                    int64_t Offset = -1);
1432 
1433   /// Creates a PseudoProbeSDNode with function GUID `Guid` and
1434   /// the index of the block `Index` it is probing, as well as the attributes
1435   /// `attr` of the probe.
1436   LLVM_ABI SDValue getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
1437                                       uint64_t Guid, uint64_t Index,
1438                                       uint32_t Attr);
1439 
1440   /// Create a MERGE_VALUES node from the given operands.
1441   LLVM_ABI SDValue getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl);
1442 
1443   /// Loads are not normal binary operators: their result type is not
1444   /// determined by their operands, and they produce a value AND a token chain.
1445   ///
1446   /// This function will set the MOLoad flag on MMOFlags, but you can set it if
1447   /// you want.  The MOStore flag must not be set.
1448   LLVM_ABI SDValue getLoad(
1449       EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr,
1450       MachinePointerInfo PtrInfo, MaybeAlign Alignment = MaybeAlign(),
1451       MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
1452       const AAMDNodes &AAInfo = AAMDNodes(), const MDNode *Ranges = nullptr);
1453   LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr,
1454                            MachineMemOperand *MMO);
1455   LLVM_ABI SDValue
1456   getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain,
1457              SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT,
1458              MaybeAlign Alignment = MaybeAlign(),
1459              MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
1460              const AAMDNodes &AAInfo = AAMDNodes());
1461   LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT,
1462                               SDValue Chain, SDValue Ptr, EVT MemVT,
1463                               MachineMemOperand *MMO);
1464   LLVM_ABI SDValue getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
1465                                   SDValue Base, SDValue Offset,
1466                                   ISD::MemIndexedMode AM);
1467   LLVM_ABI SDValue getLoad(
1468       ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
1469       SDValue Chain, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo,
1470       EVT MemVT, Align Alignment,
1471       MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
1472       const AAMDNodes &AAInfo = AAMDNodes(), const MDNode *Ranges = nullptr);
1473   inline SDValue getLoad(
1474       ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
1475       SDValue Chain, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo,
1476       EVT MemVT, MaybeAlign Alignment = MaybeAlign(),
1477       MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
1478       const AAMDNodes &AAInfo = AAMDNodes(), const MDNode *Ranges = nullptr) {
1479     // Ensures that codegen never sees a None Alignment.
1480     return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, PtrInfo, MemVT,
1481                    Alignment.value_or(getEVTAlign(MemVT)), MMOFlags, AAInfo,
1482                    Ranges);
1483   }
1484   LLVM_ABI SDValue getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
1485                            EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr,
1486                            SDValue Offset, EVT MemVT, MachineMemOperand *MMO);
1487 
1488   /// Helper function to build ISD::STORE nodes.
1489   ///
1490   /// This function will set the MOStore flag on MMOFlags, but you can set it if
1491   /// you want.  The MOLoad and MOInvariant flags must not be set.
1492 
1493   LLVM_ABI SDValue
1494   getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr,
1495            MachinePointerInfo PtrInfo, Align Alignment,
1496            MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
1497            const AAMDNodes &AAInfo = AAMDNodes());
1498   inline SDValue
1499   getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr,
1500            MachinePointerInfo PtrInfo, MaybeAlign Alignment = MaybeAlign(),
1501            MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
1502            const AAMDNodes &AAInfo = AAMDNodes()) {
1503     return getStore(Chain, dl, Val, Ptr, PtrInfo,
1504                     Alignment.value_or(getEVTAlign(Val.getValueType())),
1505                     MMOFlags, AAInfo);
1506   }
1507   LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
1508                             SDValue Ptr, MachineMemOperand *MMO);
1509   LLVM_ABI SDValue
1510   getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr,
1511                 MachinePointerInfo PtrInfo, EVT SVT, Align Alignment,
1512                 MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
1513                 const AAMDNodes &AAInfo = AAMDNodes());
1514   inline SDValue
1515   getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr,
1516                 MachinePointerInfo PtrInfo, EVT SVT,
1517                 MaybeAlign Alignment = MaybeAlign(),
1518                 MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
1519                 const AAMDNodes &AAInfo = AAMDNodes()) {
1520     return getTruncStore(Chain, dl, Val, Ptr, PtrInfo, SVT,
1521                          Alignment.value_or(getEVTAlign(SVT)), MMOFlags,
1522                          AAInfo);
1523   }
1524   LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
1525                                  SDValue Ptr, EVT SVT, MachineMemOperand *MMO);
1526   LLVM_ABI SDValue getIndexedStore(SDValue OrigStore, const SDLoc &dl,
1527                                    SDValue Base, SDValue Offset,
1528                                    ISD::MemIndexedMode AM);
1529   LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
1530                             SDValue Ptr, SDValue Offset, EVT SVT,
1531                             MachineMemOperand *MMO, ISD::MemIndexedMode AM,
1532                             bool IsTruncating = false);
1533 
1534   LLVM_ABI SDValue getLoadVP(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
1535                              EVT VT, const SDLoc &dl, SDValue Chain,
1536                              SDValue Ptr, SDValue Offset, SDValue Mask,
1537                              SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT,
1538                              Align Alignment, MachineMemOperand::Flags MMOFlags,
1539                              const AAMDNodes &AAInfo,
1540                              const MDNode *Ranges = nullptr,
1541                              bool IsExpanding = false);
1542   inline SDValue
1543   getLoadVP(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT,
1544             const SDLoc &dl, SDValue Chain, SDValue Ptr, SDValue Offset,
1545             SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT,
1546             MaybeAlign Alignment = MaybeAlign(),
1547             MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
1548             const AAMDNodes &AAInfo = AAMDNodes(),
1549             const MDNode *Ranges = nullptr, bool IsExpanding = false) {
1550     // Ensures that codegen never sees a None Alignment.
1551     return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL,
1552                      PtrInfo, MemVT, Alignment.value_or(getEVTAlign(MemVT)),
1553                      MMOFlags, AAInfo, Ranges, IsExpanding);
1554   }
1555   LLVM_ABI SDValue getLoadVP(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
1556                              EVT VT, const SDLoc &dl, SDValue Chain,
1557                              SDValue Ptr, SDValue Offset, SDValue Mask,
1558                              SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
1559                              bool IsExpanding = false);
1560   LLVM_ABI SDValue getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
1561                              SDValue Ptr, SDValue Mask, SDValue EVL,
1562                              MachinePointerInfo PtrInfo, MaybeAlign Alignment,
1563                              MachineMemOperand::Flags MMOFlags,
1564                              const AAMDNodes &AAInfo,
1565                              const MDNode *Ranges = nullptr,
1566                              bool IsExpanding = false);
1567   LLVM_ABI SDValue getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
1568                              SDValue Ptr, SDValue Mask, SDValue EVL,
1569                              MachineMemOperand *MMO, bool IsExpanding = false);
1570   LLVM_ABI SDValue getExtLoadVP(
1571       ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain,
1572       SDValue Ptr, SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo,
1573       EVT MemVT, MaybeAlign Alignment, MachineMemOperand::Flags MMOFlags,
1574       const AAMDNodes &AAInfo, bool IsExpanding = false);
1575   LLVM_ABI SDValue getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
1576                                 EVT VT, SDValue Chain, SDValue Ptr,
1577                                 SDValue Mask, SDValue EVL, EVT MemVT,
1578                                 MachineMemOperand *MMO,
1579                                 bool IsExpanding = false);
1580   LLVM_ABI SDValue getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
1581                                     SDValue Base, SDValue Offset,
1582                                     ISD::MemIndexedMode AM);
1583   LLVM_ABI SDValue getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
1584                               SDValue Ptr, SDValue Offset, SDValue Mask,
1585                               SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
1586                               ISD::MemIndexedMode AM, bool IsTruncating = false,
1587                               bool IsCompressing = false);
1588   LLVM_ABI SDValue getTruncStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
1589                                    SDValue Ptr, SDValue Mask, SDValue EVL,
1590                                    MachinePointerInfo PtrInfo, EVT SVT,
1591                                    Align Alignment,
1592                                    MachineMemOperand::Flags MMOFlags,
1593                                    const AAMDNodes &AAInfo,
1594                                    bool IsCompressing = false);
1595   LLVM_ABI SDValue getTruncStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
1596                                    SDValue Ptr, SDValue Mask, SDValue EVL,
1597                                    EVT SVT, MachineMemOperand *MMO,
1598                                    bool IsCompressing = false);
1599   LLVM_ABI SDValue getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
1600                                      SDValue Base, SDValue Offset,
1601                                      ISD::MemIndexedMode AM);
1602 
1603   LLVM_ABI SDValue getStridedLoadVP(
1604       ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
1605       SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
1606       SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding = false);
1607   LLVM_ABI SDValue getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain,
1608                                     SDValue Ptr, SDValue Stride, SDValue Mask,
1609                                     SDValue EVL, MachineMemOperand *MMO,
1610                                     bool IsExpanding = false);
1611   LLVM_ABI SDValue getExtStridedLoadVP(ISD::LoadExtType ExtType,
1612                                        const SDLoc &DL, EVT VT, SDValue Chain,
1613                                        SDValue Ptr, SDValue Stride,
1614                                        SDValue Mask, SDValue EVL, EVT MemVT,
1615                                        MachineMemOperand *MMO,
1616                                        bool IsExpanding = false);
1617   LLVM_ABI SDValue getStridedStoreVP(SDValue Chain, const SDLoc &DL,
1618                                      SDValue Val, SDValue Ptr, SDValue Offset,
1619                                      SDValue Stride, SDValue Mask, SDValue EVL,
1620                                      EVT MemVT, MachineMemOperand *MMO,
1621                                      ISD::MemIndexedMode AM,
1622                                      bool IsTruncating = false,
1623                                      bool IsCompressing = false);
1624   LLVM_ABI SDValue getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL,
1625                                           SDValue Val, SDValue Ptr,
1626                                           SDValue Stride, SDValue Mask,
1627                                           SDValue EVL, EVT SVT,
1628                                           MachineMemOperand *MMO,
1629                                           bool IsCompressing = false);
1630 
1631   LLVM_ABI SDValue getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
1632                                ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
1633                                ISD::MemIndexType IndexType);
1634   LLVM_ABI SDValue getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
1635                                 ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
1636                                 ISD::MemIndexType IndexType);
1637 
1638   LLVM_ABI SDValue getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
1639                                  SDValue Base, SDValue Offset, SDValue Mask,
1640                                  SDValue Src0, EVT MemVT,
1641                                  MachineMemOperand *MMO, ISD::MemIndexedMode AM,
1642                                  ISD::LoadExtType, bool IsExpanding = false);
1643   LLVM_ABI SDValue getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
1644                                         SDValue Base, SDValue Offset,
1645                                         ISD::MemIndexedMode AM);
1646   LLVM_ABI SDValue getMaskedStore(SDValue Chain, const SDLoc &dl, SDValue Val,
1647                                   SDValue Base, SDValue Offset, SDValue Mask,
1648                                   EVT MemVT, MachineMemOperand *MMO,
1649                                   ISD::MemIndexedMode AM,
1650                                   bool IsTruncating = false,
1651                                   bool IsCompressing = false);
1652   LLVM_ABI SDValue getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
1653                                          SDValue Base, SDValue Offset,
1654                                          ISD::MemIndexedMode AM);
1655   LLVM_ABI SDValue getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
1656                                    ArrayRef<SDValue> Ops,
1657                                    MachineMemOperand *MMO,
1658                                    ISD::MemIndexType IndexType,
1659                                    ISD::LoadExtType ExtTy);
1660   LLVM_ABI SDValue getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
1661                                     ArrayRef<SDValue> Ops,
1662                                     MachineMemOperand *MMO,
1663                                     ISD::MemIndexType IndexType,
1664                                     bool IsTruncating = false);
1665   LLVM_ABI SDValue getMaskedHistogram(SDVTList VTs, EVT MemVT, const SDLoc &dl,
1666                                       ArrayRef<SDValue> Ops,
1667                                       MachineMemOperand *MMO,
1668                                       ISD::MemIndexType IndexType);
1669 
1670   LLVM_ABI SDValue getGetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr,
1671                                EVT MemVT, MachineMemOperand *MMO);
1672   LLVM_ABI SDValue getSetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr,
1673                                EVT MemVT, MachineMemOperand *MMO);
1674 
1675   /// Construct a node to track a Value* through the backend.
1676   LLVM_ABI SDValue getSrcValue(const Value *v);
1677 
1678   /// Return an MDNodeSDNode which holds an MDNode.
1679   LLVM_ABI SDValue getMDNode(const MDNode *MD);
1680 
1681   /// Return a bitcast using the SDLoc of the value operand, and casting to the
1682   /// provided type. Use getNode to set a custom SDLoc.
1683   LLVM_ABI SDValue getBitcast(EVT VT, SDValue V);
1684 
1685   /// Return an AddrSpaceCastSDNode.
1686   LLVM_ABI SDValue getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
1687                                     unsigned SrcAS, unsigned DestAS);
1688 
1689   /// Return a freeze using the SDLoc of the value operand.
1690   LLVM_ABI SDValue getFreeze(SDValue V);
1691 
1692   /// Return an AssertAlignSDNode.
1693   LLVM_ABI SDValue getAssertAlign(const SDLoc &DL, SDValue V, Align A);
1694 
1695   /// Swap N1 and N2 if Opcode is a commutative binary opcode
1696   /// and the canonical form expects the opposite order.
1697   LLVM_ABI void canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1,
1698                                              SDValue &N2) const;
1699 
1700   /// Return the specified value casted to
1701   /// the target's desired shift amount type.
1702   LLVM_ABI SDValue getShiftAmountOperand(EVT LHSTy, SDValue Op);
1703 
1704   /// Expands a node with multiple results to an FP or vector libcall. The
1705   /// libcall is expected to take all the operands of the \p Node followed by
1706   /// output pointers for each of the results. \p CallRetResNo can be optionally
1707   /// set to indicate that one of the results comes from the libcall's return
1708   /// value.
1709   LLVM_ABI bool
1710   expandMultipleResultFPLibCall(RTLIB::Libcall LC, SDNode *Node,
1711                                 SmallVectorImpl<SDValue> &Results,
1712                                 std::optional<unsigned> CallRetResNo = {});
1713 
1714   /// Expand the specified \c ISD::VAARG node as the Legalize pass would.
1715   LLVM_ABI SDValue expandVAArg(SDNode *Node);
1716 
1717   /// Expand the specified \c ISD::VACOPY node as the Legalize pass would.
1718   LLVM_ABI SDValue expandVACopy(SDNode *Node);
1719 
1720   /// Return a GlobalAddress of the function from the current module with
1721   /// name matching the given ExternalSymbol. Additionally can provide the
1722   /// matched function.
1723   /// Panic if the function doesn't exist.
1724   LLVM_ABI SDValue getSymbolFunctionGlobalAddress(
1725       SDValue Op, Function **TargetFunction = nullptr);
1726 
1727   /// *Mutate* the specified node in-place to have the
1728   /// specified operands.  If the resultant node already exists in the DAG,
1729   /// this does not modify the specified node, instead it returns the node that
1730   /// already exists.  If the resultant node does not exist in the DAG, the
1731   /// input node is returned.  As a degenerate case, if you specify the same
1732   /// input operands as the node already has, the input node is returned.
1733   LLVM_ABI SDNode *UpdateNodeOperands(SDNode *N, SDValue Op);
1734   LLVM_ABI SDNode *UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2);
1735   LLVM_ABI SDNode *UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
1736                                       SDValue Op3);
1737   LLVM_ABI SDNode *UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
1738                                       SDValue Op3, SDValue Op4);
1739   LLVM_ABI SDNode *UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
1740                                       SDValue Op3, SDValue Op4, SDValue Op5);
1741   LLVM_ABI SDNode *UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops);
1742 
1743   /// Creates a new TokenFactor containing \p Vals. If \p Vals contains 64k
1744   /// values or more, move values into new TokenFactors in 64k-1 blocks, until
1745   /// the final TokenFactor has less than 64k operands.
1746   LLVM_ABI SDValue getTokenFactor(const SDLoc &DL,
1747                                   SmallVectorImpl<SDValue> &Vals);
1748 
1749   /// *Mutate* the specified machine node's memory references to the provided
1750   /// list.
1751   LLVM_ABI void setNodeMemRefs(MachineSDNode *N,
1752                                ArrayRef<MachineMemOperand *> NewMemRefs);
1753 
1754   // Calculate divergence of node \p N based on its operands.
1755   LLVM_ABI bool calculateDivergence(SDNode *N);
1756 
1757   // Propagates the change in divergence to users
1758   LLVM_ABI void updateDivergence(SDNode *N);
1759 
1760   /// These are used for target selectors to *mutate* the
1761   /// specified node to have the specified return type, Target opcode, and
1762   /// operands.  Note that target opcodes are stored as
1763   /// ~TargetOpcode in the node opcode field.  The resultant node is returned.
1764   LLVM_ABI SDNode *SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT);
1765   LLVM_ABI SDNode *SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT,
1766                                 SDValue Op1);
1767   LLVM_ABI SDNode *SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT,
1768                                 SDValue Op1, SDValue Op2);
1769   LLVM_ABI SDNode *SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT,
1770                                 SDValue Op1, SDValue Op2, SDValue Op3);
1771   LLVM_ABI SDNode *SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT,
1772                                 ArrayRef<SDValue> Ops);
1773   LLVM_ABI SDNode *SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT1,
1774                                 EVT VT2);
1775   LLVM_ABI SDNode *SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT1,
1776                                 EVT VT2, ArrayRef<SDValue> Ops);
1777   LLVM_ABI SDNode *SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT1,
1778                                 EVT VT2, EVT VT3, ArrayRef<SDValue> Ops);
1779   LLVM_ABI SDNode *SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT1,
1780                                 EVT VT2, SDValue Op1, SDValue Op2);
1781   LLVM_ABI SDNode *SelectNodeTo(SDNode *N, unsigned MachineOpc, SDVTList VTs,
1782                                 ArrayRef<SDValue> Ops);
1783 
1784   /// This *mutates* the specified node to have the specified
1785   /// return type, opcode, and operands.
1786   LLVM_ABI SDNode *MorphNodeTo(SDNode *N, unsigned Opc, SDVTList VTs,
1787                                ArrayRef<SDValue> Ops);
1788 
1789   /// Mutate the specified strict FP node to its non-strict equivalent,
1790   /// unlinking the node from its chain and dropping the metadata arguments.
1791   /// The node must be a strict FP node.
1792   LLVM_ABI SDNode *mutateStrictFPToFP(SDNode *Node);
1793 
1794   /// These are used for target selectors to create a new node
1795   /// with specified return type(s), MachineInstr opcode, and operands.
1796   ///
1797   /// Note that getMachineNode returns the resultant node.  If there is already
1798   /// a node of the specified opcode and operands, it returns that node instead
1799   /// of the current one.
1800   LLVM_ABI MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl,
1801                                          EVT VT);
1802   LLVM_ABI MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl,
1803                                          EVT VT, SDValue Op1);
1804   LLVM_ABI MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl,
1805                                          EVT VT, SDValue Op1, SDValue Op2);
1806   LLVM_ABI MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl,
1807                                          EVT VT, SDValue Op1, SDValue Op2,
1808                                          SDValue Op3);
1809   LLVM_ABI MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl,
1810                                          EVT VT, ArrayRef<SDValue> Ops);
1811   LLVM_ABI MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl,
1812                                          EVT VT1, EVT VT2, SDValue Op1,
1813                                          SDValue Op2);
1814   LLVM_ABI MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl,
1815                                          EVT VT1, EVT VT2, SDValue Op1,
1816                                          SDValue Op2, SDValue Op3);
1817   LLVM_ABI MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl,
1818                                          EVT VT1, EVT VT2,
1819                                          ArrayRef<SDValue> Ops);
1820   LLVM_ABI MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl,
1821                                          EVT VT1, EVT VT2, EVT VT3, SDValue Op1,
1822                                          SDValue Op2);
1823   LLVM_ABI MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl,
1824                                          EVT VT1, EVT VT2, EVT VT3, SDValue Op1,
1825                                          SDValue Op2, SDValue Op3);
1826   LLVM_ABI MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl,
1827                                          EVT VT1, EVT VT2, EVT VT3,
1828                                          ArrayRef<SDValue> Ops);
1829   LLVM_ABI MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl,
1830                                          ArrayRef<EVT> ResultTys,
1831                                          ArrayRef<SDValue> Ops);
1832   LLVM_ABI MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl,
1833                                          SDVTList VTs, ArrayRef<SDValue> Ops);
1834 
1835   /// A convenience function for creating TargetInstrInfo::EXTRACT_SUBREG nodes.
1836   LLVM_ABI SDValue getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
1837                                           SDValue Operand);
1838 
1839   /// A convenience function for creating TargetInstrInfo::INSERT_SUBREG nodes.
1840   LLVM_ABI SDValue getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
1841                                          SDValue Operand, SDValue Subreg);
1842 
1843   /// Get the specified node if it's already available, or else return NULL.
1844   LLVM_ABI SDNode *getNodeIfExists(unsigned Opcode, SDVTList VTList,
1845                                    ArrayRef<SDValue> Ops,
1846                                    const SDNodeFlags Flags);
1847   LLVM_ABI SDNode *getNodeIfExists(unsigned Opcode, SDVTList VTList,
1848                                    ArrayRef<SDValue> Ops);
1849 
1850   /// Check if a node exists without modifying its flags.
1851   LLVM_ABI bool doesNodeExist(unsigned Opcode, SDVTList VTList,
1852                               ArrayRef<SDValue> Ops);
1853 
1854   /// Creates a SDDbgValue node.
1855   LLVM_ABI SDDbgValue *getDbgValue(DIVariable *Var, DIExpression *Expr,
1856                                    SDNode *N, unsigned R, bool IsIndirect,
1857                                    const DebugLoc &DL, unsigned O);
1858 
1859   /// Creates a constant SDDbgValue node.
1860   LLVM_ABI SDDbgValue *getConstantDbgValue(DIVariable *Var, DIExpression *Expr,
1861                                            const Value *C, const DebugLoc &DL,
1862                                            unsigned O);
1863 
1864   /// Creates a FrameIndex SDDbgValue node.
1865   LLVM_ABI SDDbgValue *getFrameIndexDbgValue(DIVariable *Var,
1866                                              DIExpression *Expr, unsigned FI,
1867                                              bool IsIndirect,
1868                                              const DebugLoc &DL, unsigned O);
1869 
1870   /// Creates a FrameIndex SDDbgValue node.
1871   LLVM_ABI SDDbgValue *getFrameIndexDbgValue(DIVariable *Var,
1872                                              DIExpression *Expr, unsigned FI,
1873                                              ArrayRef<SDNode *> Dependencies,
1874                                              bool IsIndirect,
1875                                              const DebugLoc &DL, unsigned O);
1876 
1877   /// Creates a VReg SDDbgValue node.
1878   LLVM_ABI SDDbgValue *getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
1879                                        Register VReg, bool IsIndirect,
1880                                        const DebugLoc &DL, unsigned O);
1881 
1882   /// Creates a SDDbgValue node from a list of locations.
1883   LLVM_ABI SDDbgValue *getDbgValueList(DIVariable *Var, DIExpression *Expr,
1884                                        ArrayRef<SDDbgOperand> Locs,
1885                                        ArrayRef<SDNode *> Dependencies,
1886                                        bool IsIndirect, const DebugLoc &DL,
1887                                        unsigned O, bool IsVariadic);
1888 
1889   /// Creates a SDDbgLabel node.
1890   LLVM_ABI SDDbgLabel *getDbgLabel(DILabel *Label, const DebugLoc &DL,
1891                                    unsigned O);
1892 
1893   /// Transfer debug values from one node to another, while optionally
1894   /// generating fragment expressions for split-up values. If \p InvalidateDbg
1895   /// is set, debug values are invalidated after they are transferred.
1896   LLVM_ABI void transferDbgValues(SDValue From, SDValue To,
1897                                   unsigned OffsetInBits = 0,
1898                                   unsigned SizeInBits = 0,
1899                                   bool InvalidateDbg = true);
1900 
1901   /// Remove the specified node from the system. If any of its
1902   /// operands then becomes dead, remove them as well. Inform UpdateListener
1903   /// for each node deleted.
1904   LLVM_ABI void RemoveDeadNode(SDNode *N);
1905 
1906   /// This method deletes the unreachable nodes in the
1907   /// given list, and any nodes that become unreachable as a result.
1908   LLVM_ABI void RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes);
1909 
1910   /// Modify anything using 'From' to use 'To' instead.
1911   /// This can cause recursive merging of nodes in the DAG.  Use the first
1912   /// version if 'From' is known to have a single result, use the second
1913   /// if you have two nodes with identical results (or if 'To' has a superset
1914   /// of the results of 'From'), use the third otherwise.
1915   ///
1916   /// These methods all take an optional UpdateListener, which (if not null) is
1917   /// informed about nodes that are deleted and modified due to recursive
1918   /// changes in the dag.
1919   ///
1920   /// These functions only replace all existing uses. It's possible that as
1921   /// these replacements are being performed, CSE may cause the From node
1922   /// to be given new uses. These new uses of From are left in place, and
1923   /// not automatically transferred to To.
1924   ///
1925   LLVM_ABI void ReplaceAllUsesWith(SDValue From, SDValue To);
1926   LLVM_ABI void ReplaceAllUsesWith(SDNode *From, SDNode *To);
1927   LLVM_ABI void ReplaceAllUsesWith(SDNode *From, const SDValue *To);
1928 
1929   /// Replace any uses of From with To, leaving
1930   /// uses of other values produced by From.getNode() alone.
1931   LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To);
1932 
1933   /// Like ReplaceAllUsesOfValueWith, but for multiple values at once.
1934   /// This correctly handles the case where
1935   /// there is an overlap between the From values and the To values.
1936   LLVM_ABI void ReplaceAllUsesOfValuesWith(const SDValue *From,
1937                                            const SDValue *To, unsigned Num);
1938 
1939   /// If an existing load has uses of its chain, create a token factor node with
1940   /// that chain and the new memory node's chain and update users of the old
1941   /// chain to the token factor. This ensures that the new memory node will have
1942   /// the same relative memory dependency position as the old load. Returns the
1943   /// new merged load chain.
1944   LLVM_ABI SDValue makeEquivalentMemoryOrdering(SDValue OldChain,
1945                                                 SDValue NewMemOpChain);
1946 
1947   /// If an existing load has uses of its chain, create a token factor node with
1948   /// that chain and the new memory node's chain and update users of the old
1949   /// chain to the token factor. This ensures that the new memory node will have
1950   /// the same relative memory dependency position as the old load. Returns the
1951   /// new merged load chain.
1952   LLVM_ABI SDValue makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
1953                                                 SDValue NewMemOp);
1954 
1955   /// Topological-sort the AllNodes list and a
1956   /// assign a unique node id for each node in the DAG based on their
1957   /// topological order. Returns the number of nodes.
1958   LLVM_ABI unsigned AssignTopologicalOrder();
1959 
1960   /// Move node N in the AllNodes list to be immediately
1961   /// before the given iterator Position. This may be used to update the
1962   /// topological ordering when the list of nodes is modified.
1963   void RepositionNode(allnodes_iterator Position, SDNode *N) {
1964     AllNodes.insert(Position, AllNodes.remove(N));
1965   }
1966 
1967   /// Add a dbg_value SDNode. If SD is non-null that means the
1968   /// value is produced by SD.
1969   LLVM_ABI void AddDbgValue(SDDbgValue *DB, bool isParameter);
1970 
1971   /// Add a dbg_label SDNode.
1972   LLVM_ABI void AddDbgLabel(SDDbgLabel *DB);
1973 
1974   /// Get the debug values which reference the given SDNode.
1975   ArrayRef<SDDbgValue*> GetDbgValues(const SDNode* SD) const {
1976     return DbgInfo->getSDDbgValues(SD);
1977   }
1978 
1979 public:
1980   /// Return true if there are any SDDbgValue nodes associated
1981   /// with this SelectionDAG.
1982   bool hasDebugValues() const { return !DbgInfo->empty(); }
1983 
1984   SDDbgInfo::DbgIterator DbgBegin() const { return DbgInfo->DbgBegin(); }
1985   SDDbgInfo::DbgIterator DbgEnd() const  { return DbgInfo->DbgEnd(); }
1986 
1987   SDDbgInfo::DbgIterator ByvalParmDbgBegin() const {
1988     return DbgInfo->ByvalParmDbgBegin();
1989   }
1990   SDDbgInfo::DbgIterator ByvalParmDbgEnd() const {
1991     return DbgInfo->ByvalParmDbgEnd();
1992   }
1993 
1994   SDDbgInfo::DbgLabelIterator DbgLabelBegin() const {
1995     return DbgInfo->DbgLabelBegin();
1996   }
1997   SDDbgInfo::DbgLabelIterator DbgLabelEnd() const {
1998     return DbgInfo->DbgLabelEnd();
1999   }
2000 
2001   /// To be invoked on an SDNode that is slated to be erased. This
2002   /// function mirrors \c llvm::salvageDebugInfo.
2003   LLVM_ABI void salvageDebugInfo(SDNode &N);
2004 
2005   LLVM_ABI void dump() const;
2006 
2007   /// In most cases this function returns the ABI alignment for a given type,
2008   /// except for illegal vector types where the alignment exceeds that of the
2009   /// stack. In such cases we attempt to break the vector down to a legal type
2010   /// and return the ABI alignment for that instead.
2011   LLVM_ABI Align getReducedAlign(EVT VT, bool UseABI);
2012 
2013   /// Create a stack temporary based on the size in bytes and the alignment
2014   LLVM_ABI SDValue CreateStackTemporary(TypeSize Bytes, Align Alignment);
2015 
2016   /// Create a stack temporary, suitable for holding the specified value type.
2017   /// If minAlign is specified, the slot size will have at least that alignment.
2018   LLVM_ABI SDValue CreateStackTemporary(EVT VT, unsigned minAlign = 1);
2019 
2020   /// Create a stack temporary suitable for holding either of the specified
2021   /// value types.
2022   LLVM_ABI SDValue CreateStackTemporary(EVT VT1, EVT VT2);
2023 
2024   LLVM_ABI SDValue FoldSymbolOffset(unsigned Opcode, EVT VT,
2025                                     const GlobalAddressSDNode *GA,
2026                                     const SDNode *N2);
2027 
2028   LLVM_ABI SDValue FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
2029                                           EVT VT, ArrayRef<SDValue> Ops,
2030                                           SDNodeFlags Flags = SDNodeFlags());
2031 
2032   /// Fold floating-point operations when all operands are constants and/or
2033   /// undefined.
2034   LLVM_ABI SDValue foldConstantFPMath(unsigned Opcode, const SDLoc &DL, EVT VT,
2035                                       ArrayRef<SDValue> Ops);
2036 
2037   /// Fold BUILD_VECTOR of constants/undefs to the destination type
2038   /// BUILD_VECTOR of constants/undefs elements.
2039   LLVM_ABI SDValue FoldConstantBuildVector(BuildVectorSDNode *BV,
2040                                            const SDLoc &DL, EVT DstEltVT);
2041 
2042   /// Constant fold a setcc to true or false.
2043   LLVM_ABI SDValue FoldSetCC(EVT VT, SDValue N1, SDValue N2, ISD::CondCode Cond,
2044                              const SDLoc &dl);
2045 
2046   /// Return true if the sign bit of Op is known to be zero.
2047   /// We use this predicate to simplify operations downstream.
2048   LLVM_ABI bool SignBitIsZero(SDValue Op, unsigned Depth = 0) const;
2049 
2050   /// Return true if 'Op & Mask' is known to be zero.  We
2051   /// use this predicate to simplify operations downstream.  Op and Mask are
2052   /// known to be the same type.
2053   LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask,
2054                                   unsigned Depth = 0) const;
2055 
2056   /// Return true if 'Op & Mask' is known to be zero in DemandedElts.  We
2057   /// use this predicate to simplify operations downstream.  Op and Mask are
2058   /// known to be the same type.
2059   LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask,
2060                                   const APInt &DemandedElts,
2061                                   unsigned Depth = 0) const;
2062 
2063   /// Return true if 'Op' is known to be zero in DemandedElts.  We
2064   /// use this predicate to simplify operations downstream.
2065   LLVM_ABI bool MaskedVectorIsZero(SDValue Op, const APInt &DemandedElts,
2066                                    unsigned Depth = 0) const;
2067 
2068   /// Return true if '(Op & Mask) == Mask'.
2069   /// Op and Mask are known to be the same type.
2070   LLVM_ABI bool MaskedValueIsAllOnes(SDValue Op, const APInt &Mask,
2071                                      unsigned Depth = 0) const;
2072 
2073   /// For each demanded element of a vector, see if it is known to be zero.
2074   LLVM_ABI APInt computeVectorKnownZeroElements(SDValue Op,
2075                                                 const APInt &DemandedElts,
2076                                                 unsigned Depth = 0) const;
2077 
2078   /// Determine which bits of Op are known to be either zero or one and return
2079   /// them in Known. For vectors, the known bits are those that are shared by
2080   /// every vector element.
2081   /// Targets can implement the computeKnownBitsForTargetNode method in the
2082   /// TargetLowering class to allow target nodes to be understood.
2083   LLVM_ABI KnownBits computeKnownBits(SDValue Op, unsigned Depth = 0) const;
2084 
2085   /// Determine which bits of Op are known to be either zero or one and return
2086   /// them in Known. The DemandedElts argument allows us to only collect the
2087   /// known bits that are shared by the requested vector elements.
2088   /// Targets can implement the computeKnownBitsForTargetNode method in the
2089   /// TargetLowering class to allow target nodes to be understood.
2090   LLVM_ABI KnownBits computeKnownBits(SDValue Op, const APInt &DemandedElts,
2091                                       unsigned Depth = 0) const;
2092 
2093   /// Used to represent the possible overflow behavior of an operation.
2094   /// Never: the operation cannot overflow.
2095   /// Always: the operation will always overflow.
2096   /// Sometime: the operation may or may not overflow.
2097   enum OverflowKind {
2098     OFK_Never,
2099     OFK_Sometime,
2100     OFK_Always,
2101   };
2102 
2103   /// Determine if the result of the signed addition of 2 nodes can overflow.
2104   LLVM_ABI OverflowKind computeOverflowForSignedAdd(SDValue N0,
2105                                                     SDValue N1) const;
2106 
2107   /// Determine if the result of the unsigned addition of 2 nodes can overflow.
2108   LLVM_ABI OverflowKind computeOverflowForUnsignedAdd(SDValue N0,
2109                                                       SDValue N1) const;
2110 
2111   /// Determine if the result of the addition of 2 nodes can overflow.
2112   OverflowKind computeOverflowForAdd(bool IsSigned, SDValue N0,
2113                                      SDValue N1) const {
2114     return IsSigned ? computeOverflowForSignedAdd(N0, N1)
2115                     : computeOverflowForUnsignedAdd(N0, N1);
2116   }
2117 
2118   /// Determine if the result of the addition of 2 nodes can never overflow.
2119   bool willNotOverflowAdd(bool IsSigned, SDValue N0, SDValue N1) const {
2120     return computeOverflowForAdd(IsSigned, N0, N1) == OFK_Never;
2121   }
2122 
2123   /// Determine if the result of the signed sub of 2 nodes can overflow.
2124   LLVM_ABI OverflowKind computeOverflowForSignedSub(SDValue N0,
2125                                                     SDValue N1) const;
2126 
2127   /// Determine if the result of the unsigned sub of 2 nodes can overflow.
2128   LLVM_ABI OverflowKind computeOverflowForUnsignedSub(SDValue N0,
2129                                                       SDValue N1) const;
2130 
2131   /// Determine if the result of the sub of 2 nodes can overflow.
2132   OverflowKind computeOverflowForSub(bool IsSigned, SDValue N0,
2133                                      SDValue N1) const {
2134     return IsSigned ? computeOverflowForSignedSub(N0, N1)
2135                     : computeOverflowForUnsignedSub(N0, N1);
2136   }
2137 
2138   /// Determine if the result of the sub of 2 nodes can never overflow.
2139   bool willNotOverflowSub(bool IsSigned, SDValue N0, SDValue N1) const {
2140     return computeOverflowForSub(IsSigned, N0, N1) == OFK_Never;
2141   }
2142 
2143   /// Determine if the result of the signed mul of 2 nodes can overflow.
2144   LLVM_ABI OverflowKind computeOverflowForSignedMul(SDValue N0,
2145                                                     SDValue N1) const;
2146 
2147   /// Determine if the result of the unsigned mul of 2 nodes can overflow.
2148   LLVM_ABI OverflowKind computeOverflowForUnsignedMul(SDValue N0,
2149                                                       SDValue N1) const;
2150 
2151   /// Determine if the result of the mul of 2 nodes can overflow.
2152   OverflowKind computeOverflowForMul(bool IsSigned, SDValue N0,
2153                                      SDValue N1) const {
2154     return IsSigned ? computeOverflowForSignedMul(N0, N1)
2155                     : computeOverflowForUnsignedMul(N0, N1);
2156   }
2157 
2158   /// Determine if the result of the mul of 2 nodes can never overflow.
2159   bool willNotOverflowMul(bool IsSigned, SDValue N0, SDValue N1) const {
2160     return computeOverflowForMul(IsSigned, N0, N1) == OFK_Never;
2161   }
2162 
2163   /// Test if the given value is known to have exactly one bit set. This differs
2164   /// from computeKnownBits in that it doesn't necessarily determine which bit
2165   /// is set.
2166   LLVM_ABI bool isKnownToBeAPowerOfTwo(SDValue Val, unsigned Depth = 0) const;
2167 
2168   /// Test if the given _fp_ value is known to be an integer power-of-2, either
2169   /// positive or negative.
2170   LLVM_ABI bool isKnownToBeAPowerOfTwoFP(SDValue Val, unsigned Depth = 0) const;
2171 
2172   /// Return the number of times the sign bit of the register is replicated into
2173   /// the other bits. We know that at least 1 bit is always equal to the sign
2174   /// bit (itself), but other cases can give us information. For example,
2175   /// immediately after an "SRA X, 2", we know that the top 3 bits are all equal
2176   /// to each other, so we return 3. Targets can implement the
2177   /// ComputeNumSignBitsForTarget method in the TargetLowering class to allow
2178   /// target nodes to be understood.
2179   LLVM_ABI unsigned ComputeNumSignBits(SDValue Op, unsigned Depth = 0) const;
2180 
2181   /// Return the number of times the sign bit of the register is replicated into
2182   /// the other bits. We know that at least 1 bit is always equal to the sign
2183   /// bit (itself), but other cases can give us information. For example,
2184   /// immediately after an "SRA X, 2", we know that the top 3 bits are all equal
2185   /// to each other, so we return 3. The DemandedElts argument allows
2186   /// us to only collect the minimum sign bits of the requested vector elements.
2187   /// Targets can implement the ComputeNumSignBitsForTarget method in the
2188   /// TargetLowering class to allow target nodes to be understood.
2189   LLVM_ABI unsigned ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
2190                                        unsigned Depth = 0) const;
2191 
2192   /// Get the upper bound on bit size for this Value \p Op as a signed integer.
2193   /// i.e.  x == sext(trunc(x to MaxSignedBits) to bitwidth(x)).
2194   /// Similar to the APInt::getSignificantBits function.
2195   /// Helper wrapper to ComputeNumSignBits.
2196   LLVM_ABI unsigned ComputeMaxSignificantBits(SDValue Op,
2197                                               unsigned Depth = 0) const;
2198 
2199   /// Get the upper bound on bit size for this Value \p Op as a signed integer.
2200   /// i.e.  x == sext(trunc(x to MaxSignedBits) to bitwidth(x)).
2201   /// Similar to the APInt::getSignificantBits function.
2202   /// Helper wrapper to ComputeNumSignBits.
2203   LLVM_ABI unsigned ComputeMaxSignificantBits(SDValue Op,
2204                                               const APInt &DemandedElts,
2205                                               unsigned Depth = 0) const;
2206 
2207   /// Return true if this function can prove that \p Op is never poison
2208   /// and, if \p PoisonOnly is false, does not have undef bits.
2209   LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(SDValue Op,
2210                                                  bool PoisonOnly = false,
2211                                                  unsigned Depth = 0) const;
2212 
2213   /// Return true if this function can prove that \p Op is never poison
2214   /// and, if \p PoisonOnly is false, does not have undef bits. The DemandedElts
2215   /// argument limits the check to the requested vector elements.
2216   LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(SDValue Op,
2217                                                  const APInt &DemandedElts,
2218                                                  bool PoisonOnly = false,
2219                                                  unsigned Depth = 0) const;
2220 
2221   /// Return true if this function can prove that \p Op is never poison.
2222   bool isGuaranteedNotToBePoison(SDValue Op, unsigned Depth = 0) const {
2223     return isGuaranteedNotToBeUndefOrPoison(Op, /*PoisonOnly*/ true, Depth);
2224   }
2225 
2226   /// Return true if this function can prove that \p Op is never poison. The
2227   /// DemandedElts argument limits the check to the requested vector elements.
2228   bool isGuaranteedNotToBePoison(SDValue Op, const APInt &DemandedElts,
2229                                  unsigned Depth = 0) const {
2230     return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts,
2231                                             /*PoisonOnly*/ true, Depth);
2232   }
2233 
2234   /// Return true if Op can create undef or poison from non-undef & non-poison
2235   /// operands. The DemandedElts argument limits the check to the requested
2236   /// vector elements.
2237   ///
2238   /// \p ConsiderFlags controls whether poison producing flags on the
2239   /// instruction are considered.  This can be used to see if the instruction
2240   /// could still introduce undef or poison even without poison generating flags
2241   /// which might be on the instruction.  (i.e. could the result of
2242   /// Op->dropPoisonGeneratingFlags() still create poison or undef)
2243   LLVM_ABI bool canCreateUndefOrPoison(SDValue Op, const APInt &DemandedElts,
2244                                        bool PoisonOnly = false,
2245                                        bool ConsiderFlags = true,
2246                                        unsigned Depth = 0) const;
2247 
2248   /// Return true if Op can create undef or poison from non-undef & non-poison
2249   /// operands.
2250   ///
2251   /// \p ConsiderFlags controls whether poison producing flags on the
2252   /// instruction are considered.  This can be used to see if the instruction
2253   /// could still introduce undef or poison even without poison generating flags
2254   /// which might be on the instruction.  (i.e. could the result of
2255   /// Op->dropPoisonGeneratingFlags() still create poison or undef)
2256   LLVM_ABI bool canCreateUndefOrPoison(SDValue Op, bool PoisonOnly = false,
2257                                        bool ConsiderFlags = true,
2258                                        unsigned Depth = 0) const;
2259 
2260   /// Return true if the specified operand is an ISD::OR or ISD::XOR node
2261   /// that can be treated as an ISD::ADD node.
2262   /// or(x,y) == add(x,y) iff haveNoCommonBitsSet(x,y)
2263   /// xor(x,y) == add(x,y) iff isMinSignedConstant(y) && !NoWrap
2264   /// If \p NoWrap is true, this will not match ISD::XOR.
2265   LLVM_ABI bool isADDLike(SDValue Op, bool NoWrap = false) const;
2266 
2267   /// Return true if the specified operand is an ISD::ADD with a ConstantSDNode
2268   /// on the right-hand side, or if it is an ISD::OR with a ConstantSDNode that
2269   /// is guaranteed to have the same semantics as an ADD. This handles the
2270   /// equivalence:
2271   ///     X|Cst == X+Cst iff X&Cst = 0.
2272   LLVM_ABI bool isBaseWithConstantOffset(SDValue Op) const;
2273 
2274   /// Test whether the given SDValue (or all elements of it, if it is a
2275   /// vector) is known to never be NaN in \p DemandedElts. If \p SNaN is true,
2276   /// returns if \p Op is known to never be a signaling NaN (it may still be a
2277   /// qNaN).
2278   LLVM_ABI bool isKnownNeverNaN(SDValue Op, const APInt &DemandedElts,
2279                                 bool SNaN = false, unsigned Depth = 0) const;
2280 
2281   /// Test whether the given SDValue (or all elements of it, if it is a
2282   /// vector) is known to never be NaN. If \p SNaN is true, returns if \p Op is
2283   /// known to never be a signaling NaN (it may still be a qNaN).
2284   LLVM_ABI bool isKnownNeverNaN(SDValue Op, bool SNaN = false,
2285                                 unsigned Depth = 0) const;
2286 
2287   /// \returns true if \p Op is known to never be a signaling NaN in \p
2288   /// DemandedElts.
2289   bool isKnownNeverSNaN(SDValue Op, const APInt &DemandedElts,
2290                         unsigned Depth = 0) const {
2291     return isKnownNeverNaN(Op, DemandedElts, true, Depth);
2292   }
2293 
2294   /// \returns true if \p Op is known to never be a signaling NaN.
2295   bool isKnownNeverSNaN(SDValue Op, unsigned Depth = 0) const {
2296     return isKnownNeverNaN(Op, true, Depth);
2297   }
2298 
2299   /// Test whether the given floating point SDValue is known to never be
2300   /// positive or negative zero.
2301   LLVM_ABI bool isKnownNeverZeroFloat(SDValue Op) const;
2302 
2303   /// Test whether the given SDValue is known to contain non-zero value(s).
2304   LLVM_ABI bool isKnownNeverZero(SDValue Op, unsigned Depth = 0) const;
2305 
2306   /// Test whether the given float value is known to be positive. +0.0, +inf and
2307   /// +nan are considered positive, -0.0, -inf and -nan are not.
2308   LLVM_ABI bool cannotBeOrderedNegativeFP(SDValue Op) const;
2309 
2310   /// Test whether two SDValues are known to compare equal. This
2311   /// is true if they are the same value, or if one is negative zero and the
2312   /// other positive zero.
2313   LLVM_ABI bool isEqualTo(SDValue A, SDValue B) const;
2314 
2315   /// Return true if A and B have no common bits set. As an example, this can
2316   /// allow an 'add' to be transformed into an 'or'.
2317   LLVM_ABI bool haveNoCommonBitsSet(SDValue A, SDValue B) const;
2318 
2319   /// Test whether \p V has a splatted value for all the demanded elements.
2320   ///
2321   /// On success \p UndefElts will indicate the elements that have UNDEF
2322   /// values instead of the splat value, this is only guaranteed to be correct
2323   /// for \p DemandedElts.
2324   ///
2325   /// NOTE: The function will return true for a demanded splat of UNDEF values.
2326   LLVM_ABI bool isSplatValue(SDValue V, const APInt &DemandedElts,
2327                              APInt &UndefElts, unsigned Depth = 0) const;
2328 
2329   /// Test whether \p V has a splatted value.
2330   LLVM_ABI bool isSplatValue(SDValue V, bool AllowUndefs = false) const;
2331 
2332   /// If V is a splatted value, return the source vector and its splat index.
2333   LLVM_ABI SDValue getSplatSourceVector(SDValue V, int &SplatIndex);
2334 
2335   /// If V is a splat vector, return its scalar source operand by extracting
2336   /// that element from the source vector. If LegalTypes is true, this method
2337   /// may only return a legally-typed splat value. If it cannot legalize the
2338   /// splatted value it will return SDValue().
2339   LLVM_ABI SDValue getSplatValue(SDValue V, bool LegalTypes = false);
2340 
2341   /// If a SHL/SRA/SRL node \p V has shift amounts that are all less than the
2342   /// element bit-width of the shift node, return the valid constant range.
2343   LLVM_ABI std::optional<ConstantRange>
2344   getValidShiftAmountRange(SDValue V, const APInt &DemandedElts,
2345                            unsigned Depth) const;
2346 
2347   /// If a SHL/SRA/SRL node \p V has a uniform shift amount
2348   /// that is less than the element bit-width of the shift node, return it.
2349   LLVM_ABI std::optional<uint64_t>
2350   getValidShiftAmount(SDValue V, const APInt &DemandedElts,
2351                       unsigned Depth = 0) const;
2352 
2353   /// If a SHL/SRA/SRL node \p V has a uniform shift amount
2354   /// that is less than the element bit-width of the shift node, return it.
2355   LLVM_ABI std::optional<uint64_t>
2356   getValidShiftAmount(SDValue V, unsigned Depth = 0) const;
2357 
2358   /// If a SHL/SRA/SRL node \p V has shift amounts that are all less than the
2359   /// element bit-width of the shift node, return the minimum possible value.
2360   LLVM_ABI std::optional<uint64_t>
2361   getValidMinimumShiftAmount(SDValue V, const APInt &DemandedElts,
2362                              unsigned Depth = 0) const;
2363 
2364   /// If a SHL/SRA/SRL node \p V has shift amounts that are all less than the
2365   /// element bit-width of the shift node, return the minimum possible value.
2366   LLVM_ABI std::optional<uint64_t>
2367   getValidMinimumShiftAmount(SDValue V, unsigned Depth = 0) const;
2368 
2369   /// If a SHL/SRA/SRL node \p V has shift amounts that are all less than the
2370   /// element bit-width of the shift node, return the maximum possible value.
2371   LLVM_ABI std::optional<uint64_t>
2372   getValidMaximumShiftAmount(SDValue V, const APInt &DemandedElts,
2373                              unsigned Depth = 0) const;
2374 
2375   /// If a SHL/SRA/SRL node \p V has shift amounts that are all less than the
2376   /// element bit-width of the shift node, return the maximum possible value.
2377   LLVM_ABI std::optional<uint64_t>
2378   getValidMaximumShiftAmount(SDValue V, unsigned Depth = 0) const;
2379 
2380   /// Match a binop + shuffle pyramid that represents a horizontal reduction
2381   /// over the elements of a vector starting from the EXTRACT_VECTOR_ELT node /p
2382   /// Extract. The reduction must use one of the opcodes listed in /p
2383   /// CandidateBinOps and on success /p BinOp will contain the matching opcode.
2384   /// Returns the vector that is being reduced on, or SDValue() if a reduction
2385   /// was not matched. If \p AllowPartials is set then in the case of a
2386   /// reduction pattern that only matches the first few stages, the extracted
2387   /// subvector of the start of the reduction is returned.
2388   LLVM_ABI SDValue matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
2389                                        ArrayRef<ISD::NodeType> CandidateBinOps,
2390                                        bool AllowPartials = false);
2391 
2392   /// Utility function used by legalize and lowering to
2393   /// "unroll" a vector operation by splitting out the scalars and operating
2394   /// on each element individually.  If the ResNE is 0, fully unroll the vector
2395   /// op. If ResNE is less than the width of the vector op, unroll up to ResNE.
2396   /// If the  ResNE is greater than the width of the vector op, unroll the
2397   /// vector op and fill the end of the resulting vector with UNDEFS.
2398   LLVM_ABI SDValue UnrollVectorOp(SDNode *N, unsigned ResNE = 0);
2399 
2400   /// Like UnrollVectorOp(), but for the [US](ADD|SUB|MUL)O family of opcodes.
2401   /// This is a separate function because those opcodes have two results.
2402   LLVM_ABI std::pair<SDValue, SDValue>
2403   UnrollVectorOverflowOp(SDNode *N, unsigned ResNE = 0);
2404 
2405   /// Return true if loads are next to each other and can be
2406   /// merged. Check that both are nonvolatile and if LD is loading
2407   /// 'Bytes' bytes from a location that is 'Dist' units away from the
2408   /// location that the 'Base' load is loading from.
2409   LLVM_ABI bool areNonVolatileConsecutiveLoads(LoadSDNode *LD, LoadSDNode *Base,
2410                                                unsigned Bytes, int Dist) const;
2411 
2412   /// Infer alignment of a load / store address. Return std::nullopt if it
2413   /// cannot be inferred.
2414   LLVM_ABI MaybeAlign InferPtrAlign(SDValue Ptr) const;
2415 
2416   /// Split the scalar node with EXTRACT_ELEMENT using the provided VTs and
2417   /// return the low/high part.
2418   LLVM_ABI std::pair<SDValue, SDValue> SplitScalar(const SDValue &N,
2419                                                    const SDLoc &DL,
2420                                                    const EVT &LoVT,
2421                                                    const EVT &HiVT);
2422 
2423   /// Compute the VTs needed for the low/hi parts of a type
2424   /// which is split (or expanded) into two not necessarily identical pieces.
2425   LLVM_ABI std::pair<EVT, EVT> GetSplitDestVTs(const EVT &VT) const;
2426 
2427   /// Compute the VTs needed for the low/hi parts of a type, dependent on an
2428   /// enveloping VT that has been split into two identical pieces. Sets the
2429   /// HisIsEmpty flag when hi type has zero storage size.
2430   LLVM_ABI std::pair<EVT, EVT> GetDependentSplitDestVTs(const EVT &VT,
2431                                                         const EVT &EnvVT,
2432                                                         bool *HiIsEmpty) const;
2433 
2434   /// Split the vector with EXTRACT_SUBVECTOR using the provided
2435   /// VTs and return the low/high part.
2436   LLVM_ABI std::pair<SDValue, SDValue> SplitVector(const SDValue &N,
2437                                                    const SDLoc &DL,
2438                                                    const EVT &LoVT,
2439                                                    const EVT &HiVT);
2440 
2441   /// Split the vector with EXTRACT_SUBVECTOR and return the low/high part.
2442   std::pair<SDValue, SDValue> SplitVector(const SDValue &N, const SDLoc &DL) {
2443     EVT LoVT, HiVT;
2444     std::tie(LoVT, HiVT) = GetSplitDestVTs(N.getValueType());
2445     return SplitVector(N, DL, LoVT, HiVT);
2446   }
2447 
2448   /// Split the explicit vector length parameter of a VP operation.
2449   LLVM_ABI std::pair<SDValue, SDValue> SplitEVL(SDValue N, EVT VecVT,
2450                                                 const SDLoc &DL);
2451 
2452   /// Split the node's operand with EXTRACT_SUBVECTOR and
2453   /// return the low/high part.
2454   std::pair<SDValue, SDValue> SplitVectorOperand(const SDNode *N, unsigned OpNo)
2455   {
2456     return SplitVector(N->getOperand(OpNo), SDLoc(N));
2457   }
2458 
2459   /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
2460   LLVM_ABI SDValue WidenVector(const SDValue &N, const SDLoc &DL);
2461 
2462   /// Append the extracted elements from Start to Count out of the vector Op in
2463   /// Args. If Count is 0, all of the elements will be extracted. The extracted
2464   /// elements will have type EVT if it is provided, and otherwise their type
2465   /// will be Op's element type.
2466   LLVM_ABI void ExtractVectorElements(SDValue Op,
2467                                       SmallVectorImpl<SDValue> &Args,
2468                                       unsigned Start = 0, unsigned Count = 0,
2469                                       EVT EltVT = EVT());
2470 
2471   /// Compute the default alignment value for the given type.
2472   LLVM_ABI Align getEVTAlign(EVT MemoryVT) const;
2473 
2474   /// Test whether the given value is a constant int or similar node.
2475   LLVM_ABI bool
2476   isConstantIntBuildVectorOrConstantInt(SDValue N,
2477                                         bool AllowOpaques = true) const;
2478 
2479   /// Test whether the given value is a constant FP or similar node.
2480   LLVM_ABI bool isConstantFPBuildVectorOrConstantFP(SDValue N) const;
2481 
2482   /// \returns true if \p N is any kind of constant or build_vector of
2483   /// constants, int or float. If a vector, it may not necessarily be a splat.
2484   inline bool isConstantValueOfAnyType(SDValue N) const {
2485     return isConstantIntBuildVectorOrConstantInt(N) ||
2486            isConstantFPBuildVectorOrConstantFP(N);
2487   }
2488 
2489   /// Check if a value \op N is a constant using the target's BooleanContent for
2490   /// its type.
2491   LLVM_ABI std::optional<bool> isBoolConstant(SDValue N) const;
2492 
2493   /// Set CallSiteInfo to be associated with Node.
2494   void addCallSiteInfo(const SDNode *Node, CallSiteInfo &&CallInfo) {
2495     SDEI[Node].CSInfo = std::move(CallInfo);
2496   }
2497   /// Return CallSiteInfo associated with Node, or a default if none exists.
2498   CallSiteInfo getCallSiteInfo(const SDNode *Node) {
2499     auto I = SDEI.find(Node);
2500     return I != SDEI.end() ? std::move(I->second).CSInfo : CallSiteInfo();
2501   }
2502   /// Set HeapAllocSite to be associated with Node.
2503   void addHeapAllocSite(const SDNode *Node, MDNode *MD) {
2504     SDEI[Node].HeapAllocSite = MD;
2505   }
2506   /// Return HeapAllocSite associated with Node, or nullptr if none exists.
2507   MDNode *getHeapAllocSite(const SDNode *Node) const {
2508     auto I = SDEI.find(Node);
2509     return I != SDEI.end() ? I->second.HeapAllocSite : nullptr;
2510   }
2511   /// Set PCSections to be associated with Node.
2512   void addPCSections(const SDNode *Node, MDNode *MD) {
2513     SDEI[Node].PCSections = MD;
2514   }
2515   /// Set MMRAMetadata to be associated with Node.
2516   void addMMRAMetadata(const SDNode *Node, MDNode *MMRA) {
2517     SDEI[Node].MMRA = MMRA;
2518   }
2519   /// Return PCSections associated with Node, or nullptr if none exists.
2520   MDNode *getPCSections(const SDNode *Node) const {
2521     auto It = SDEI.find(Node);
2522     return It != SDEI.end() ? It->second.PCSections : nullptr;
2523   }
2524   /// Return the MMRA MDNode associated with Node, or nullptr if none
2525   /// exists.
2526   MDNode *getMMRAMetadata(const SDNode *Node) const {
2527     auto It = SDEI.find(Node);
2528     return It != SDEI.end() ? It->second.MMRA : nullptr;
2529   }
2530   /// Set CalledGlobal to be associated with Node.
2531   void addCalledGlobal(const SDNode *Node, const GlobalValue *GV,
2532                        unsigned OpFlags) {
2533     SDEI[Node].CalledGlobal = {GV, OpFlags};
2534   }
2535   /// Return CalledGlobal associated with Node, or a nullopt if none exists.
2536   std::optional<CalledGlobalInfo> getCalledGlobal(const SDNode *Node) {
2537     auto I = SDEI.find(Node);
2538     return I != SDEI.end()
2539                ? std::make_optional(std::move(I->second).CalledGlobal)
2540                : std::nullopt;
2541   }
2542   /// Set NoMergeSiteInfo to be associated with Node if NoMerge is true.
2543   void addNoMergeSiteInfo(const SDNode *Node, bool NoMerge) {
2544     if (NoMerge)
2545       SDEI[Node].NoMerge = NoMerge;
2546   }
2547   /// Return NoMerge info associated with Node.
2548   bool getNoMergeSiteInfo(const SDNode *Node) const {
2549     auto I = SDEI.find(Node);
2550     return I != SDEI.end() ? I->second.NoMerge : false;
2551   }
2552 
2553   /// Copy extra info associated with one node to another.
2554   LLVM_ABI void copyExtraInfo(SDNode *From, SDNode *To);
2555 
2556   /// Return the current function's default denormal handling kind for the given
2557   /// floating point type.
2558   DenormalMode getDenormalMode(EVT VT) const {
2559     return MF->getDenormalMode(VT.getFltSemantics());
2560   }
2561 
2562   LLVM_ABI bool shouldOptForSize() const;
2563 
2564   /// Get the (commutative) neutral element for the given opcode, if it exists.
2565   LLVM_ABI SDValue getNeutralElement(unsigned Opcode, const SDLoc &DL, EVT VT,
2566                                      SDNodeFlags Flags);
2567 
2568   /// Some opcodes may create immediate undefined behavior when used with some
2569   /// values (integer division-by-zero for example). Therefore, these operations
2570   /// are not generally safe to move around or change.
2571   bool isSafeToSpeculativelyExecute(unsigned Opcode) const {
2572     switch (Opcode) {
2573     case ISD::SDIV:
2574     case ISD::SREM:
2575     case ISD::SDIVREM:
2576     case ISD::UDIV:
2577     case ISD::UREM:
2578     case ISD::UDIVREM:
2579       return false;
2580     default:
2581       return true;
2582     }
2583   }
2584 
2585   /// Check if the provided node is save to speculatively executed given its
2586   /// current arguments. So, while `udiv` the opcode is not safe to
2587   /// speculatively execute, a given `udiv` node may be if the denominator is
2588   /// known nonzero.
2589   bool isSafeToSpeculativelyExecuteNode(const SDNode *N) const {
2590     switch (N->getOpcode()) {
2591     case ISD::UDIV:
2592       return isKnownNeverZero(N->getOperand(1));
2593     default:
2594       return isSafeToSpeculativelyExecute(N->getOpcode());
2595     }
2596   }
2597 
2598   LLVM_ABI SDValue makeStateFunctionCall(unsigned LibFunc, SDValue Ptr,
2599                                          SDValue InChain, const SDLoc &DLoc);
2600 
2601 private:
2602 #ifndef NDEBUG
2603   void verifyNode(SDNode *N) const;
2604 #endif
2605   void InsertNode(SDNode *N);
2606   bool RemoveNodeFromCSEMaps(SDNode *N);
2607   void AddModifiedNodeToCSEMaps(SDNode *N);
2608   SDNode *FindModifiedNodeSlot(SDNode *N, SDValue Op, void *&InsertPos);
2609   SDNode *FindModifiedNodeSlot(SDNode *N, SDValue Op1, SDValue Op2,
2610                                void *&InsertPos);
2611   SDNode *FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
2612                                void *&InsertPos);
2613   SDNode *UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &loc);
2614 
2615   void DeleteNodeNotInCSEMaps(SDNode *N);
2616   void DeallocateNode(SDNode *N);
2617 
2618   void allnodes_clear();
2619 
2620   /// Look up the node specified by ID in CSEMap.  If it exists, return it.  If
2621   /// not, return the insertion token that will make insertion faster.  This
2622   /// overload is for nodes other than Constant or ConstantFP, use the other one
2623   /// for those.
2624   SDNode *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos);
2625 
2626   /// Look up the node specified by ID in CSEMap.  If it exists, return it.  If
2627   /// not, return the insertion token that will make insertion faster.  Performs
2628   /// additional processing for constant nodes.
2629   SDNode *FindNodeOrInsertPos(const FoldingSetNodeID &ID, const SDLoc &DL,
2630                               void *&InsertPos);
2631 
2632   /// Maps to auto-CSE operations.
2633   std::vector<CondCodeSDNode*> CondCodeNodes;
2634 
2635   std::vector<SDNode*> ValueTypeNodes;
2636   std::map<EVT, SDNode*, EVT::compareRawBits> ExtendedValueTypeNodes;
2637   StringMap<SDNode*> ExternalSymbols;
2638 
2639   std::map<std::pair<std::string, unsigned>, SDNode *> TargetExternalSymbols;
2640   DenseMap<MCSymbol *, SDNode *> MCSymbols;
2641 
2642   FlagInserter *Inserter = nullptr;
2643 };
2644 
2645 template <> struct GraphTraits<SelectionDAG*> : public GraphTraits<SDNode*> {
2646   using nodes_iterator = pointer_iterator<SelectionDAG::allnodes_iterator>;
2647 
2648   static nodes_iterator nodes_begin(SelectionDAG *G) {
2649     return nodes_iterator(G->allnodes_begin());
2650   }
2651 
2652   static nodes_iterator nodes_end(SelectionDAG *G) {
2653     return nodes_iterator(G->allnodes_end());
2654   }
2655 };
2656 
2657 } // end namespace llvm
2658 
2659 #endif // LLVM_CODEGEN_SELECTIONDAG_H
2660