]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/CodeGen/SelectionDAG.h
MFV r324198: 8081 Compiler warnings in zdb
[FreeBSD/FreeBSD.git] / contrib / llvm / include / llvm / CodeGen / SelectionDAG.h
1 //===- llvm/CodeGen/SelectionDAG.h - InstSelection DAG ----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file declares the SelectionDAG class, and transitively defines the
11 // SDNode class and subclasses.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_CODEGEN_SELECTIONDAG_H
16 #define LLVM_CODEGEN_SELECTIONDAG_H
17
18 #include "llvm/ADT/APFloat.h"
19 #include "llvm/ADT/APInt.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/DenseSet.h"
23 #include "llvm/ADT/FoldingSet.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/ilist.h"
28 #include "llvm/ADT/iterator.h"
29 #include "llvm/ADT/iterator_range.h"
30 #include "llvm/Analysis/AliasAnalysis.h"
31 #include "llvm/CodeGen/DAGCombine.h"
32 #include "llvm/CodeGen/ISDOpcodes.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineMemOperand.h"
35 #include "llvm/CodeGen/MachineValueType.h"
36 #include "llvm/CodeGen/SelectionDAGNodes.h"
37 #include "llvm/CodeGen/ValueTypes.h"
38 #include "llvm/IR/DebugLoc.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Metadata.h"
41 #include "llvm/Support/Allocator.h"
42 #include "llvm/Support/ArrayRecycler.h"
43 #include "llvm/Support/AtomicOrdering.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/CodeGen.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/RecyclingAllocator.h"
48 #include <algorithm>
49 #include <cassert>
50 #include <cstdint>
51 #include <functional>
52 #include <map>
53 #include <string>
54 #include <tuple>
55 #include <utility>
56 #include <vector>
57
58 namespace llvm {
59
60 class BlockAddress;
61 class Constant;
62 class ConstantFP;
63 class ConstantInt;
64 class DataLayout;
65 struct fltSemantics;
66 class GlobalValue;
67 struct KnownBits;
68 class LLVMContext;
69 class MachineBasicBlock;
70 class MachineConstantPoolValue;
71 class MCSymbol;
72 class OptimizationRemarkEmitter;
73 class SDDbgValue;
74 class SelectionDAG;
75 class SelectionDAGTargetInfo;
76 class TargetLowering;
77 class TargetMachine;
78 class TargetSubtargetInfo;
79 class Value;
80
81 class SDVTListNode : public FoldingSetNode {
82   friend struct FoldingSetTrait<SDVTListNode>;
83
84   /// A reference to an Interned FoldingSetNodeID for this node.
85   /// The Allocator in SelectionDAG holds the data.
86   /// SDVTList contains all types which are frequently accessed in SelectionDAG.
87   /// The size of this list is not expected to be big so it won't introduce
88   /// a memory penalty.
89   FoldingSetNodeIDRef FastID;
90   const EVT *VTs;
91   unsigned int NumVTs;
92   /// The hash value for SDVTList is fixed, so cache it to avoid
93   /// hash calculation.
94   unsigned HashValue;
95
96 public:
97   SDVTListNode(const FoldingSetNodeIDRef ID, const EVT *VT, unsigned int Num) :
98       FastID(ID), VTs(VT), NumVTs(Num) {
99     HashValue = ID.ComputeHash();
100   }
101
102   SDVTList getSDVTList() {
103     SDVTList result = {VTs, NumVTs};
104     return result;
105   }
106 };
107
108 /// Specialize FoldingSetTrait for SDVTListNode
109 /// to avoid computing temp FoldingSetNodeID and hash value.
110 template<> struct FoldingSetTrait<SDVTListNode> : DefaultFoldingSetTrait<SDVTListNode> {
111   static void Profile(const SDVTListNode &X, FoldingSetNodeID& ID) {
112     ID = X.FastID;
113   }
114
115   static bool Equals(const SDVTListNode &X, const FoldingSetNodeID &ID,
116                      unsigned IDHash, FoldingSetNodeID &TempID) {
117     if (X.HashValue != IDHash)
118       return false;
119     return ID == X.FastID;
120   }
121
122   static unsigned ComputeHash(const SDVTListNode &X, FoldingSetNodeID &TempID) {
123     return X.HashValue;
124   }
125 };
126
127 template <> struct ilist_alloc_traits<SDNode> {
128   static void deleteNode(SDNode *) {
129     llvm_unreachable("ilist_traits<SDNode> shouldn't see a deleteNode call!");
130   }
131 };
132
133 /// Keeps track of dbg_value information through SDISel.  We do
134 /// not build SDNodes for these so as not to perturb the generated code;
135 /// instead the info is kept off to the side in this structure. Each SDNode may
136 /// have one or more associated dbg_value entries. This information is kept in
137 /// DbgValMap.
138 /// Byval parameters are handled separately because they don't use alloca's,
139 /// which busts the normal mechanism.  There is good reason for handling all
140 /// parameters separately:  they may not have code generated for them, they
141 /// should always go at the beginning of the function regardless of other code
142 /// motion, and debug info for them is potentially useful even if the parameter
143 /// is unused.  Right now only byval parameters are handled separately.
144 class SDDbgInfo {
145   BumpPtrAllocator Alloc;
146   SmallVector<SDDbgValue*, 32> DbgValues;
147   SmallVector<SDDbgValue*, 32> ByvalParmDbgValues;
148   using DbgValMapType = DenseMap<const SDNode *, SmallVector<SDDbgValue *, 2>>;
149   DbgValMapType DbgValMap;
150
151 public:
152   SDDbgInfo() = default;
153   SDDbgInfo(const SDDbgInfo &) = delete;
154   SDDbgInfo &operator=(const SDDbgInfo &) = delete;
155
156   void add(SDDbgValue *V, const SDNode *Node, bool isParameter) {
157     if (isParameter) {
158       ByvalParmDbgValues.push_back(V);
159     } else     DbgValues.push_back(V);
160     if (Node)
161       DbgValMap[Node].push_back(V);
162   }
163
164   /// \brief Invalidate all DbgValues attached to the node and remove
165   /// it from the Node-to-DbgValues map.
166   void erase(const SDNode *Node);
167
168   void clear() {
169     DbgValMap.clear();
170     DbgValues.clear();
171     ByvalParmDbgValues.clear();
172     Alloc.Reset();
173   }
174
175   BumpPtrAllocator &getAlloc() { return Alloc; }
176
177   bool empty() const {
178     return DbgValues.empty() && ByvalParmDbgValues.empty();
179   }
180
181   ArrayRef<SDDbgValue*> getSDDbgValues(const SDNode *Node) {
182     DbgValMapType::iterator I = DbgValMap.find(Node);
183     if (I != DbgValMap.end())
184       return I->second;
185     return ArrayRef<SDDbgValue*>();
186   }
187
188   using DbgIterator = SmallVectorImpl<SDDbgValue*>::iterator;
189
190   DbgIterator DbgBegin() { return DbgValues.begin(); }
191   DbgIterator DbgEnd()   { return DbgValues.end(); }
192   DbgIterator ByvalParmDbgBegin() { return ByvalParmDbgValues.begin(); }
193   DbgIterator ByvalParmDbgEnd()   { return ByvalParmDbgValues.end(); }
194 };
195
196 void checkForCycles(const SelectionDAG *DAG, bool force = false);
197
198 /// This is used to represent a portion of an LLVM function in a low-level
199 /// Data Dependence DAG representation suitable for instruction selection.
200 /// This DAG is constructed as the first step of instruction selection in order
201 /// to allow implementation of machine specific optimizations
202 /// and code simplifications.
203 ///
204 /// The representation used by the SelectionDAG is a target-independent
205 /// representation, which has some similarities to the GCC RTL representation,
206 /// but is significantly more simple, powerful, and is a graph form instead of a
207 /// linear form.
208 ///
209 class SelectionDAG {
210   const TargetMachine &TM;
211   const SelectionDAGTargetInfo *TSI = nullptr;
212   const TargetLowering *TLI = nullptr;
213   MachineFunction *MF;
214   Pass *SDAGISelPass = nullptr;
215   LLVMContext *Context;
216   CodeGenOpt::Level OptLevel;
217
218   /// The function-level optimization remark emitter.  Used to emit remarks
219   /// whenever manipulating the DAG.
220   OptimizationRemarkEmitter *ORE;
221
222   /// The starting token.
223   SDNode EntryNode;
224
225   /// The root of the entire DAG.
226   SDValue Root;
227
228   /// A linked list of nodes in the current DAG.
229   ilist<SDNode> AllNodes;
230
231   /// The AllocatorType for allocating SDNodes. We use
232   /// pool allocation with recycling.
233   using NodeAllocatorType = RecyclingAllocator<BumpPtrAllocator, SDNode,
234                                                sizeof(LargestSDNode),
235                                                alignof(MostAlignedSDNode)>;
236
237   /// Pool allocation for nodes.
238   NodeAllocatorType NodeAllocator;
239
240   /// This structure is used to memoize nodes, automatically performing
241   /// CSE with existing nodes when a duplicate is requested.
242   FoldingSet<SDNode> CSEMap;
243
244   /// Pool allocation for machine-opcode SDNode operands.
245   BumpPtrAllocator OperandAllocator;
246   ArrayRecycler<SDUse> OperandRecycler;
247
248   /// Pool allocation for misc. objects that are created once per SelectionDAG.
249   BumpPtrAllocator Allocator;
250
251   /// Tracks dbg_value information through SDISel.
252   SDDbgInfo *DbgInfo;
253
254   uint16_t NextPersistentId = 0;
255
256 public:
257   /// Clients of various APIs that cause global effects on
258   /// the DAG can optionally implement this interface.  This allows the clients
259   /// to handle the various sorts of updates that happen.
260   ///
261   /// A DAGUpdateListener automatically registers itself with DAG when it is
262   /// constructed, and removes itself when destroyed in RAII fashion.
263   struct DAGUpdateListener {
264     DAGUpdateListener *const Next;
265     SelectionDAG &DAG;
266
267     explicit DAGUpdateListener(SelectionDAG &D)
268       : Next(D.UpdateListeners), DAG(D) {
269       DAG.UpdateListeners = this;
270     }
271
272     virtual ~DAGUpdateListener() {
273       assert(DAG.UpdateListeners == this &&
274              "DAGUpdateListeners must be destroyed in LIFO order");
275       DAG.UpdateListeners = Next;
276     }
277
278     /// The node N that was deleted and, if E is not null, an
279     /// equivalent node E that replaced it.
280     virtual void NodeDeleted(SDNode *N, SDNode *E);
281
282     /// The node N that was updated.
283     virtual void NodeUpdated(SDNode *N);
284   };
285
286   struct DAGNodeDeletedListener : public DAGUpdateListener {
287     std::function<void(SDNode *, SDNode *)> Callback;
288
289     DAGNodeDeletedListener(SelectionDAG &DAG,
290                            std::function<void(SDNode *, SDNode *)> Callback)
291         : DAGUpdateListener(DAG), Callback(std::move(Callback)) {}
292
293     void NodeDeleted(SDNode *N, SDNode *E) override { Callback(N, E); }
294   };
295
296   /// When true, additional steps are taken to
297   /// ensure that getConstant() and similar functions return DAG nodes that
298   /// have legal types. This is important after type legalization since
299   /// any illegally typed nodes generated after this point will not experience
300   /// type legalization.
301   bool NewNodesMustHaveLegalTypes = false;
302
303 private:
304   /// DAGUpdateListener is a friend so it can manipulate the listener stack.
305   friend struct DAGUpdateListener;
306
307   /// Linked list of registered DAGUpdateListener instances.
308   /// This stack is maintained by DAGUpdateListener RAII.
309   DAGUpdateListener *UpdateListeners = nullptr;
310
311   /// Implementation of setSubgraphColor.
312   /// Return whether we had to truncate the search.
313   bool setSubgraphColorHelper(SDNode *N, const char *Color,
314                               DenseSet<SDNode *> &visited,
315                               int level, bool &printed);
316
317   template <typename SDNodeT, typename... ArgTypes>
318   SDNodeT *newSDNode(ArgTypes &&... Args) {
319     return new (NodeAllocator.template Allocate<SDNodeT>())
320         SDNodeT(std::forward<ArgTypes>(Args)...);
321   }
322
323   /// Build a synthetic SDNodeT with the given args and extract its subclass
324   /// data as an integer (e.g. for use in a folding set).
325   ///
326   /// The args to this function are the same as the args to SDNodeT's
327   /// constructor, except the second arg (assumed to be a const DebugLoc&) is
328   /// omitted.
329   template <typename SDNodeT, typename... ArgTypes>
330   static uint16_t getSyntheticNodeSubclassData(unsigned IROrder,
331                                                ArgTypes &&... Args) {
332     // The compiler can reduce this expression to a constant iff we pass an
333     // empty DebugLoc.  Thankfully, the debug location doesn't have any bearing
334     // on the subclass data.
335     return SDNodeT(IROrder, DebugLoc(), std::forward<ArgTypes>(Args)...)
336         .getRawSubclassData();
337   }
338
339   template <typename SDNodeTy>
340   static uint16_t getSyntheticNodeSubclassData(unsigned Opc, unsigned Order,
341                                                 SDVTList VTs, EVT MemoryVT,
342                                                 MachineMemOperand *MMO) {
343     return SDNodeTy(Opc, Order, DebugLoc(), VTs, MemoryVT, MMO)
344          .getRawSubclassData();
345   }
346
347   void createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
348     assert(!Node->OperandList && "Node already has operands");
349     SDUse *Ops = OperandRecycler.allocate(
350         ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
351
352     for (unsigned I = 0; I != Vals.size(); ++I) {
353       Ops[I].setUser(Node);
354       Ops[I].setInitial(Vals[I]);
355     }
356     Node->NumOperands = Vals.size();
357     Node->OperandList = Ops;
358     checkForCycles(Node);
359   }
360
361   void removeOperands(SDNode *Node) {
362     if (!Node->OperandList)
363       return;
364     OperandRecycler.deallocate(
365         ArrayRecycler<SDUse>::Capacity::get(Node->NumOperands),
366         Node->OperandList);
367     Node->NumOperands = 0;
368     Node->OperandList = nullptr;
369   }
370
371 public:
372   explicit SelectionDAG(const TargetMachine &TM, CodeGenOpt::Level);
373   SelectionDAG(const SelectionDAG &) = delete;
374   SelectionDAG &operator=(const SelectionDAG &) = delete;
375   ~SelectionDAG();
376
377   /// Prepare this SelectionDAG to process code in the given MachineFunction.
378   void init(MachineFunction &NewMF, OptimizationRemarkEmitter &NewORE,
379             Pass *PassPtr);
380
381   /// Clear state and free memory necessary to make this
382   /// SelectionDAG ready to process a new block.
383   void clear();
384
385   MachineFunction &getMachineFunction() const { return *MF; }
386   const Pass *getPass() const { return SDAGISelPass; }
387
388   const DataLayout &getDataLayout() const { return MF->getDataLayout(); }
389   const TargetMachine &getTarget() const { return TM; }
390   const TargetSubtargetInfo &getSubtarget() const { return MF->getSubtarget(); }
391   const TargetLowering &getTargetLoweringInfo() const { return *TLI; }
392   const SelectionDAGTargetInfo &getSelectionDAGInfo() const { return *TSI; }
393   LLVMContext *getContext() const {return Context; }
394   OptimizationRemarkEmitter &getORE() const { return *ORE; }
395
396   /// Pop up a GraphViz/gv window with the DAG rendered using 'dot'.
397   void viewGraph(const std::string &Title);
398   void viewGraph();
399
400 #ifndef NDEBUG
401   std::map<const SDNode *, std::string> NodeGraphAttrs;
402 #endif
403
404   /// Clear all previously defined node graph attributes.
405   /// Intended to be used from a debugging tool (eg. gdb).
406   void clearGraphAttrs();
407
408   /// Set graph attributes for a node. (eg. "color=red".)
409   void setGraphAttrs(const SDNode *N, const char *Attrs);
410
411   /// Get graph attributes for a node. (eg. "color=red".)
412   /// Used from getNodeAttributes.
413   const std::string getGraphAttrs(const SDNode *N) const;
414
415   /// Convenience for setting node color attribute.
416   void setGraphColor(const SDNode *N, const char *Color);
417
418   /// Convenience for setting subgraph color attribute.
419   void setSubgraphColor(SDNode *N, const char *Color);
420
421   using allnodes_const_iterator = ilist<SDNode>::const_iterator;
422
423   allnodes_const_iterator allnodes_begin() const { return AllNodes.begin(); }
424   allnodes_const_iterator allnodes_end() const { return AllNodes.end(); }
425
426   using allnodes_iterator = ilist<SDNode>::iterator;
427
428   allnodes_iterator allnodes_begin() { return AllNodes.begin(); }
429   allnodes_iterator allnodes_end() { return AllNodes.end(); }
430
431   ilist<SDNode>::size_type allnodes_size() const {
432     return AllNodes.size();
433   }
434
435   iterator_range<allnodes_iterator> allnodes() {
436     return make_range(allnodes_begin(), allnodes_end());
437   }
438   iterator_range<allnodes_const_iterator> allnodes() const {
439     return make_range(allnodes_begin(), allnodes_end());
440   }
441
442   /// Return the root tag of the SelectionDAG.
443   const SDValue &getRoot() const { return Root; }
444
445   /// Return the token chain corresponding to the entry of the function.
446   SDValue getEntryNode() const {
447     return SDValue(const_cast<SDNode *>(&EntryNode), 0);
448   }
449
450   /// Set the current root tag of the SelectionDAG.
451   ///
452   const SDValue &setRoot(SDValue N) {
453     assert((!N.getNode() || N.getValueType() == MVT::Other) &&
454            "DAG root value is not a chain!");
455     if (N.getNode())
456       checkForCycles(N.getNode(), this);
457     Root = N;
458     if (N.getNode())
459       checkForCycles(this);
460     return Root;
461   }
462
463   /// This iterates over the nodes in the SelectionDAG, folding
464   /// certain types of nodes together, or eliminating superfluous nodes.  The
465   /// Level argument controls whether Combine is allowed to produce nodes and
466   /// types that are illegal on the target.
467   void Combine(CombineLevel Level, AliasAnalysis *AA,
468                CodeGenOpt::Level OptLevel);
469
470   /// This transforms the SelectionDAG into a SelectionDAG that
471   /// only uses types natively supported by the target.
472   /// Returns "true" if it made any changes.
473   ///
474   /// Note that this is an involved process that may invalidate pointers into
475   /// the graph.
476   bool LegalizeTypes();
477
478   /// This transforms the SelectionDAG into a SelectionDAG that is
479   /// compatible with the target instruction selector, as indicated by the
480   /// TargetLowering object.
481   ///
482   /// Note that this is an involved process that may invalidate pointers into
483   /// the graph.
484   void Legalize();
485
486   /// \brief Transforms a SelectionDAG node and any operands to it into a node
487   /// that is compatible with the target instruction selector, as indicated by
488   /// the TargetLowering object.
489   ///
490   /// \returns true if \c N is a valid, legal node after calling this.
491   ///
492   /// This essentially runs a single recursive walk of the \c Legalize process
493   /// over the given node (and its operands). This can be used to incrementally
494   /// legalize the DAG. All of the nodes which are directly replaced,
495   /// potentially including N, are added to the output parameter \c
496   /// UpdatedNodes so that the delta to the DAG can be understood by the
497   /// caller.
498   ///
499   /// When this returns false, N has been legalized in a way that make the
500   /// pointer passed in no longer valid. It may have even been deleted from the
501   /// DAG, and so it shouldn't be used further. When this returns true, the
502   /// N passed in is a legal node, and can be immediately processed as such.
503   /// This may still have done some work on the DAG, and will still populate
504   /// UpdatedNodes with any new nodes replacing those originally in the DAG.
505   bool LegalizeOp(SDNode *N, SmallSetVector<SDNode *, 16> &UpdatedNodes);
506
507   /// This transforms the SelectionDAG into a SelectionDAG
508   /// that only uses vector math operations supported by the target.  This is
509   /// necessary as a separate step from Legalize because unrolling a vector
510   /// operation can introduce illegal types, which requires running
511   /// LegalizeTypes again.
512   ///
513   /// This returns true if it made any changes; in that case, LegalizeTypes
514   /// is called again before Legalize.
515   ///
516   /// Note that this is an involved process that may invalidate pointers into
517   /// the graph.
518   bool LegalizeVectors();
519
520   /// This method deletes all unreachable nodes in the SelectionDAG.
521   void RemoveDeadNodes();
522
523   /// Remove the specified node from the system.  This node must
524   /// have no referrers.
525   void DeleteNode(SDNode *N);
526
527   /// Return an SDVTList that represents the list of values specified.
528   SDVTList getVTList(EVT VT);
529   SDVTList getVTList(EVT VT1, EVT VT2);
530   SDVTList getVTList(EVT VT1, EVT VT2, EVT VT3);
531   SDVTList getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4);
532   SDVTList getVTList(ArrayRef<EVT> VTs);
533
534   //===--------------------------------------------------------------------===//
535   // Node creation methods.
536
537   /// \brief Create a ConstantSDNode wrapping a constant value.
538   /// If VT is a vector type, the constant is splatted into a BUILD_VECTOR.
539   ///
540   /// If only legal types can be produced, this does the necessary
541   /// transformations (e.g., if the vector element type is illegal).
542   /// @{
543   SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
544                       bool isTarget = false, bool isOpaque = false);
545   SDValue getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
546                       bool isTarget = false, bool isOpaque = false);
547
548   SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget = false,
549                              bool IsOpaque = false) {
550     return getConstant(APInt::getAllOnesValue(VT.getScalarSizeInBits()), DL,
551                        VT, IsTarget, IsOpaque);
552   }
553
554   SDValue getConstant(const ConstantInt &Val, const SDLoc &DL, EVT VT,
555                       bool isTarget = false, bool isOpaque = false);
556   SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL,
557                             bool isTarget = false);
558   SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT,
559                             bool isOpaque = false) {
560     return getConstant(Val, DL, VT, true, isOpaque);
561   }
562   SDValue getTargetConstant(const APInt &Val, const SDLoc &DL, EVT VT,
563                             bool isOpaque = false) {
564     return getConstant(Val, DL, VT, true, isOpaque);
565   }
566   SDValue getTargetConstant(const ConstantInt &Val, const SDLoc &DL, EVT VT,
567                             bool isOpaque = false) {
568     return getConstant(Val, DL, VT, true, isOpaque);
569   }
570   /// @}
571
572   /// \brief Create a ConstantFPSDNode wrapping a constant value.
573   /// If VT is a vector type, the constant is splatted into a BUILD_VECTOR.
574   ///
575   /// If only legal types can be produced, this does the necessary
576   /// transformations (e.g., if the vector element type is illegal).
577   /// The forms that take a double should only be used for simple constants
578   /// that can be exactly represented in VT.  No checks are made.
579   /// @{
580   SDValue getConstantFP(double Val, const SDLoc &DL, EVT VT,
581                         bool isTarget = false);
582   SDValue getConstantFP(const APFloat &Val, const SDLoc &DL, EVT VT,
583                         bool isTarget = false);
584   SDValue getConstantFP(const ConstantFP &CF, const SDLoc &DL, EVT VT,
585                         bool isTarget = false);
586   SDValue getTargetConstantFP(double Val, const SDLoc &DL, EVT VT) {
587     return getConstantFP(Val, DL, VT, true);
588   }
589   SDValue getTargetConstantFP(const APFloat &Val, const SDLoc &DL, EVT VT) {
590     return getConstantFP(Val, DL, VT, true);
591   }
592   SDValue getTargetConstantFP(const ConstantFP &Val, const SDLoc &DL, EVT VT) {
593     return getConstantFP(Val, DL, VT, true);
594   }
595   /// @}
596
597   SDValue getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT,
598                            int64_t offset = 0, bool isTargetGA = false,
599                            unsigned char TargetFlags = 0);
600   SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT,
601                                  int64_t offset = 0,
602                                  unsigned char TargetFlags = 0) {
603     return getGlobalAddress(GV, DL, VT, offset, true, TargetFlags);
604   }
605   SDValue getFrameIndex(int FI, EVT VT, bool isTarget = false);
606   SDValue getTargetFrameIndex(int FI, EVT VT) {
607     return getFrameIndex(FI, VT, true);
608   }
609   SDValue getJumpTable(int JTI, EVT VT, bool isTarget = false,
610                        unsigned char TargetFlags = 0);
611   SDValue getTargetJumpTable(int JTI, EVT VT, unsigned char TargetFlags = 0) {
612     return getJumpTable(JTI, VT, true, TargetFlags);
613   }
614   SDValue getConstantPool(const Constant *C, EVT VT,
615                           unsigned Align = 0, int Offs = 0, bool isT=false,
616                           unsigned char TargetFlags = 0);
617   SDValue getTargetConstantPool(const Constant *C, EVT VT,
618                                 unsigned Align = 0, int Offset = 0,
619                                 unsigned char TargetFlags = 0) {
620     return getConstantPool(C, VT, Align, Offset, true, TargetFlags);
621   }
622   SDValue getConstantPool(MachineConstantPoolValue *C, EVT VT,
623                           unsigned Align = 0, int Offs = 0, bool isT=false,
624                           unsigned char TargetFlags = 0);
625   SDValue getTargetConstantPool(MachineConstantPoolValue *C,
626                                   EVT VT, unsigned Align = 0,
627                                   int Offset = 0, unsigned char TargetFlags=0) {
628     return getConstantPool(C, VT, Align, Offset, true, TargetFlags);
629   }
630   SDValue getTargetIndex(int Index, EVT VT, int64_t Offset = 0,
631                          unsigned char TargetFlags = 0);
632   // When generating a branch to a BB, we don't in general know enough
633   // to provide debug info for the BB at that time, so keep this one around.
634   SDValue getBasicBlock(MachineBasicBlock *MBB);
635   SDValue getBasicBlock(MachineBasicBlock *MBB, SDLoc dl);
636   SDValue getExternalSymbol(const char *Sym, EVT VT);
637   SDValue getExternalSymbol(const char *Sym, const SDLoc &dl, EVT VT);
638   SDValue getTargetExternalSymbol(const char *Sym, EVT VT,
639                                   unsigned char TargetFlags = 0);
640   SDValue getMCSymbol(MCSymbol *Sym, EVT VT);
641
642   SDValue getValueType(EVT);
643   SDValue getRegister(unsigned Reg, EVT VT);
644   SDValue getRegisterMask(const uint32_t *RegMask);
645   SDValue getEHLabel(const SDLoc &dl, SDValue Root, MCSymbol *Label);
646   SDValue getLabelNode(unsigned Opcode, const SDLoc &dl, SDValue Root,
647                        MCSymbol *Label);
648   SDValue getBlockAddress(const BlockAddress *BA, EVT VT,
649                           int64_t Offset = 0, bool isTarget = false,
650                           unsigned char TargetFlags = 0);
651   SDValue getTargetBlockAddress(const BlockAddress *BA, EVT VT,
652                                 int64_t Offset = 0,
653                                 unsigned char TargetFlags = 0) {
654     return getBlockAddress(BA, VT, Offset, true, TargetFlags);
655   }
656
657   SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, unsigned Reg,
658                        SDValue N) {
659     return getNode(ISD::CopyToReg, dl, MVT::Other, Chain,
660                    getRegister(Reg, N.getValueType()), N);
661   }
662
663   // This version of the getCopyToReg method takes an extra operand, which
664   // indicates that there is potentially an incoming glue value (if Glue is not
665   // null) and that there should be a glue result.
666   SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, unsigned Reg, SDValue N,
667                        SDValue Glue) {
668     SDVTList VTs = getVTList(MVT::Other, MVT::Glue);
669     SDValue Ops[] = { Chain, getRegister(Reg, N.getValueType()), N, Glue };
670     return getNode(ISD::CopyToReg, dl, VTs,
671                    makeArrayRef(Ops, Glue.getNode() ? 4 : 3));
672   }
673
674   // Similar to last getCopyToReg() except parameter Reg is a SDValue
675   SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, SDValue Reg, SDValue N,
676                        SDValue Glue) {
677     SDVTList VTs = getVTList(MVT::Other, MVT::Glue);
678     SDValue Ops[] = { Chain, Reg, N, Glue };
679     return getNode(ISD::CopyToReg, dl, VTs,
680                    makeArrayRef(Ops, Glue.getNode() ? 4 : 3));
681   }
682
683   SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, unsigned Reg, EVT VT) {
684     SDVTList VTs = getVTList(VT, MVT::Other);
685     SDValue Ops[] = { Chain, getRegister(Reg, VT) };
686     return getNode(ISD::CopyFromReg, dl, VTs, Ops);
687   }
688
689   // This version of the getCopyFromReg method takes an extra operand, which
690   // indicates that there is potentially an incoming glue value (if Glue is not
691   // null) and that there should be a glue result.
692   SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, unsigned Reg, EVT VT,
693                          SDValue Glue) {
694     SDVTList VTs = getVTList(VT, MVT::Other, MVT::Glue);
695     SDValue Ops[] = { Chain, getRegister(Reg, VT), Glue };
696     return getNode(ISD::CopyFromReg, dl, VTs,
697                    makeArrayRef(Ops, Glue.getNode() ? 3 : 2));
698   }
699
700   SDValue getCondCode(ISD::CondCode Cond);
701
702   /// Return an ISD::VECTOR_SHUFFLE node. The number of elements in VT,
703   /// which must be a vector type, must match the number of mask elements
704   /// NumElts. An integer mask element equal to -1 is treated as undefined.
705   SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, SDValue N2,
706                            ArrayRef<int> Mask);
707
708   /// Return an ISD::BUILD_VECTOR node. The number of elements in VT,
709   /// which must be a vector type, must match the number of operands in Ops.
710   /// The operands must have the same type as (or, for integers, a type wider
711   /// than) VT's element type.
712   SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef<SDValue> Ops) {
713     // VerifySDNode (via InsertNode) checks BUILD_VECTOR later.
714     return getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
715   }
716
717   /// Return an ISD::BUILD_VECTOR node. The number of elements in VT,
718   /// which must be a vector type, must match the number of operands in Ops.
719   /// The operands must have the same type as (or, for integers, a type wider
720   /// than) VT's element type.
721   SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef<SDUse> Ops) {
722     // VerifySDNode (via InsertNode) checks BUILD_VECTOR later.
723     return getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
724   }
725
726   /// Return a splat ISD::BUILD_VECTOR node, consisting of Op splatted to all
727   /// elements. VT must be a vector type. Op's type must be the same as (or,
728   /// for integers, a type wider than) VT's element type.
729   SDValue getSplatBuildVector(EVT VT, const SDLoc &DL, SDValue Op) {
730     // VerifySDNode (via InsertNode) checks BUILD_VECTOR later.
731     if (Op.getOpcode() == ISD::UNDEF) {
732       assert((VT.getVectorElementType() == Op.getValueType() ||
733               (VT.isInteger() &&
734                VT.getVectorElementType().bitsLE(Op.getValueType()))) &&
735              "A splatted value must have a width equal or (for integers) "
736              "greater than the vector element type!");
737       return getNode(ISD::UNDEF, SDLoc(), VT);
738     }
739
740     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Op);
741     return getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
742   }
743
744   /// \brief Returns an ISD::VECTOR_SHUFFLE node semantically equivalent to
745   /// the shuffle node in input but with swapped operands.
746   ///
747   /// Example: shuffle A, B, <0,5,2,7> -> shuffle B, A, <4,1,6,3>
748   SDValue getCommutedVectorShuffle(const ShuffleVectorSDNode &SV);
749
750   /// Convert Op, which must be of float type, to the
751   /// float type VT, by either extending or rounding (by truncation).
752   SDValue getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT);
753
754   /// Convert Op, which must be of integer type, to the
755   /// integer type VT, by either any-extending or truncating it.
756   SDValue getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT);
757
758   /// Convert Op, which must be of integer type, to the
759   /// integer type VT, by either sign-extending or truncating it.
760   SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT);
761
762   /// Convert Op, which must be of integer type, to the
763   /// integer type VT, by either zero-extending or truncating it.
764   SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT);
765
766   /// Return the expression required to zero extend the Op
767   /// value assuming it was the smaller SrcTy value.
768   SDValue getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT SrcTy);
769
770   /// Return an operation which will any-extend the low lanes of the operand
771   /// into the specified vector type. For example,
772   /// this can convert a v16i8 into a v4i32 by any-extending the low four
773   /// lanes of the operand from i8 to i32.
774   SDValue getAnyExtendVectorInReg(SDValue Op, const SDLoc &DL, EVT VT);
775
776   /// Return an operation which will sign extend the low lanes of the operand
777   /// into the specified vector type. For example,
778   /// this can convert a v16i8 into a v4i32 by sign extending the low four
779   /// lanes of the operand from i8 to i32.
780   SDValue getSignExtendVectorInReg(SDValue Op, const SDLoc &DL, EVT VT);
781
782   /// Return an operation which will zero extend the low lanes of the operand
783   /// into the specified vector type. For example,
784   /// this can convert a v16i8 into a v4i32 by zero extending the low four
785   /// lanes of the operand from i8 to i32.
786   SDValue getZeroExtendVectorInReg(SDValue Op, const SDLoc &DL, EVT VT);
787
788   /// Convert Op, which must be of integer type, to the integer type VT,
789   /// by using an extension appropriate for the target's
790   /// BooleanContent for type OpVT or truncating it.
791   SDValue getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, EVT OpVT);
792
793   /// Create a bitwise NOT operation as (XOR Val, -1).
794   SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT);
795
796   /// \brief Create a logical NOT operation as (XOR Val, BooleanOne).
797   SDValue getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT);
798
799   /// \brief Create an add instruction with appropriate flags when used for
800   /// addressing some offset of an object. i.e. if a load is split into multiple
801   /// components, create an add nuw from the base pointer to the offset.
802   SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Op, int64_t Offset) {
803     EVT VT = Op.getValueType();
804     return getObjectPtrOffset(SL, Op, getConstant(Offset, SL, VT));
805   }
806
807   SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Op, SDValue Offset) {
808     EVT VT = Op.getValueType();
809
810     // The object itself can't wrap around the address space, so it shouldn't be
811     // possible for the adds of the offsets to the split parts to overflow.
812     SDNodeFlags Flags;
813     Flags.setNoUnsignedWrap(true);
814     return getNode(ISD::ADD, SL, VT, Op, Offset, Flags);
815   }
816
817   /// Return a new CALLSEQ_START node, that starts new call frame, in which
818   /// InSize bytes are set up inside CALLSEQ_START..CALLSEQ_END sequence and
819   /// OutSize specifies part of the frame set up prior to the sequence.
820   SDValue getCALLSEQ_START(SDValue Chain, uint64_t InSize, uint64_t OutSize,
821                            const SDLoc &DL) {
822     SDVTList VTs = getVTList(MVT::Other, MVT::Glue);
823     SDValue Ops[] = { Chain,
824                       getIntPtrConstant(InSize, DL, true),
825                       getIntPtrConstant(OutSize, DL, true) };
826     return getNode(ISD::CALLSEQ_START, DL, VTs, Ops);
827   }
828
829   /// Return a new CALLSEQ_END node, which always must have a
830   /// glue result (to ensure it's not CSE'd).
831   /// CALLSEQ_END does not have a useful SDLoc.
832   SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2,
833                          SDValue InGlue, const SDLoc &DL) {
834     SDVTList NodeTys = getVTList(MVT::Other, MVT::Glue);
835     SmallVector<SDValue, 4> Ops;
836     Ops.push_back(Chain);
837     Ops.push_back(Op1);
838     Ops.push_back(Op2);
839     if (InGlue.getNode())
840       Ops.push_back(InGlue);
841     return getNode(ISD::CALLSEQ_END, DL, NodeTys, Ops);
842   }
843
844   /// Return true if the result of this operation is always undefined.
845   bool isUndef(unsigned Opcode, ArrayRef<SDValue> Ops);
846
847   /// Return an UNDEF node. UNDEF does not have a useful SDLoc.
848   SDValue getUNDEF(EVT VT) {
849     return getNode(ISD::UNDEF, SDLoc(), VT);
850   }
851
852   /// Return a GLOBAL_OFFSET_TABLE node. This does not have a useful SDLoc.
853   SDValue getGLOBAL_OFFSET_TABLE(EVT VT) {
854     return getNode(ISD::GLOBAL_OFFSET_TABLE, SDLoc(), VT);
855   }
856
857   /// Gets or creates the specified node.
858   ///
859   SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
860                   ArrayRef<SDUse> Ops);
861   SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
862                   ArrayRef<SDValue> Ops, const SDNodeFlags Flags = SDNodeFlags());
863   SDValue getNode(unsigned Opcode, const SDLoc &DL, ArrayRef<EVT> ResultTys,
864                   ArrayRef<SDValue> Ops);
865   SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTs,
866                   ArrayRef<SDValue> Ops);
867
868   // Specialize based on number of operands.
869   SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT);
870   SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N,
871                   const SDNodeFlags Flags = SDNodeFlags());
872   SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N1,
873                   SDValue N2, const SDNodeFlags Flags = SDNodeFlags());
874   SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N1,
875                   SDValue N2, SDValue N3);
876   SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N1,
877                   SDValue N2, SDValue N3, SDValue N4);
878   SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N1,
879                   SDValue N2, SDValue N3, SDValue N4, SDValue N5);
880
881   // Specialize again based on number of operands for nodes with a VTList
882   // rather than a single VT.
883   SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTs);
884   SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTs, SDValue N);
885   SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTs, SDValue N1,
886                   SDValue N2);
887   SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTs, SDValue N1,
888                   SDValue N2, SDValue N3);
889   SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTs, SDValue N1,
890                   SDValue N2, SDValue N3, SDValue N4);
891   SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTs, SDValue N1,
892                   SDValue N2, SDValue N3, SDValue N4, SDValue N5);
893
894   /// Compute a TokenFactor to force all the incoming stack arguments to be
895   /// loaded from the stack. This is used in tail call lowering to protect
896   /// stack arguments from being clobbered.
897   SDValue getStackArgumentTokenFactor(SDValue Chain);
898
899   SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src,
900                     SDValue Size, unsigned Align, bool isVol, bool AlwaysInline,
901                     bool isTailCall, MachinePointerInfo DstPtrInfo,
902                     MachinePointerInfo SrcPtrInfo);
903
904   SDValue getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src,
905                      SDValue Size, unsigned Align, bool isVol, bool isTailCall,
906                      MachinePointerInfo DstPtrInfo,
907                      MachinePointerInfo SrcPtrInfo);
908
909   SDValue getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src,
910                     SDValue Size, unsigned Align, bool isVol, bool isTailCall,
911                     MachinePointerInfo DstPtrInfo);
912
913   /// Helper function to make it easier to build SetCC's if you just
914   /// have an ISD::CondCode instead of an SDValue.
915   ///
916   SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS,
917                    ISD::CondCode Cond) {
918     assert(LHS.getValueType().isVector() == RHS.getValueType().isVector() &&
919       "Cannot compare scalars to vectors");
920     assert(LHS.getValueType().isVector() == VT.isVector() &&
921       "Cannot compare scalars to vectors");
922     assert(Cond != ISD::SETCC_INVALID &&
923         "Cannot create a setCC of an invalid node.");
924     return getNode(ISD::SETCC, DL, VT, LHS, RHS, getCondCode(Cond));
925   }
926
927   /// Helper function to make it easier to build Select's if you just
928   /// have operands and don't want to check for vector.
929   SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS,
930                     SDValue RHS) {
931     assert(LHS.getValueType() == RHS.getValueType() &&
932            "Cannot use select on differing types");
933     assert(VT.isVector() == LHS.getValueType().isVector() &&
934            "Cannot mix vectors and scalars");
935     return getNode(Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
936                    Cond, LHS, RHS);
937   }
938
939   /// Helper function to make it easier to build SelectCC's if you
940   /// just have an ISD::CondCode instead of an SDValue.
941   ///
942   SDValue getSelectCC(const SDLoc &DL, SDValue LHS, SDValue RHS, SDValue True,
943                       SDValue False, ISD::CondCode Cond) {
944     return getNode(ISD::SELECT_CC, DL, True.getValueType(),
945                    LHS, RHS, True, False, getCondCode(Cond));
946   }
947
948   /// VAArg produces a result and token chain, and takes a pointer
949   /// and a source value as input.
950   SDValue getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr,
951                    SDValue SV, unsigned Align);
952
953   /// Gets a node for an atomic cmpxchg op. There are two
954   /// valid Opcodes. ISD::ATOMIC_CMO_SWAP produces the value loaded and a
955   /// chain result. ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS produces the value loaded,
956   /// a success flag (initially i1), and a chain.
957   SDValue getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, EVT MemVT,
958                            SDVTList VTs, SDValue Chain, SDValue Ptr,
959                            SDValue Cmp, SDValue Swp, MachinePointerInfo PtrInfo,
960                            unsigned Alignment, AtomicOrdering SuccessOrdering,
961                            AtomicOrdering FailureOrdering,
962                            SyncScope::ID SSID);
963   SDValue getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, EVT MemVT,
964                            SDVTList VTs, SDValue Chain, SDValue Ptr,
965                            SDValue Cmp, SDValue Swp, MachineMemOperand *MMO);
966
967   /// Gets a node for an atomic op, produces result (if relevant)
968   /// and chain and takes 2 operands.
969   SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDValue Chain,
970                     SDValue Ptr, SDValue Val, const Value *PtrVal,
971                     unsigned Alignment, AtomicOrdering Ordering,
972                     SyncScope::ID SSID);
973   SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDValue Chain,
974                     SDValue Ptr, SDValue Val, MachineMemOperand *MMO);
975
976   /// Gets a node for an atomic op, produces result and chain and
977   /// takes 1 operand.
978   SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, EVT VT,
979                     SDValue Chain, SDValue Ptr, MachineMemOperand *MMO);
980
981   /// Gets a node for an atomic op, produces result and chain and takes N
982   /// operands.
983   SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
984                     SDVTList VTList, ArrayRef<SDValue> Ops,
985                     MachineMemOperand *MMO);
986
987   /// Creates a MemIntrinsicNode that may produce a
988   /// result and takes a list of operands. Opcode may be INTRINSIC_VOID,
989   /// INTRINSIC_W_CHAIN, or a target-specific opcode with a value not
990   /// less than FIRST_TARGET_MEMORY_OPCODE.
991   SDValue getMemIntrinsicNode(
992     unsigned Opcode, const SDLoc &dl, SDVTList VTList,
993     ArrayRef<SDValue> Ops, EVT MemVT,
994     MachinePointerInfo PtrInfo,
995     unsigned Align = 0,
996     MachineMemOperand::Flags Flags
997     = MachineMemOperand::MOLoad | MachineMemOperand::MOStore,
998     unsigned Size = 0);
999
1000   SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList,
1001                               ArrayRef<SDValue> Ops, EVT MemVT,
1002                               MachineMemOperand *MMO);
1003
1004   /// Create a MERGE_VALUES node from the given operands.
1005   SDValue getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl);
1006
1007   /// Loads are not normal binary operators: their result type is not
1008   /// determined by their operands, and they produce a value AND a token chain.
1009   ///
1010   /// This function will set the MOLoad flag on MMOFlags, but you can set it if
1011   /// you want.  The MOStore flag must not be set.
1012   SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr,
1013                   MachinePointerInfo PtrInfo, unsigned Alignment = 0,
1014                   MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
1015                   const AAMDNodes &AAInfo = AAMDNodes(),
1016                   const MDNode *Ranges = nullptr);
1017   SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr,
1018                   MachineMemOperand *MMO);
1019   SDValue
1020   getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain,
1021              SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT,
1022              unsigned Alignment = 0,
1023              MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
1024              const AAMDNodes &AAInfo = AAMDNodes());
1025   SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT,
1026                      SDValue Chain, SDValue Ptr, EVT MemVT,
1027                      MachineMemOperand *MMO);
1028   SDValue getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, SDValue Base,
1029                          SDValue Offset, ISD::MemIndexedMode AM);
1030   SDValue getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT,
1031                   const SDLoc &dl, SDValue Chain, SDValue Ptr, SDValue Offset,
1032                   MachinePointerInfo PtrInfo, EVT MemVT, unsigned Alignment = 0,
1033                   MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
1034                   const AAMDNodes &AAInfo = AAMDNodes(),
1035                   const MDNode *Ranges = nullptr);
1036   SDValue getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT,
1037                   const SDLoc &dl, SDValue Chain, SDValue Ptr, SDValue Offset,
1038                   EVT MemVT, MachineMemOperand *MMO);
1039
1040   /// Helper function to build ISD::STORE nodes.
1041   ///
1042   /// This function will set the MOStore flag on MMOFlags, but you can set it if
1043   /// you want.  The MOLoad and MOInvariant flags must not be set.
1044   SDValue
1045   getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr,
1046            MachinePointerInfo PtrInfo, unsigned Alignment = 0,
1047            MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
1048            const AAMDNodes &AAInfo = AAMDNodes());
1049   SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr,
1050                    MachineMemOperand *MMO);
1051   SDValue
1052   getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr,
1053                 MachinePointerInfo PtrInfo, EVT TVT, unsigned Alignment = 0,
1054                 MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
1055                 const AAMDNodes &AAInfo = AAMDNodes());
1056   SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
1057                         SDValue Ptr, EVT TVT, MachineMemOperand *MMO);
1058   SDValue getIndexedStore(SDValue OrigStoe, const SDLoc &dl, SDValue Base,
1059                           SDValue Offset, ISD::MemIndexedMode AM);
1060
1061   /// Returns sum of the base pointer and offset.
1062   SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset, const SDLoc &DL);
1063
1064   SDValue getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr,
1065                         SDValue Mask, SDValue Src0, EVT MemVT,
1066                         MachineMemOperand *MMO, ISD::LoadExtType,
1067                         bool IsExpanding = false);
1068   SDValue getMaskedStore(SDValue Chain, const SDLoc &dl, SDValue Val,
1069                          SDValue Ptr, SDValue Mask, EVT MemVT,
1070                          MachineMemOperand *MMO, bool IsTruncating = false,
1071                          bool IsCompressing = false);
1072   SDValue getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
1073                           ArrayRef<SDValue> Ops, MachineMemOperand *MMO);
1074   SDValue getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
1075                            ArrayRef<SDValue> Ops, MachineMemOperand *MMO);
1076
1077   /// Return (create a new or find existing) a target-specific node.
1078   /// TargetMemSDNode should be derived class from MemSDNode.
1079   template <class TargetMemSDNode>
1080   SDValue getTargetMemSDNode(SDVTList VTs, ArrayRef<SDValue> Ops,
1081                              const SDLoc &dl, EVT MemVT,
1082                              MachineMemOperand *MMO);
1083
1084   /// Construct a node to track a Value* through the backend.
1085   SDValue getSrcValue(const Value *v);
1086
1087   /// Return an MDNodeSDNode which holds an MDNode.
1088   SDValue getMDNode(const MDNode *MD);
1089
1090   /// Return a bitcast using the SDLoc of the value operand, and casting to the
1091   /// provided type. Use getNode to set a custom SDLoc.
1092   SDValue getBitcast(EVT VT, SDValue V);
1093
1094   /// Return an AddrSpaceCastSDNode.
1095   SDValue getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, unsigned SrcAS,
1096                            unsigned DestAS);
1097
1098   /// Return the specified value casted to
1099   /// the target's desired shift amount type.
1100   SDValue getShiftAmountOperand(EVT LHSTy, SDValue Op);
1101
1102   /// Expand the specified \c ISD::VAARG node as the Legalize pass would.
1103   SDValue expandVAArg(SDNode *Node);
1104
1105   /// Expand the specified \c ISD::VACOPY node as the Legalize pass would.
1106   SDValue expandVACopy(SDNode *Node);
1107
1108   /// *Mutate* the specified node in-place to have the
1109   /// specified operands.  If the resultant node already exists in the DAG,
1110   /// this does not modify the specified node, instead it returns the node that
1111   /// already exists.  If the resultant node does not exist in the DAG, the
1112   /// input node is returned.  As a degenerate case, if you specify the same
1113   /// input operands as the node already has, the input node is returned.
1114   SDNode *UpdateNodeOperands(SDNode *N, SDValue Op);
1115   SDNode *UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2);
1116   SDNode *UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
1117                                SDValue Op3);
1118   SDNode *UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
1119                                SDValue Op3, SDValue Op4);
1120   SDNode *UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
1121                                SDValue Op3, SDValue Op4, SDValue Op5);
1122   SDNode *UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops);
1123
1124   /// These are used for target selectors to *mutate* the
1125   /// specified node to have the specified return type, Target opcode, and
1126   /// operands.  Note that target opcodes are stored as
1127   /// ~TargetOpcode in the node opcode field.  The resultant node is returned.
1128   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT);
1129   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT, SDValue Op1);
1130   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT,
1131                        SDValue Op1, SDValue Op2);
1132   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT,
1133                        SDValue Op1, SDValue Op2, SDValue Op3);
1134   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT,
1135                        ArrayRef<SDValue> Ops);
1136   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT1, EVT VT2);
1137   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT1,
1138                        EVT VT2, ArrayRef<SDValue> Ops);
1139   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT1,
1140                        EVT VT2, EVT VT3, ArrayRef<SDValue> Ops);
1141   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT1,
1142                        EVT VT2, SDValue Op1);
1143   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT1,
1144                        EVT VT2, SDValue Op1, SDValue Op2);
1145   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, SDVTList VTs,
1146                        ArrayRef<SDValue> Ops);
1147
1148   /// This *mutates* the specified node to have the specified
1149   /// return type, opcode, and operands.
1150   SDNode *MorphNodeTo(SDNode *N, unsigned Opc, SDVTList VTs,
1151                       ArrayRef<SDValue> Ops);
1152
1153   /// Mutate the specified strict FP node to its non-strict equivalent,
1154   /// unlinking the node from its chain and dropping the metadata arguments.
1155   /// The node must be a strict FP node.
1156   SDNode *mutateStrictFPToFP(SDNode *Node);
1157
1158   /// These are used for target selectors to create a new node
1159   /// with specified return type(s), MachineInstr opcode, and operands.
1160   ///
1161   /// Note that getMachineNode returns the resultant node.  If there is already
1162   /// a node of the specified opcode and operands, it returns that node instead
1163   /// of the current one.
1164   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT);
1165   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT,
1166                                 SDValue Op1);
1167   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT,
1168                                 SDValue Op1, SDValue Op2);
1169   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT,
1170                                 SDValue Op1, SDValue Op2, SDValue Op3);
1171   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT,
1172                                 ArrayRef<SDValue> Ops);
1173   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT1,
1174                                 EVT VT2, SDValue Op1, SDValue Op2);
1175   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT1,
1176                                 EVT VT2, SDValue Op1, SDValue Op2, SDValue Op3);
1177   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT1,
1178                                 EVT VT2, ArrayRef<SDValue> Ops);
1179   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT1,
1180                                 EVT VT2, EVT VT3, SDValue Op1, SDValue Op2);
1181   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT1,
1182                                 EVT VT2, EVT VT3, SDValue Op1, SDValue Op2,
1183                                 SDValue Op3);
1184   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT1,
1185                                 EVT VT2, EVT VT3, ArrayRef<SDValue> Ops);
1186   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl,
1187                                 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops);
1188   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, SDVTList VTs,
1189                                 ArrayRef<SDValue> Ops);
1190
1191   /// A convenience function for creating TargetInstrInfo::EXTRACT_SUBREG nodes.
1192   SDValue getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
1193                                  SDValue Operand);
1194
1195   /// A convenience function for creating TargetInstrInfo::INSERT_SUBREG nodes.
1196   SDValue getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
1197                                 SDValue Operand, SDValue Subreg);
1198
1199   /// Get the specified node if it's already available, or else return NULL.
1200   SDNode *getNodeIfExists(unsigned Opcode, SDVTList VTs, ArrayRef<SDValue> Ops,
1201                           const SDNodeFlags Flags = SDNodeFlags());
1202
1203   /// Creates a SDDbgValue node.
1204   SDDbgValue *getDbgValue(DIVariable *Var, DIExpression *Expr, SDNode *N,
1205                           unsigned R, bool IsIndirect, const DebugLoc &DL,
1206                           unsigned O);
1207
1208   /// Creates a constant SDDbgValue node.
1209   SDDbgValue *getConstantDbgValue(DIVariable *Var, DIExpression *Expr,
1210                                   const Value *C, const DebugLoc &DL,
1211                                   unsigned O);
1212
1213   /// Creates a FrameIndex SDDbgValue node.
1214   SDDbgValue *getFrameIndexDbgValue(DIVariable *Var, DIExpression *Expr,
1215                                     unsigned FI, const DebugLoc &DL,
1216                                     unsigned O);
1217
1218   /// Transfer debug values from one node to another, while optionally
1219   /// generating fragment expressions for split-up values. If \p InvalidateDbg
1220   /// is set, debug values are invalidated after they are transferred.
1221   void transferDbgValues(SDValue From, SDValue To, unsigned OffsetInBits = 0,
1222                          unsigned SizeInBits = 0, bool InvalidateDbg = true);
1223
1224   /// Remove the specified node from the system. If any of its
1225   /// operands then becomes dead, remove them as well. Inform UpdateListener
1226   /// for each node deleted.
1227   void RemoveDeadNode(SDNode *N);
1228
1229   /// This method deletes the unreachable nodes in the
1230   /// given list, and any nodes that become unreachable as a result.
1231   void RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes);
1232
1233   /// Modify anything using 'From' to use 'To' instead.
1234   /// This can cause recursive merging of nodes in the DAG.  Use the first
1235   /// version if 'From' is known to have a single result, use the second
1236   /// if you have two nodes with identical results (or if 'To' has a superset
1237   /// of the results of 'From'), use the third otherwise.
1238   ///
1239   /// These methods all take an optional UpdateListener, which (if not null) is
1240   /// informed about nodes that are deleted and modified due to recursive
1241   /// changes in the dag.
1242   ///
1243   /// These functions only replace all existing uses. It's possible that as
1244   /// these replacements are being performed, CSE may cause the From node
1245   /// to be given new uses. These new uses of From are left in place, and
1246   /// not automatically transferred to To.
1247   ///
1248   void ReplaceAllUsesWith(SDValue From, SDValue Op);
1249   void ReplaceAllUsesWith(SDNode *From, SDNode *To);
1250   void ReplaceAllUsesWith(SDNode *From, const SDValue *To);
1251
1252   /// Replace any uses of From with To, leaving
1253   /// uses of other values produced by From.getNode() alone.
1254   void ReplaceAllUsesOfValueWith(SDValue From, SDValue To);
1255
1256   /// Like ReplaceAllUsesOfValueWith, but for multiple values at once.
1257   /// This correctly handles the case where
1258   /// there is an overlap between the From values and the To values.
1259   void ReplaceAllUsesOfValuesWith(const SDValue *From, const SDValue *To,
1260                                   unsigned Num);
1261
1262   /// If an existing load has uses of its chain, create a token factor node with
1263   /// that chain and the new memory node's chain and update users of the old
1264   /// chain to the token factor. This ensures that the new memory node will have
1265   /// the same relative memory dependency position as the old load. Returns the
1266   /// new merged load chain.
1267   SDValue makeEquivalentMemoryOrdering(LoadSDNode *Old, SDValue New);
1268
1269   /// Topological-sort the AllNodes list and a
1270   /// assign a unique node id for each node in the DAG based on their
1271   /// topological order. Returns the number of nodes.
1272   unsigned AssignTopologicalOrder();
1273
1274   /// Move node N in the AllNodes list to be immediately
1275   /// before the given iterator Position. This may be used to update the
1276   /// topological ordering when the list of nodes is modified.
1277   void RepositionNode(allnodes_iterator Position, SDNode *N) {
1278     AllNodes.insert(Position, AllNodes.remove(N));
1279   }
1280
1281   /// Returns an APFloat semantics tag appropriate for the given type. If VT is
1282   /// a vector type, the element semantics are returned.
1283   static const fltSemantics &EVTToAPFloatSemantics(EVT VT) {
1284     switch (VT.getScalarType().getSimpleVT().SimpleTy) {
1285     default: llvm_unreachable("Unknown FP format");
1286     case MVT::f16:     return APFloat::IEEEhalf();
1287     case MVT::f32:     return APFloat::IEEEsingle();
1288     case MVT::f64:     return APFloat::IEEEdouble();
1289     case MVT::f80:     return APFloat::x87DoubleExtended();
1290     case MVT::f128:    return APFloat::IEEEquad();
1291     case MVT::ppcf128: return APFloat::PPCDoubleDouble();
1292     }
1293   }
1294
1295   /// Add a dbg_value SDNode. If SD is non-null that means the
1296   /// value is produced by SD.
1297   void AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter);
1298
1299   /// Get the debug values which reference the given SDNode.
1300   ArrayRef<SDDbgValue*> GetDbgValues(const SDNode* SD) {
1301     return DbgInfo->getSDDbgValues(SD);
1302   }
1303
1304 public:
1305   /// Return true if there are any SDDbgValue nodes associated
1306   /// with this SelectionDAG.
1307   bool hasDebugValues() const { return !DbgInfo->empty(); }
1308
1309   SDDbgInfo::DbgIterator DbgBegin() { return DbgInfo->DbgBegin(); }
1310   SDDbgInfo::DbgIterator DbgEnd()   { return DbgInfo->DbgEnd(); }
1311
1312   SDDbgInfo::DbgIterator ByvalParmDbgBegin() {
1313     return DbgInfo->ByvalParmDbgBegin();
1314   }
1315
1316   SDDbgInfo::DbgIterator ByvalParmDbgEnd()   {
1317     return DbgInfo->ByvalParmDbgEnd();
1318   }
1319
1320   /// To be invoked on an SDNode that is slated to be erased. This
1321   /// function mirrors \c llvm::salvageDebugInfo.
1322   void salvageDebugInfo(SDNode &N);
1323
1324   void dump() const;
1325
1326   /// Create a stack temporary, suitable for holding the specified value type.
1327   /// If minAlign is specified, the slot size will have at least that alignment.
1328   SDValue CreateStackTemporary(EVT VT, unsigned minAlign = 1);
1329
1330   /// Create a stack temporary suitable for holding either of the specified
1331   /// value types.
1332   SDValue CreateStackTemporary(EVT VT1, EVT VT2);
1333
1334   SDValue FoldSymbolOffset(unsigned Opcode, EVT VT,
1335                            const GlobalAddressSDNode *GA,
1336                            const SDNode *N2);
1337
1338   SDValue FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, EVT VT,
1339                                  SDNode *Cst1, SDNode *Cst2);
1340
1341   SDValue FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, EVT VT,
1342                                  const ConstantSDNode *Cst1,
1343                                  const ConstantSDNode *Cst2);
1344
1345   SDValue FoldConstantVectorArithmetic(unsigned Opcode, const SDLoc &DL, EVT VT,
1346                                        ArrayRef<SDValue> Ops,
1347                                        const SDNodeFlags Flags = SDNodeFlags());
1348
1349   /// Constant fold a setcc to true or false.
1350   SDValue FoldSetCC(EVT VT, SDValue N1, SDValue N2, ISD::CondCode Cond,
1351                     const SDLoc &dl);
1352
1353   /// See if the specified operand can be simplified with the knowledge that only
1354   /// the bits specified by Mask are used.  If so, return the simpler operand,
1355   /// otherwise return a null SDValue.
1356   ///
1357   /// (This exists alongside SimplifyDemandedBits because GetDemandedBits can
1358   /// simplify nodes with multiple uses more aggressively.)
1359   SDValue GetDemandedBits(SDValue V, const APInt &Mask);
1360
1361   /// Return true if the sign bit of Op is known to be zero.
1362   /// We use this predicate to simplify operations downstream.
1363   bool SignBitIsZero(SDValue Op, unsigned Depth = 0) const;
1364
1365   /// Return true if 'Op & Mask' is known to be zero.  We
1366   /// use this predicate to simplify operations downstream.  Op and Mask are
1367   /// known to be the same type.
1368   bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth = 0)
1369     const;
1370
1371   /// Determine which bits of Op are known to be either zero or one and return
1372   /// them in Known. For vectors, the known bits are those that are shared by
1373   /// every vector element.
1374   /// Targets can implement the computeKnownBitsForTargetNode method in the
1375   /// TargetLowering class to allow target nodes to be understood.
1376   void computeKnownBits(SDValue Op, KnownBits &Known, unsigned Depth = 0) const;
1377
1378   /// Determine which bits of Op are known to be either zero or one and return
1379   /// them in Known. The DemandedElts argument allows us to only collect the
1380   /// known bits that are shared by the requested vector elements.
1381   /// Targets can implement the computeKnownBitsForTargetNode method in the
1382   /// TargetLowering class to allow target nodes to be understood.
1383   void computeKnownBits(SDValue Op, KnownBits &Known, const APInt &DemandedElts,
1384                         unsigned Depth = 0) const;
1385
1386   /// Used to represent the possible overflow behavior of an operation.
1387   /// Never: the operation cannot overflow.
1388   /// Always: the operation will always overflow.
1389   /// Sometime: the operation may or may not overflow.
1390   enum OverflowKind {
1391     OFK_Never,
1392     OFK_Sometime,
1393     OFK_Always,
1394   };
1395
1396   /// Determine if the result of the addition of 2 node can overflow.
1397   OverflowKind computeOverflowKind(SDValue N0, SDValue N1) const;
1398
1399   /// Test if the given value is known to have exactly one bit set. This differs
1400   /// from computeKnownBits in that it doesn't necessarily determine which bit
1401   /// is set.
1402   bool isKnownToBeAPowerOfTwo(SDValue Val) const;
1403
1404   /// Return the number of times the sign bit of the register is replicated into
1405   /// the other bits. We know that at least 1 bit is always equal to the sign
1406   /// bit (itself), but other cases can give us information. For example,
1407   /// immediately after an "SRA X, 2", we know that the top 3 bits are all equal
1408   /// to each other, so we return 3. Targets can implement the
1409   /// ComputeNumSignBitsForTarget method in the TargetLowering class to allow
1410   /// target nodes to be understood.
1411   unsigned ComputeNumSignBits(SDValue Op, unsigned Depth = 0) const;
1412
1413   /// Return the number of times the sign bit of the register is replicated into
1414   /// the other bits. We know that at least 1 bit is always equal to the sign
1415   /// bit (itself), but other cases can give us information. For example,
1416   /// immediately after an "SRA X, 2", we know that the top 3 bits are all equal
1417   /// to each other, so we return 3. The DemandedElts argument allows
1418   /// us to only collect the minimum sign bits of the requested vector elements.
1419   /// Targets can implement the ComputeNumSignBitsForTarget method in the
1420   /// TargetLowering class to allow target nodes to be understood.
1421   unsigned ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
1422                               unsigned Depth = 0) const;
1423
1424   /// Return true if the specified operand is an ISD::ADD with a ConstantSDNode
1425   /// on the right-hand side, or if it is an ISD::OR with a ConstantSDNode that
1426   /// is guaranteed to have the same semantics as an ADD. This handles the
1427   /// equivalence:
1428   ///     X|Cst == X+Cst iff X&Cst = 0.
1429   bool isBaseWithConstantOffset(SDValue Op) const;
1430
1431   /// Test whether the given SDValue is known to never be NaN.
1432   bool isKnownNeverNaN(SDValue Op) const;
1433
1434   /// Test whether the given SDValue is known to never be positive or negative
1435   /// zero.
1436   bool isKnownNeverZero(SDValue Op) const;
1437
1438   /// Test whether two SDValues are known to compare equal. This
1439   /// is true if they are the same value, or if one is negative zero and the
1440   /// other positive zero.
1441   bool isEqualTo(SDValue A, SDValue B) const;
1442
1443   /// Return true if A and B have no common bits set. As an example, this can
1444   /// allow an 'add' to be transformed into an 'or'.
1445   bool haveNoCommonBitsSet(SDValue A, SDValue B) const;
1446
1447   /// Utility function used by legalize and lowering to
1448   /// "unroll" a vector operation by splitting out the scalars and operating
1449   /// on each element individually.  If the ResNE is 0, fully unroll the vector
1450   /// op. If ResNE is less than the width of the vector op, unroll up to ResNE.
1451   /// If the  ResNE is greater than the width of the vector op, unroll the
1452   /// vector op and fill the end of the resulting vector with UNDEFS.
1453   SDValue UnrollVectorOp(SDNode *N, unsigned ResNE = 0);
1454
1455   /// Return true if loads are next to each other and can be
1456   /// merged. Check that both are nonvolatile and if LD is loading
1457   /// 'Bytes' bytes from a location that is 'Dist' units away from the
1458   /// location that the 'Base' load is loading from.
1459   bool areNonVolatileConsecutiveLoads(LoadSDNode *LD, LoadSDNode *Base,
1460                                       unsigned Bytes, int Dist) const;
1461
1462   /// Infer alignment of a load / store address. Return 0 if
1463   /// it cannot be inferred.
1464   unsigned InferPtrAlignment(SDValue Ptr) const;
1465
1466   /// Compute the VTs needed for the low/hi parts of a type
1467   /// which is split (or expanded) into two not necessarily identical pieces.
1468   std::pair<EVT, EVT> GetSplitDestVTs(const EVT &VT) const;
1469
1470   /// Split the vector with EXTRACT_SUBVECTOR using the provides
1471   /// VTs and return the low/high part.
1472   std::pair<SDValue, SDValue> SplitVector(const SDValue &N, const SDLoc &DL,
1473                                           const EVT &LoVT, const EVT &HiVT);
1474
1475   /// Split the vector with EXTRACT_SUBVECTOR and return the low/high part.
1476   std::pair<SDValue, SDValue> SplitVector(const SDValue &N, const SDLoc &DL) {
1477     EVT LoVT, HiVT;
1478     std::tie(LoVT, HiVT) = GetSplitDestVTs(N.getValueType());
1479     return SplitVector(N, DL, LoVT, HiVT);
1480   }
1481
1482   /// Split the node's operand with EXTRACT_SUBVECTOR and
1483   /// return the low/high part.
1484   std::pair<SDValue, SDValue> SplitVectorOperand(const SDNode *N, unsigned OpNo)
1485   {
1486     return SplitVector(N->getOperand(OpNo), SDLoc(N));
1487   }
1488
1489   /// Append the extracted elements from Start to Count out of the vector Op
1490   /// in Args. If Count is 0, all of the elements will be extracted.
1491   void ExtractVectorElements(SDValue Op, SmallVectorImpl<SDValue> &Args,
1492                              unsigned Start = 0, unsigned Count = 0);
1493
1494   /// Compute the default alignment value for the given type.
1495   unsigned getEVTAlignment(EVT MemoryVT) const;
1496
1497   /// Test whether the given value is a constant int or similar node.
1498   SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N);
1499
1500   /// Test whether the given value is a constant FP or similar node.
1501   SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N);
1502
1503   /// \returns true if \p N is any kind of constant or build_vector of
1504   /// constants, int or float. If a vector, it may not necessarily be a splat.
1505   inline bool isConstantValueOfAnyType(SDValue N) {
1506     return isConstantIntBuildVectorOrConstantInt(N) ||
1507            isConstantFPBuildVectorOrConstantFP(N);
1508   }
1509
1510 private:
1511   void InsertNode(SDNode *N);
1512   bool RemoveNodeFromCSEMaps(SDNode *N);
1513   void AddModifiedNodeToCSEMaps(SDNode *N);
1514   SDNode *FindModifiedNodeSlot(SDNode *N, SDValue Op, void *&InsertPos);
1515   SDNode *FindModifiedNodeSlot(SDNode *N, SDValue Op1, SDValue Op2,
1516                                void *&InsertPos);
1517   SDNode *FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1518                                void *&InsertPos);
1519   SDNode *UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &loc);
1520
1521   void DeleteNodeNotInCSEMaps(SDNode *N);
1522   void DeallocateNode(SDNode *N);
1523
1524   void allnodes_clear();
1525
1526   /// Look up the node specified by ID in CSEMap.  If it exists, return it.  If
1527   /// not, return the insertion token that will make insertion faster.  This
1528   /// overload is for nodes other than Constant or ConstantFP, use the other one
1529   /// for those.
1530   SDNode *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos);
1531
1532   /// Look up the node specified by ID in CSEMap.  If it exists, return it.  If
1533   /// not, return the insertion token that will make insertion faster.  Performs
1534   /// additional processing for constant nodes.
1535   SDNode *FindNodeOrInsertPos(const FoldingSetNodeID &ID, const SDLoc &DL,
1536                               void *&InsertPos);
1537
1538   /// List of non-single value types.
1539   FoldingSet<SDVTListNode> VTListMap;
1540
1541   /// Maps to auto-CSE operations.
1542   std::vector<CondCodeSDNode*> CondCodeNodes;
1543
1544   std::vector<SDNode*> ValueTypeNodes;
1545   std::map<EVT, SDNode*, EVT::compareRawBits> ExtendedValueTypeNodes;
1546   StringMap<SDNode*> ExternalSymbols;
1547
1548   std::map<std::pair<std::string, unsigned char>,SDNode*> TargetExternalSymbols;
1549   DenseMap<MCSymbol *, SDNode *> MCSymbols;
1550 };
1551
1552 template <> struct GraphTraits<SelectionDAG*> : public GraphTraits<SDNode*> {
1553   using nodes_iterator = pointer_iterator<SelectionDAG::allnodes_iterator>;
1554
1555   static nodes_iterator nodes_begin(SelectionDAG *G) {
1556     return nodes_iterator(G->allnodes_begin());
1557   }
1558
1559   static nodes_iterator nodes_end(SelectionDAG *G) {
1560     return nodes_iterator(G->allnodes_end());
1561   }
1562 };
1563
1564 template <class TargetMemSDNode>
1565 SDValue SelectionDAG::getTargetMemSDNode(SDVTList VTs,
1566                                          ArrayRef<SDValue> Ops,
1567                                          const SDLoc &dl, EVT MemVT,
1568                                          MachineMemOperand *MMO) {
1569   /// Compose node ID and try to find an existing node.
1570   FoldingSetNodeID ID;
1571   unsigned Opcode =
1572     TargetMemSDNode(dl.getIROrder(), DebugLoc(), VTs, MemVT, MMO).getOpcode();
1573   ID.AddInteger(Opcode);
1574   ID.AddPointer(VTs.VTs);
1575   for (auto& Op : Ops) {
1576     ID.AddPointer(Op.getNode());
1577     ID.AddInteger(Op.getResNo());
1578   }
1579   ID.AddInteger(MemVT.getRawBits());
1580   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
1581   ID.AddInteger(getSyntheticNodeSubclassData<TargetMemSDNode>(
1582     dl.getIROrder(), VTs, MemVT, MMO));
1583
1584   void *IP = nullptr;
1585   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
1586     cast<TargetMemSDNode>(E)->refineAlignment(MMO);
1587     return SDValue(E, 0);
1588   }
1589
1590   /// Existing node was not found. Create a new one.
1591   auto *N = newSDNode<TargetMemSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
1592                                        MemVT, MMO);
1593   createOperands(N, Ops);
1594   CSEMap.InsertNode(N, IP);
1595   InsertNode(N);
1596   return SDValue(N, 0);
1597 }
1598
1599 } // end namespace llvm
1600
1601 #endif // LLVM_CODEGEN_SELECTIONDAG_H