1 //===-- llvm/CodeGen/SelectionDAG.h - InstSelection DAG ---------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file declares the SelectionDAG class, and transitively defines the
11 // SDNode class and subclasses.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CODEGEN_SELECTIONDAG_H
16 #define LLVM_CODEGEN_SELECTIONDAG_H
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/ilist.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/CodeGen/DAGCombine.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/SelectionDAGNodes.h"
26 #include "llvm/Support/ArrayRecycler.h"
27 #include "llvm/Support/RecyclingAllocator.h"
28 #include "llvm/Target/TargetMachine.h"
36 class MachineConstantPoolValue;
37 class MachineFunction;
39 class OptimizationRemarkEmitter;
42 class SelectionDAGTargetInfo;
44 class SDVTListNode : public FoldingSetNode {
45 friend struct FoldingSetTrait<SDVTListNode>;
46 /// A reference to an Interned FoldingSetNodeID for this node.
47 /// The Allocator in SelectionDAG holds the data.
48 /// SDVTList contains all types which are frequently accessed in SelectionDAG.
49 /// The size of this list is not expected to be big so it won't introduce
51 FoldingSetNodeIDRef FastID;
54 /// The hash value for SDVTList is fixed, so cache it to avoid
58 SDVTListNode(const FoldingSetNodeIDRef ID, const EVT *VT, unsigned int Num) :
59 FastID(ID), VTs(VT), NumVTs(Num) {
60 HashValue = ID.ComputeHash();
62 SDVTList getSDVTList() {
63 SDVTList result = {VTs, NumVTs};
68 /// Specialize FoldingSetTrait for SDVTListNode
69 /// to avoid computing temp FoldingSetNodeID and hash value.
70 template<> struct FoldingSetTrait<SDVTListNode> : DefaultFoldingSetTrait<SDVTListNode> {
71 static void Profile(const SDVTListNode &X, FoldingSetNodeID& ID) {
74 static bool Equals(const SDVTListNode &X, const FoldingSetNodeID &ID,
75 unsigned IDHash, FoldingSetNodeID &TempID) {
76 if (X.HashValue != IDHash)
78 return ID == X.FastID;
80 static unsigned ComputeHash(const SDVTListNode &X, FoldingSetNodeID &TempID) {
85 template <> struct ilist_alloc_traits<SDNode> {
86 static void deleteNode(SDNode *) {
87 llvm_unreachable("ilist_traits<SDNode> shouldn't see a deleteNode call!");
91 /// Keeps track of dbg_value information through SDISel. We do
92 /// not build SDNodes for these so as not to perturb the generated code;
93 /// instead the info is kept off to the side in this structure. Each SDNode may
94 /// have one or more associated dbg_value entries. This information is kept in
96 /// Byval parameters are handled separately because they don't use alloca's,
97 /// which busts the normal mechanism. There is good reason for handling all
98 /// parameters separately: they may not have code generated for them, they
99 /// should always go at the beginning of the function regardless of other code
100 /// motion, and debug info for them is potentially useful even if the parameter
101 /// is unused. Right now only byval parameters are handled separately.
103 BumpPtrAllocator Alloc;
104 SmallVector<SDDbgValue*, 32> DbgValues;
105 SmallVector<SDDbgValue*, 32> ByvalParmDbgValues;
106 typedef DenseMap<const SDNode*, SmallVector<SDDbgValue*, 2> > DbgValMapType;
107 DbgValMapType DbgValMap;
109 void operator=(const SDDbgInfo&) = delete;
110 SDDbgInfo(const SDDbgInfo&) = delete;
114 void add(SDDbgValue *V, const SDNode *Node, bool isParameter) {
116 ByvalParmDbgValues.push_back(V);
117 } else DbgValues.push_back(V);
119 DbgValMap[Node].push_back(V);
122 /// \brief Invalidate all DbgValues attached to the node and remove
123 /// it from the Node-to-DbgValues map.
124 void erase(const SDNode *Node);
129 ByvalParmDbgValues.clear();
133 BumpPtrAllocator &getAlloc() { return Alloc; }
136 return DbgValues.empty() && ByvalParmDbgValues.empty();
139 ArrayRef<SDDbgValue*> getSDDbgValues(const SDNode *Node) {
140 DbgValMapType::iterator I = DbgValMap.find(Node);
141 if (I != DbgValMap.end())
143 return ArrayRef<SDDbgValue*>();
146 typedef SmallVectorImpl<SDDbgValue*>::iterator DbgIterator;
147 DbgIterator DbgBegin() { return DbgValues.begin(); }
148 DbgIterator DbgEnd() { return DbgValues.end(); }
149 DbgIterator ByvalParmDbgBegin() { return ByvalParmDbgValues.begin(); }
150 DbgIterator ByvalParmDbgEnd() { return ByvalParmDbgValues.end(); }
154 void checkForCycles(const SelectionDAG *DAG, bool force = false);
156 /// This is used to represent a portion of an LLVM function in a low-level
157 /// Data Dependence DAG representation suitable for instruction selection.
158 /// This DAG is constructed as the first step of instruction selection in order
159 /// to allow implementation of machine specific optimizations
160 /// and code simplifications.
162 /// The representation used by the SelectionDAG is a target-independent
163 /// representation, which has some similarities to the GCC RTL representation,
164 /// but is significantly more simple, powerful, and is a graph form instead of a
168 const TargetMachine &TM;
169 const SelectionDAGTargetInfo *TSI;
170 const TargetLowering *TLI;
172 LLVMContext *Context;
173 CodeGenOpt::Level OptLevel;
175 /// The function-level optimization remark emitter. Used to emit remarks
176 /// whenever manipulating the DAG.
177 OptimizationRemarkEmitter *ORE;
179 /// The starting token.
182 /// The root of the entire DAG.
185 /// A linked list of nodes in the current DAG.
186 ilist<SDNode> AllNodes;
188 /// The AllocatorType for allocating SDNodes. We use
189 /// pool allocation with recycling.
190 typedef RecyclingAllocator<BumpPtrAllocator, SDNode, sizeof(LargestSDNode),
191 alignof(MostAlignedSDNode)>
194 /// Pool allocation for nodes.
195 NodeAllocatorType NodeAllocator;
197 /// This structure is used to memoize nodes, automatically performing
198 /// CSE with existing nodes when a duplicate is requested.
199 FoldingSet<SDNode> CSEMap;
201 /// Pool allocation for machine-opcode SDNode operands.
202 BumpPtrAllocator OperandAllocator;
203 ArrayRecycler<SDUse> OperandRecycler;
205 /// Pool allocation for misc. objects that are created once per SelectionDAG.
206 BumpPtrAllocator Allocator;
208 /// Tracks dbg_value information through SDISel.
211 uint16_t NextPersistentId = 0;
214 /// Clients of various APIs that cause global effects on
215 /// the DAG can optionally implement this interface. This allows the clients
216 /// to handle the various sorts of updates that happen.
218 /// A DAGUpdateListener automatically registers itself with DAG when it is
219 /// constructed, and removes itself when destroyed in RAII fashion.
220 struct DAGUpdateListener {
221 DAGUpdateListener *const Next;
224 explicit DAGUpdateListener(SelectionDAG &D)
225 : Next(D.UpdateListeners), DAG(D) {
226 DAG.UpdateListeners = this;
229 virtual ~DAGUpdateListener() {
230 assert(DAG.UpdateListeners == this &&
231 "DAGUpdateListeners must be destroyed in LIFO order");
232 DAG.UpdateListeners = Next;
235 /// The node N that was deleted and, if E is not null, an
236 /// equivalent node E that replaced it.
237 virtual void NodeDeleted(SDNode *N, SDNode *E);
239 /// The node N that was updated.
240 virtual void NodeUpdated(SDNode *N);
243 struct DAGNodeDeletedListener : public DAGUpdateListener {
244 std::function<void(SDNode *, SDNode *)> Callback;
245 DAGNodeDeletedListener(SelectionDAG &DAG,
246 std::function<void(SDNode *, SDNode *)> Callback)
247 : DAGUpdateListener(DAG), Callback(std::move(Callback)) {}
248 void NodeDeleted(SDNode *N, SDNode *E) override { Callback(N, E); }
251 /// When true, additional steps are taken to
252 /// ensure that getConstant() and similar functions return DAG nodes that
253 /// have legal types. This is important after type legalization since
254 /// any illegally typed nodes generated after this point will not experience
255 /// type legalization.
256 bool NewNodesMustHaveLegalTypes;
259 /// DAGUpdateListener is a friend so it can manipulate the listener stack.
260 friend struct DAGUpdateListener;
262 /// Linked list of registered DAGUpdateListener instances.
263 /// This stack is maintained by DAGUpdateListener RAII.
264 DAGUpdateListener *UpdateListeners;
266 /// Implementation of setSubgraphColor.
267 /// Return whether we had to truncate the search.
268 bool setSubgraphColorHelper(SDNode *N, const char *Color,
269 DenseSet<SDNode *> &visited,
270 int level, bool &printed);
272 template <typename SDNodeT, typename... ArgTypes>
273 SDNodeT *newSDNode(ArgTypes &&... Args) {
274 return new (NodeAllocator.template Allocate<SDNodeT>())
275 SDNodeT(std::forward<ArgTypes>(Args)...);
278 /// Build a synthetic SDNodeT with the given args and extract its subclass
279 /// data as an integer (e.g. for use in a folding set).
281 /// The args to this function are the same as the args to SDNodeT's
282 /// constructor, except the second arg (assumed to be a const DebugLoc&) is
284 template <typename SDNodeT, typename... ArgTypes>
285 static uint16_t getSyntheticNodeSubclassData(unsigned IROrder,
286 ArgTypes &&... Args) {
287 // The compiler can reduce this expression to a constant iff we pass an
288 // empty DebugLoc. Thankfully, the debug location doesn't have any bearing
289 // on the subclass data.
290 return SDNodeT(IROrder, DebugLoc(), std::forward<ArgTypes>(Args)...)
291 .getRawSubclassData();
294 void createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
295 assert(!Node->OperandList && "Node already has operands");
296 SDUse *Ops = OperandRecycler.allocate(
297 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
299 for (unsigned I = 0; I != Vals.size(); ++I) {
300 Ops[I].setUser(Node);
301 Ops[I].setInitial(Vals[I]);
303 Node->NumOperands = Vals.size();
304 Node->OperandList = Ops;
305 checkForCycles(Node);
308 void removeOperands(SDNode *Node) {
309 if (!Node->OperandList)
311 OperandRecycler.deallocate(
312 ArrayRecycler<SDUse>::Capacity::get(Node->NumOperands),
314 Node->NumOperands = 0;
315 Node->OperandList = nullptr;
318 void operator=(const SelectionDAG&) = delete;
319 SelectionDAG(const SelectionDAG&) = delete;
322 explicit SelectionDAG(const TargetMachine &TM, llvm::CodeGenOpt::Level);
325 /// Prepare this SelectionDAG to process code in the given MachineFunction.
326 void init(MachineFunction &NewMF, OptimizationRemarkEmitter &NewORE);
328 /// Clear state and free memory necessary to make this
329 /// SelectionDAG ready to process a new block.
332 MachineFunction &getMachineFunction() const { return *MF; }
333 const DataLayout &getDataLayout() const { return MF->getDataLayout(); }
334 const TargetMachine &getTarget() const { return TM; }
335 const TargetSubtargetInfo &getSubtarget() const { return MF->getSubtarget(); }
336 const TargetLowering &getTargetLoweringInfo() const { return *TLI; }
337 const SelectionDAGTargetInfo &getSelectionDAGInfo() const { return *TSI; }
338 LLVMContext *getContext() const {return Context; }
339 OptimizationRemarkEmitter &getORE() const { return *ORE; }
341 /// Pop up a GraphViz/gv window with the DAG rendered using 'dot'.
342 void viewGraph(const std::string &Title);
346 std::map<const SDNode *, std::string> NodeGraphAttrs;
349 /// Clear all previously defined node graph attributes.
350 /// Intended to be used from a debugging tool (eg. gdb).
351 void clearGraphAttrs();
353 /// Set graph attributes for a node. (eg. "color=red".)
354 void setGraphAttrs(const SDNode *N, const char *Attrs);
356 /// Get graph attributes for a node. (eg. "color=red".)
357 /// Used from getNodeAttributes.
358 const std::string getGraphAttrs(const SDNode *N) const;
360 /// Convenience for setting node color attribute.
361 void setGraphColor(const SDNode *N, const char *Color);
363 /// Convenience for setting subgraph color attribute.
364 void setSubgraphColor(SDNode *N, const char *Color);
366 typedef ilist<SDNode>::const_iterator allnodes_const_iterator;
367 allnodes_const_iterator allnodes_begin() const { return AllNodes.begin(); }
368 allnodes_const_iterator allnodes_end() const { return AllNodes.end(); }
369 typedef ilist<SDNode>::iterator allnodes_iterator;
370 allnodes_iterator allnodes_begin() { return AllNodes.begin(); }
371 allnodes_iterator allnodes_end() { return AllNodes.end(); }
372 ilist<SDNode>::size_type allnodes_size() const {
373 return AllNodes.size();
376 iterator_range<allnodes_iterator> allnodes() {
377 return make_range(allnodes_begin(), allnodes_end());
379 iterator_range<allnodes_const_iterator> allnodes() const {
380 return make_range(allnodes_begin(), allnodes_end());
383 /// Return the root tag of the SelectionDAG.
384 const SDValue &getRoot() const { return Root; }
386 /// Return the token chain corresponding to the entry of the function.
387 SDValue getEntryNode() const {
388 return SDValue(const_cast<SDNode *>(&EntryNode), 0);
391 /// Set the current root tag of the SelectionDAG.
393 const SDValue &setRoot(SDValue N) {
394 assert((!N.getNode() || N.getValueType() == MVT::Other) &&
395 "DAG root value is not a chain!");
397 checkForCycles(N.getNode(), this);
400 checkForCycles(this);
404 /// This iterates over the nodes in the SelectionDAG, folding
405 /// certain types of nodes together, or eliminating superfluous nodes. The
406 /// Level argument controls whether Combine is allowed to produce nodes and
407 /// types that are illegal on the target.
408 void Combine(CombineLevel Level, AliasAnalysis &AA,
409 CodeGenOpt::Level OptLevel);
411 /// This transforms the SelectionDAG into a SelectionDAG that
412 /// only uses types natively supported by the target.
413 /// Returns "true" if it made any changes.
415 /// Note that this is an involved process that may invalidate pointers into
417 bool LegalizeTypes();
419 /// This transforms the SelectionDAG into a SelectionDAG that is
420 /// compatible with the target instruction selector, as indicated by the
421 /// TargetLowering object.
423 /// Note that this is an involved process that may invalidate pointers into
427 /// \brief Transforms a SelectionDAG node and any operands to it into a node
428 /// that is compatible with the target instruction selector, as indicated by
429 /// the TargetLowering object.
431 /// \returns true if \c N is a valid, legal node after calling this.
433 /// This essentially runs a single recursive walk of the \c Legalize process
434 /// over the given node (and its operands). This can be used to incrementally
435 /// legalize the DAG. All of the nodes which are directly replaced,
436 /// potentially including N, are added to the output parameter \c
437 /// UpdatedNodes so that the delta to the DAG can be understood by the
440 /// When this returns false, N has been legalized in a way that make the
441 /// pointer passed in no longer valid. It may have even been deleted from the
442 /// DAG, and so it shouldn't be used further. When this returns true, the
443 /// N passed in is a legal node, and can be immediately processed as such.
444 /// This may still have done some work on the DAG, and will still populate
445 /// UpdatedNodes with any new nodes replacing those originally in the DAG.
446 bool LegalizeOp(SDNode *N, SmallSetVector<SDNode *, 16> &UpdatedNodes);
448 /// This transforms the SelectionDAG into a SelectionDAG
449 /// that only uses vector math operations supported by the target. This is
450 /// necessary as a separate step from Legalize because unrolling a vector
451 /// operation can introduce illegal types, which requires running
452 /// LegalizeTypes again.
454 /// This returns true if it made any changes; in that case, LegalizeTypes
455 /// is called again before Legalize.
457 /// Note that this is an involved process that may invalidate pointers into
459 bool LegalizeVectors();
461 /// This method deletes all unreachable nodes in the SelectionDAG.
462 void RemoveDeadNodes();
464 /// Remove the specified node from the system. This node must
465 /// have no referrers.
466 void DeleteNode(SDNode *N);
468 /// Return an SDVTList that represents the list of values specified.
469 SDVTList getVTList(EVT VT);
470 SDVTList getVTList(EVT VT1, EVT VT2);
471 SDVTList getVTList(EVT VT1, EVT VT2, EVT VT3);
472 SDVTList getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4);
473 SDVTList getVTList(ArrayRef<EVT> VTs);
475 //===--------------------------------------------------------------------===//
476 // Node creation methods.
479 /// \brief Create a ConstantSDNode wrapping a constant value.
480 /// If VT is a vector type, the constant is splatted into a BUILD_VECTOR.
482 /// If only legal types can be produced, this does the necessary
483 /// transformations (e.g., if the vector element type is illegal).
485 SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
486 bool isTarget = false, bool isOpaque = false);
487 SDValue getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
488 bool isTarget = false, bool isOpaque = false);
490 SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget = false,
491 bool IsOpaque = false) {
492 return getConstant(APInt::getAllOnesValue(VT.getScalarSizeInBits()), DL,
493 VT, IsTarget, IsOpaque);
496 SDValue getConstant(const ConstantInt &Val, const SDLoc &DL, EVT VT,
497 bool isTarget = false, bool isOpaque = false);
498 SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL,
499 bool isTarget = false);
500 SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT,
501 bool isOpaque = false) {
502 return getConstant(Val, DL, VT, true, isOpaque);
504 SDValue getTargetConstant(const APInt &Val, const SDLoc &DL, EVT VT,
505 bool isOpaque = false) {
506 return getConstant(Val, DL, VT, true, isOpaque);
508 SDValue getTargetConstant(const ConstantInt &Val, const SDLoc &DL, EVT VT,
509 bool isOpaque = false) {
510 return getConstant(Val, DL, VT, true, isOpaque);
514 /// \brief Create a ConstantFPSDNode wrapping a constant value.
515 /// If VT is a vector type, the constant is splatted into a BUILD_VECTOR.
517 /// If only legal types can be produced, this does the necessary
518 /// transformations (e.g., if the vector element type is illegal).
519 /// The forms that take a double should only be used for simple constants
520 /// that can be exactly represented in VT. No checks are made.
522 SDValue getConstantFP(double Val, const SDLoc &DL, EVT VT,
523 bool isTarget = false);
524 SDValue getConstantFP(const APFloat &Val, const SDLoc &DL, EVT VT,
525 bool isTarget = false);
526 SDValue getConstantFP(const ConstantFP &CF, const SDLoc &DL, EVT VT,
527 bool isTarget = false);
528 SDValue getTargetConstantFP(double Val, const SDLoc &DL, EVT VT) {
529 return getConstantFP(Val, DL, VT, true);
531 SDValue getTargetConstantFP(const APFloat &Val, const SDLoc &DL, EVT VT) {
532 return getConstantFP(Val, DL, VT, true);
534 SDValue getTargetConstantFP(const ConstantFP &Val, const SDLoc &DL, EVT VT) {
535 return getConstantFP(Val, DL, VT, true);
539 SDValue getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT,
540 int64_t offset = 0, bool isTargetGA = false,
541 unsigned char TargetFlags = 0);
542 SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT,
544 unsigned char TargetFlags = 0) {
545 return getGlobalAddress(GV, DL, VT, offset, true, TargetFlags);
547 SDValue getFrameIndex(int FI, EVT VT, bool isTarget = false);
548 SDValue getTargetFrameIndex(int FI, EVT VT) {
549 return getFrameIndex(FI, VT, true);
551 SDValue getJumpTable(int JTI, EVT VT, bool isTarget = false,
552 unsigned char TargetFlags = 0);
553 SDValue getTargetJumpTable(int JTI, EVT VT, unsigned char TargetFlags = 0) {
554 return getJumpTable(JTI, VT, true, TargetFlags);
556 SDValue getConstantPool(const Constant *C, EVT VT,
557 unsigned Align = 0, int Offs = 0, bool isT=false,
558 unsigned char TargetFlags = 0);
559 SDValue getTargetConstantPool(const Constant *C, EVT VT,
560 unsigned Align = 0, int Offset = 0,
561 unsigned char TargetFlags = 0) {
562 return getConstantPool(C, VT, Align, Offset, true, TargetFlags);
564 SDValue getConstantPool(MachineConstantPoolValue *C, EVT VT,
565 unsigned Align = 0, int Offs = 0, bool isT=false,
566 unsigned char TargetFlags = 0);
567 SDValue getTargetConstantPool(MachineConstantPoolValue *C,
568 EVT VT, unsigned Align = 0,
569 int Offset = 0, unsigned char TargetFlags=0) {
570 return getConstantPool(C, VT, Align, Offset, true, TargetFlags);
572 SDValue getTargetIndex(int Index, EVT VT, int64_t Offset = 0,
573 unsigned char TargetFlags = 0);
574 // When generating a branch to a BB, we don't in general know enough
575 // to provide debug info for the BB at that time, so keep this one around.
576 SDValue getBasicBlock(MachineBasicBlock *MBB);
577 SDValue getBasicBlock(MachineBasicBlock *MBB, SDLoc dl);
578 SDValue getExternalSymbol(const char *Sym, EVT VT);
579 SDValue getExternalSymbol(const char *Sym, const SDLoc &dl, EVT VT);
580 SDValue getTargetExternalSymbol(const char *Sym, EVT VT,
581 unsigned char TargetFlags = 0);
582 SDValue getMCSymbol(MCSymbol *Sym, EVT VT);
584 SDValue getValueType(EVT);
585 SDValue getRegister(unsigned Reg, EVT VT);
586 SDValue getRegisterMask(const uint32_t *RegMask);
587 SDValue getEHLabel(const SDLoc &dl, SDValue Root, MCSymbol *Label);
588 SDValue getBlockAddress(const BlockAddress *BA, EVT VT,
589 int64_t Offset = 0, bool isTarget = false,
590 unsigned char TargetFlags = 0);
591 SDValue getTargetBlockAddress(const BlockAddress *BA, EVT VT,
593 unsigned char TargetFlags = 0) {
594 return getBlockAddress(BA, VT, Offset, true, TargetFlags);
597 SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, unsigned Reg,
599 return getNode(ISD::CopyToReg, dl, MVT::Other, Chain,
600 getRegister(Reg, N.getValueType()), N);
603 // This version of the getCopyToReg method takes an extra operand, which
604 // indicates that there is potentially an incoming glue value (if Glue is not
605 // null) and that there should be a glue result.
606 SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, unsigned Reg, SDValue N,
608 SDVTList VTs = getVTList(MVT::Other, MVT::Glue);
609 SDValue Ops[] = { Chain, getRegister(Reg, N.getValueType()), N, Glue };
610 return getNode(ISD::CopyToReg, dl, VTs,
611 makeArrayRef(Ops, Glue.getNode() ? 4 : 3));
614 // Similar to last getCopyToReg() except parameter Reg is a SDValue
615 SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, SDValue Reg, SDValue N,
617 SDVTList VTs = getVTList(MVT::Other, MVT::Glue);
618 SDValue Ops[] = { Chain, Reg, N, Glue };
619 return getNode(ISD::CopyToReg, dl, VTs,
620 makeArrayRef(Ops, Glue.getNode() ? 4 : 3));
623 SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, unsigned Reg, EVT VT) {
624 SDVTList VTs = getVTList(VT, MVT::Other);
625 SDValue Ops[] = { Chain, getRegister(Reg, VT) };
626 return getNode(ISD::CopyFromReg, dl, VTs, Ops);
629 // This version of the getCopyFromReg method takes an extra operand, which
630 // indicates that there is potentially an incoming glue value (if Glue is not
631 // null) and that there should be a glue result.
632 SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, unsigned Reg, EVT VT,
634 SDVTList VTs = getVTList(VT, MVT::Other, MVT::Glue);
635 SDValue Ops[] = { Chain, getRegister(Reg, VT), Glue };
636 return getNode(ISD::CopyFromReg, dl, VTs,
637 makeArrayRef(Ops, Glue.getNode() ? 3 : 2));
640 SDValue getCondCode(ISD::CondCode Cond);
642 /// Return an ISD::VECTOR_SHUFFLE node. The number of elements in VT,
643 /// which must be a vector type, must match the number of mask elements
644 /// NumElts. An integer mask element equal to -1 is treated as undefined.
645 SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, SDValue N2,
648 /// Return an ISD::BUILD_VECTOR node. The number of elements in VT,
649 /// which must be a vector type, must match the number of operands in Ops.
650 /// The operands must have the same type as (or, for integers, a type wider
651 /// than) VT's element type.
652 SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef<SDValue> Ops) {
653 // VerifySDNode (via InsertNode) checks BUILD_VECTOR later.
654 return getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
657 /// Return a splat ISD::BUILD_VECTOR node, consisting of Op splatted to all
658 /// elements. VT must be a vector type. Op's type must be the same as (or,
659 /// for integers, a type wider than) VT's element type.
660 SDValue getSplatBuildVector(EVT VT, const SDLoc &DL, SDValue Op) {
661 // VerifySDNode (via InsertNode) checks BUILD_VECTOR later.
662 if (Op.getOpcode() == ISD::UNDEF) {
663 assert((VT.getVectorElementType() == Op.getValueType() ||
665 VT.getVectorElementType().bitsLE(Op.getValueType()))) &&
666 "A splatted value must have a width equal or (for integers) "
667 "greater than the vector element type!");
668 return getNode(ISD::UNDEF, SDLoc(), VT);
671 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Op);
672 return getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
675 /// \brief Returns an ISD::VECTOR_SHUFFLE node semantically equivalent to
676 /// the shuffle node in input but with swapped operands.
678 /// Example: shuffle A, B, <0,5,2,7> -> shuffle B, A, <4,1,6,3>
679 SDValue getCommutedVectorShuffle(const ShuffleVectorSDNode &SV);
681 /// Convert Op, which must be of integer type, to the
682 /// integer type VT, by either any-extending or truncating it.
683 SDValue getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT);
685 /// Convert Op, which must be of integer type, to the
686 /// integer type VT, by either sign-extending or truncating it.
687 SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT);
689 /// Convert Op, which must be of integer type, to the
690 /// integer type VT, by either zero-extending or truncating it.
691 SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT);
693 /// Return the expression required to zero extend the Op
694 /// value assuming it was the smaller SrcTy value.
695 SDValue getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT SrcTy);
697 /// Return an operation which will any-extend the low lanes of the operand
698 /// into the specified vector type. For example,
699 /// this can convert a v16i8 into a v4i32 by any-extending the low four
700 /// lanes of the operand from i8 to i32.
701 SDValue getAnyExtendVectorInReg(SDValue Op, const SDLoc &DL, EVT VT);
703 /// Return an operation which will sign extend the low lanes of the operand
704 /// into the specified vector type. For example,
705 /// this can convert a v16i8 into a v4i32 by sign extending the low four
706 /// lanes of the operand from i8 to i32.
707 SDValue getSignExtendVectorInReg(SDValue Op, const SDLoc &DL, EVT VT);
709 /// Return an operation which will zero extend the low lanes of the operand
710 /// into the specified vector type. For example,
711 /// this can convert a v16i8 into a v4i32 by zero extending the low four
712 /// lanes of the operand from i8 to i32.
713 SDValue getZeroExtendVectorInReg(SDValue Op, const SDLoc &DL, EVT VT);
715 /// Convert Op, which must be of integer type, to the integer type VT,
716 /// by using an extension appropriate for the target's
717 /// BooleanContent for type OpVT or truncating it.
718 SDValue getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, EVT OpVT);
720 /// Create a bitwise NOT operation as (XOR Val, -1).
721 SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT);
723 /// \brief Create a logical NOT operation as (XOR Val, BooleanOne).
724 SDValue getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT);
726 /// Return a new CALLSEQ_START node, which always must have a glue result
727 /// (to ensure it's not CSE'd). CALLSEQ_START does not have a useful SDLoc.
728 SDValue getCALLSEQ_START(SDValue Chain, SDValue Op, const SDLoc &DL) {
729 SDVTList VTs = getVTList(MVT::Other, MVT::Glue);
730 SDValue Ops[] = { Chain, Op };
731 return getNode(ISD::CALLSEQ_START, DL, VTs, Ops);
734 /// Return a new CALLSEQ_END node, which always must have a
735 /// glue result (to ensure it's not CSE'd).
736 /// CALLSEQ_END does not have a useful SDLoc.
737 SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2,
738 SDValue InGlue, const SDLoc &DL) {
739 SDVTList NodeTys = getVTList(MVT::Other, MVT::Glue);
740 SmallVector<SDValue, 4> Ops;
741 Ops.push_back(Chain);
744 if (InGlue.getNode())
745 Ops.push_back(InGlue);
746 return getNode(ISD::CALLSEQ_END, DL, NodeTys, Ops);
749 /// Return true if the result of this operation is always undefined.
750 bool isUndef(unsigned Opcode, ArrayRef<SDValue> Ops);
752 /// Return an UNDEF node. UNDEF does not have a useful SDLoc.
753 SDValue getUNDEF(EVT VT) {
754 return getNode(ISD::UNDEF, SDLoc(), VT);
757 /// Return a GLOBAL_OFFSET_TABLE node. This does not have a useful SDLoc.
758 SDValue getGLOBAL_OFFSET_TABLE(EVT VT) {
759 return getNode(ISD::GLOBAL_OFFSET_TABLE, SDLoc(), VT);
762 /// Gets or creates the specified node.
764 SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
765 ArrayRef<SDUse> Ops);
766 SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
767 ArrayRef<SDValue> Ops, const SDNodeFlags *Flags = nullptr);
768 SDValue getNode(unsigned Opcode, const SDLoc &DL, ArrayRef<EVT> ResultTys,
769 ArrayRef<SDValue> Ops);
770 SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTs,
771 ArrayRef<SDValue> Ops);
773 // Specialize based on number of operands.
774 SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT);
775 SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N);
776 SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N1,
777 SDValue N2, const SDNodeFlags *Flags = nullptr);
778 SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N1,
779 SDValue N2, SDValue N3);
780 SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N1,
781 SDValue N2, SDValue N3, SDValue N4);
782 SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N1,
783 SDValue N2, SDValue N3, SDValue N4, SDValue N5);
785 // Specialize again based on number of operands for nodes with a VTList
786 // rather than a single VT.
787 SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTs);
788 SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTs, SDValue N);
789 SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTs, SDValue N1,
791 SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTs, SDValue N1,
792 SDValue N2, SDValue N3);
793 SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTs, SDValue N1,
794 SDValue N2, SDValue N3, SDValue N4);
795 SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTs, SDValue N1,
796 SDValue N2, SDValue N3, SDValue N4, SDValue N5);
798 /// Compute a TokenFactor to force all the incoming stack arguments to be
799 /// loaded from the stack. This is used in tail call lowering to protect
800 /// stack arguments from being clobbered.
801 SDValue getStackArgumentTokenFactor(SDValue Chain);
803 SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src,
804 SDValue Size, unsigned Align, bool isVol, bool AlwaysInline,
805 bool isTailCall, MachinePointerInfo DstPtrInfo,
806 MachinePointerInfo SrcPtrInfo);
808 SDValue getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src,
809 SDValue Size, unsigned Align, bool isVol, bool isTailCall,
810 MachinePointerInfo DstPtrInfo,
811 MachinePointerInfo SrcPtrInfo);
813 SDValue getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src,
814 SDValue Size, unsigned Align, bool isVol, bool isTailCall,
815 MachinePointerInfo DstPtrInfo);
817 /// Helper function to make it easier to build SetCC's if you just
818 /// have an ISD::CondCode instead of an SDValue.
820 SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS,
821 ISD::CondCode Cond) {
822 assert(LHS.getValueType().isVector() == RHS.getValueType().isVector() &&
823 "Cannot compare scalars to vectors");
824 assert(LHS.getValueType().isVector() == VT.isVector() &&
825 "Cannot compare scalars to vectors");
826 assert(Cond != ISD::SETCC_INVALID &&
827 "Cannot create a setCC of an invalid node.");
828 return getNode(ISD::SETCC, DL, VT, LHS, RHS, getCondCode(Cond));
831 /// Helper function to make it easier to build Select's if you just
832 /// have operands and don't want to check for vector.
833 SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS,
835 assert(LHS.getValueType() == RHS.getValueType() &&
836 "Cannot use select on differing types");
837 assert(VT.isVector() == LHS.getValueType().isVector() &&
838 "Cannot mix vectors and scalars");
839 return getNode(Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
843 /// Helper function to make it easier to build SelectCC's if you
844 /// just have an ISD::CondCode instead of an SDValue.
846 SDValue getSelectCC(const SDLoc &DL, SDValue LHS, SDValue RHS, SDValue True,
847 SDValue False, ISD::CondCode Cond) {
848 return getNode(ISD::SELECT_CC, DL, True.getValueType(),
849 LHS, RHS, True, False, getCondCode(Cond));
852 /// VAArg produces a result and token chain, and takes a pointer
853 /// and a source value as input.
854 SDValue getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr,
855 SDValue SV, unsigned Align);
857 /// Gets a node for an atomic cmpxchg op. There are two
858 /// valid Opcodes. ISD::ATOMIC_CMO_SWAP produces the value loaded and a
859 /// chain result. ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS produces the value loaded,
860 /// a success flag (initially i1), and a chain.
861 SDValue getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, EVT MemVT,
862 SDVTList VTs, SDValue Chain, SDValue Ptr,
863 SDValue Cmp, SDValue Swp, MachinePointerInfo PtrInfo,
864 unsigned Alignment, AtomicOrdering SuccessOrdering,
865 AtomicOrdering FailureOrdering,
866 SynchronizationScope SynchScope);
867 SDValue getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, EVT MemVT,
868 SDVTList VTs, SDValue Chain, SDValue Ptr,
869 SDValue Cmp, SDValue Swp, MachineMemOperand *MMO);
871 /// Gets a node for an atomic op, produces result (if relevant)
872 /// and chain and takes 2 operands.
873 SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDValue Chain,
874 SDValue Ptr, SDValue Val, const Value *PtrVal,
875 unsigned Alignment, AtomicOrdering Ordering,
876 SynchronizationScope SynchScope);
877 SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDValue Chain,
878 SDValue Ptr, SDValue Val, MachineMemOperand *MMO);
880 /// Gets a node for an atomic op, produces result and chain and
882 SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, EVT VT,
883 SDValue Chain, SDValue Ptr, MachineMemOperand *MMO);
885 /// Gets a node for an atomic op, produces result and chain and takes N
887 SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
888 SDVTList VTList, ArrayRef<SDValue> Ops,
889 MachineMemOperand *MMO);
891 /// Creates a MemIntrinsicNode that may produce a
892 /// result and takes a list of operands. Opcode may be INTRINSIC_VOID,
893 /// INTRINSIC_W_CHAIN, or a target-specific opcode with a value not
894 /// less than FIRST_TARGET_MEMORY_OPCODE.
895 SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList,
896 ArrayRef<SDValue> Ops, EVT MemVT,
897 MachinePointerInfo PtrInfo, unsigned Align = 0,
898 bool Vol = false, bool ReadMem = true,
899 bool WriteMem = true, unsigned Size = 0);
901 SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList,
902 ArrayRef<SDValue> Ops, EVT MemVT,
903 MachineMemOperand *MMO);
905 /// Create a MERGE_VALUES node from the given operands.
906 SDValue getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl);
908 /// Loads are not normal binary operators: their result type is not
909 /// determined by their operands, and they produce a value AND a token chain.
911 /// This function will set the MOLoad flag on MMOFlags, but you can set it if
912 /// you want. The MOStore flag must not be set.
913 SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr,
914 MachinePointerInfo PtrInfo, unsigned Alignment = 0,
915 MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
916 const AAMDNodes &AAInfo = AAMDNodes(),
917 const MDNode *Ranges = nullptr);
918 SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr,
919 MachineMemOperand *MMO);
921 getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain,
922 SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT,
923 unsigned Alignment = 0,
924 MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
925 const AAMDNodes &AAInfo = AAMDNodes());
926 SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT,
927 SDValue Chain, SDValue Ptr, EVT MemVT,
928 MachineMemOperand *MMO);
929 SDValue getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, SDValue Base,
930 SDValue Offset, ISD::MemIndexedMode AM);
931 SDValue getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT,
932 const SDLoc &dl, SDValue Chain, SDValue Ptr, SDValue Offset,
933 MachinePointerInfo PtrInfo, EVT MemVT, unsigned Alignment = 0,
934 MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
935 const AAMDNodes &AAInfo = AAMDNodes(),
936 const MDNode *Ranges = nullptr);
937 SDValue getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT,
938 const SDLoc &dl, SDValue Chain, SDValue Ptr, SDValue Offset,
939 EVT MemVT, MachineMemOperand *MMO);
941 /// Helper function to build ISD::STORE nodes.
943 /// This function will set the MOStore flag on MMOFlags, but you can set it if
944 /// you want. The MOLoad and MOInvariant flags must not be set.
946 getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr,
947 MachinePointerInfo PtrInfo, unsigned Alignment = 0,
948 MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
949 const AAMDNodes &AAInfo = AAMDNodes());
950 SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr,
951 MachineMemOperand *MMO);
953 getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr,
954 MachinePointerInfo PtrInfo, EVT TVT, unsigned Alignment = 0,
955 MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
956 const AAMDNodes &AAInfo = AAMDNodes());
957 SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
958 SDValue Ptr, EVT TVT, MachineMemOperand *MMO);
959 SDValue getIndexedStore(SDValue OrigStoe, const SDLoc &dl, SDValue Base,
960 SDValue Offset, ISD::MemIndexedMode AM);
962 /// Returns sum of the base pointer and offset.
963 SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset, const SDLoc &DL);
965 SDValue getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr,
966 SDValue Mask, SDValue Src0, EVT MemVT,
967 MachineMemOperand *MMO, ISD::LoadExtType,
968 bool IsExpanding = false);
969 SDValue getMaskedStore(SDValue Chain, const SDLoc &dl, SDValue Val,
970 SDValue Ptr, SDValue Mask, EVT MemVT,
971 MachineMemOperand *MMO, bool IsTruncating = false,
972 bool IsCompressing = false);
973 SDValue getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
974 ArrayRef<SDValue> Ops, MachineMemOperand *MMO);
975 SDValue getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
976 ArrayRef<SDValue> Ops, MachineMemOperand *MMO);
978 /// Return (create a new or find existing) a target-specific node.
979 /// TargetMemSDNode should be derived class from MemSDNode.
980 template <class TargetMemSDNode>
981 SDValue getTargetMemSDNode(SDVTList VTs, ArrayRef<SDValue> Ops,
982 const SDLoc &dl, EVT MemVT,
983 MachineMemOperand *MMO);
985 /// Construct a node to track a Value* through the backend.
986 SDValue getSrcValue(const Value *v);
988 /// Return an MDNodeSDNode which holds an MDNode.
989 SDValue getMDNode(const MDNode *MD);
991 /// Return a bitcast using the SDLoc of the value operand, and casting to the
992 /// provided type. Use getNode to set a custom SDLoc.
993 SDValue getBitcast(EVT VT, SDValue V);
995 /// Return an AddrSpaceCastSDNode.
996 SDValue getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, unsigned SrcAS,
999 /// Return the specified value casted to
1000 /// the target's desired shift amount type.
1001 SDValue getShiftAmountOperand(EVT LHSTy, SDValue Op);
1003 /// Expand the specified \c ISD::VAARG node as the Legalize pass would.
1004 SDValue expandVAArg(SDNode *Node);
1006 /// Expand the specified \c ISD::VACOPY node as the Legalize pass would.
1007 SDValue expandVACopy(SDNode *Node);
1009 /// *Mutate* the specified node in-place to have the
1010 /// specified operands. If the resultant node already exists in the DAG,
1011 /// this does not modify the specified node, instead it returns the node that
1012 /// already exists. If the resultant node does not exist in the DAG, the
1013 /// input node is returned. As a degenerate case, if you specify the same
1014 /// input operands as the node already has, the input node is returned.
1015 SDNode *UpdateNodeOperands(SDNode *N, SDValue Op);
1016 SDNode *UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2);
1017 SDNode *UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
1019 SDNode *UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
1020 SDValue Op3, SDValue Op4);
1021 SDNode *UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
1022 SDValue Op3, SDValue Op4, SDValue Op5);
1023 SDNode *UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops);
1025 /// These are used for target selectors to *mutate* the
1026 /// specified node to have the specified return type, Target opcode, and
1027 /// operands. Note that target opcodes are stored as
1028 /// ~TargetOpcode in the node opcode field. The resultant node is returned.
1029 SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT);
1030 SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT, SDValue Op1);
1031 SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT,
1032 SDValue Op1, SDValue Op2);
1033 SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT,
1034 SDValue Op1, SDValue Op2, SDValue Op3);
1035 SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT,
1036 ArrayRef<SDValue> Ops);
1037 SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT1, EVT VT2);
1038 SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT1,
1039 EVT VT2, ArrayRef<SDValue> Ops);
1040 SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT1,
1041 EVT VT2, EVT VT3, ArrayRef<SDValue> Ops);
1042 SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT1,
1043 EVT VT2, SDValue Op1);
1044 SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT1,
1045 EVT VT2, SDValue Op1, SDValue Op2);
1046 SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, SDVTList VTs,
1047 ArrayRef<SDValue> Ops);
1049 /// This *mutates* the specified node to have the specified
1050 /// return type, opcode, and operands.
1051 SDNode *MorphNodeTo(SDNode *N, unsigned Opc, SDVTList VTs,
1052 ArrayRef<SDValue> Ops);
1054 /// These are used for target selectors to create a new node
1055 /// with specified return type(s), MachineInstr opcode, and operands.
1057 /// Note that getMachineNode returns the resultant node. If there is already
1058 /// a node of the specified opcode and operands, it returns that node instead
1059 /// of the current one.
1060 MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT);
1061 MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT,
1063 MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT,
1064 SDValue Op1, SDValue Op2);
1065 MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT,
1066 SDValue Op1, SDValue Op2, SDValue Op3);
1067 MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT,
1068 ArrayRef<SDValue> Ops);
1069 MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT1,
1070 EVT VT2, SDValue Op1, SDValue Op2);
1071 MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT1,
1072 EVT VT2, SDValue Op1, SDValue Op2, SDValue Op3);
1073 MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT1,
1074 EVT VT2, ArrayRef<SDValue> Ops);
1075 MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT1,
1076 EVT VT2, EVT VT3, SDValue Op1, SDValue Op2);
1077 MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT1,
1078 EVT VT2, EVT VT3, SDValue Op1, SDValue Op2,
1080 MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT1,
1081 EVT VT2, EVT VT3, ArrayRef<SDValue> Ops);
1082 MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl,
1083 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops);
1084 MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, SDVTList VTs,
1085 ArrayRef<SDValue> Ops);
1087 /// A convenience function for creating TargetInstrInfo::EXTRACT_SUBREG nodes.
1088 SDValue getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
1091 /// A convenience function for creating TargetInstrInfo::INSERT_SUBREG nodes.
1092 SDValue getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
1093 SDValue Operand, SDValue Subreg);
1095 /// Get the specified node if it's already available, or else return NULL.
1096 SDNode *getNodeIfExists(unsigned Opcode, SDVTList VTs, ArrayRef<SDValue> Ops,
1097 const SDNodeFlags *Flags = nullptr);
1099 /// Creates a SDDbgValue node.
1100 SDDbgValue *getDbgValue(MDNode *Var, MDNode *Expr, SDNode *N, unsigned R,
1101 bool IsIndirect, uint64_t Off, const DebugLoc &DL,
1105 SDDbgValue *getConstantDbgValue(MDNode *Var, MDNode *Expr, const Value *C,
1106 uint64_t Off, const DebugLoc &DL, unsigned O);
1109 SDDbgValue *getFrameIndexDbgValue(MDNode *Var, MDNode *Expr, unsigned FI,
1110 uint64_t Off, const DebugLoc &DL,
1113 /// Remove the specified node from the system. If any of its
1114 /// operands then becomes dead, remove them as well. Inform UpdateListener
1115 /// for each node deleted.
1116 void RemoveDeadNode(SDNode *N);
1118 /// This method deletes the unreachable nodes in the
1119 /// given list, and any nodes that become unreachable as a result.
1120 void RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes);
1122 /// Modify anything using 'From' to use 'To' instead.
1123 /// This can cause recursive merging of nodes in the DAG. Use the first
1124 /// version if 'From' is known to have a single result, use the second
1125 /// if you have two nodes with identical results (or if 'To' has a superset
1126 /// of the results of 'From'), use the third otherwise.
1128 /// These methods all take an optional UpdateListener, which (if not null) is
1129 /// informed about nodes that are deleted and modified due to recursive
1130 /// changes in the dag.
1132 /// These functions only replace all existing uses. It's possible that as
1133 /// these replacements are being performed, CSE may cause the From node
1134 /// to be given new uses. These new uses of From are left in place, and
1135 /// not automatically transferred to To.
1137 void ReplaceAllUsesWith(SDValue From, SDValue Op);
1138 void ReplaceAllUsesWith(SDNode *From, SDNode *To);
1139 void ReplaceAllUsesWith(SDNode *From, const SDValue *To);
1141 /// Replace any uses of From with To, leaving
1142 /// uses of other values produced by From.Val alone.
1143 void ReplaceAllUsesOfValueWith(SDValue From, SDValue To);
1145 /// Like ReplaceAllUsesOfValueWith, but for multiple values at once.
1146 /// This correctly handles the case where
1147 /// there is an overlap between the From values and the To values.
1148 void ReplaceAllUsesOfValuesWith(const SDValue *From, const SDValue *To,
1151 /// Topological-sort the AllNodes list and a
1152 /// assign a unique node id for each node in the DAG based on their
1153 /// topological order. Returns the number of nodes.
1154 unsigned AssignTopologicalOrder();
1156 /// Move node N in the AllNodes list to be immediately
1157 /// before the given iterator Position. This may be used to update the
1158 /// topological ordering when the list of nodes is modified.
1159 void RepositionNode(allnodes_iterator Position, SDNode *N) {
1160 AllNodes.insert(Position, AllNodes.remove(N));
1163 /// Returns true if the opcode is a commutative binary operation.
1164 static bool isCommutativeBinOp(unsigned Opcode) {
1165 // FIXME: This should get its info from the td file, so that we can include
1176 case ISD::SMUL_LOHI:
1177 case ISD::UMUL_LOHI:
1192 default: return false;
1196 /// Returns an APFloat semantics tag appropriate for the given type. If VT is
1197 /// a vector type, the element semantics are returned.
1198 static const fltSemantics &EVTToAPFloatSemantics(EVT VT) {
1199 switch (VT.getScalarType().getSimpleVT().SimpleTy) {
1200 default: llvm_unreachable("Unknown FP format");
1201 case MVT::f16: return APFloat::IEEEhalf();
1202 case MVT::f32: return APFloat::IEEEsingle();
1203 case MVT::f64: return APFloat::IEEEdouble();
1204 case MVT::f80: return APFloat::x87DoubleExtended();
1205 case MVT::f128: return APFloat::IEEEquad();
1206 case MVT::ppcf128: return APFloat::PPCDoubleDouble();
1210 /// Add a dbg_value SDNode. If SD is non-null that means the
1211 /// value is produced by SD.
1212 void AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter);
1214 /// Get the debug values which reference the given SDNode.
1215 ArrayRef<SDDbgValue*> GetDbgValues(const SDNode* SD) {
1216 return DbgInfo->getSDDbgValues(SD);
1220 /// Transfer SDDbgValues. Called via ReplaceAllUses{OfValue}?With
1221 void TransferDbgValues(SDValue From, SDValue To);
1224 /// Return true if there are any SDDbgValue nodes associated
1225 /// with this SelectionDAG.
1226 bool hasDebugValues() const { return !DbgInfo->empty(); }
1228 SDDbgInfo::DbgIterator DbgBegin() { return DbgInfo->DbgBegin(); }
1229 SDDbgInfo::DbgIterator DbgEnd() { return DbgInfo->DbgEnd(); }
1230 SDDbgInfo::DbgIterator ByvalParmDbgBegin() {
1231 return DbgInfo->ByvalParmDbgBegin();
1233 SDDbgInfo::DbgIterator ByvalParmDbgEnd() {
1234 return DbgInfo->ByvalParmDbgEnd();
1239 /// Create a stack temporary, suitable for holding the specified value type.
1240 /// If minAlign is specified, the slot size will have at least that alignment.
1241 SDValue CreateStackTemporary(EVT VT, unsigned minAlign = 1);
1243 /// Create a stack temporary suitable for holding either of the specified
1245 SDValue CreateStackTemporary(EVT VT1, EVT VT2);
1247 SDValue FoldSymbolOffset(unsigned Opcode, EVT VT,
1248 const GlobalAddressSDNode *GA,
1251 SDValue FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, EVT VT,
1252 SDNode *Cst1, SDNode *Cst2);
1254 SDValue FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, EVT VT,
1255 const ConstantSDNode *Cst1,
1256 const ConstantSDNode *Cst2);
1258 SDValue FoldConstantVectorArithmetic(unsigned Opcode, const SDLoc &DL, EVT VT,
1259 ArrayRef<SDValue> Ops,
1260 const SDNodeFlags *Flags = nullptr);
1262 /// Constant fold a setcc to true or false.
1263 SDValue FoldSetCC(EVT VT, SDValue N1, SDValue N2, ISD::CondCode Cond,
1266 /// Return true if the sign bit of Op is known to be zero.
1267 /// We use this predicate to simplify operations downstream.
1268 bool SignBitIsZero(SDValue Op, unsigned Depth = 0) const;
1270 /// Return true if 'Op & Mask' is known to be zero. We
1271 /// use this predicate to simplify operations downstream. Op and Mask are
1272 /// known to be the same type.
1273 bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth = 0)
1276 /// Determine which bits of Op are known to be either zero or one and return
1277 /// them in the KnownZero/KnownOne bitsets. For vectors, the known bits are
1278 /// those that are shared by every vector element.
1279 /// Targets can implement the computeKnownBitsForTargetNode method in the
1280 /// TargetLowering class to allow target nodes to be understood.
1281 void computeKnownBits(SDValue Op, APInt &KnownZero, APInt &KnownOne,
1282 unsigned Depth = 0) const;
1284 /// Determine which bits of Op are known to be either zero or one and return
1285 /// them in the KnownZero/KnownOne bitsets. The DemandedElts argument allows
1286 /// us to only collect the known bits that are shared by the requested vector
1288 /// Targets can implement the computeKnownBitsForTargetNode method in the
1289 /// TargetLowering class to allow target nodes to be understood.
1290 void computeKnownBits(SDValue Op, APInt &KnownZero, APInt &KnownOne,
1291 const APInt &DemandedElts, unsigned Depth = 0) const;
1293 /// Used to represent the possible overflow behavior of an operation.
1294 /// Never: the operation cannot overflow.
1295 /// Always: the operation will always overflow.
1296 /// Sometime: the operation may or may not overflow.
1303 /// Determine if the result of the addition of 2 node can overflow.
1304 OverflowKind computeOverflowKind(SDValue N0, SDValue N1) const;
1306 /// Test if the given value is known to have exactly one bit set. This differs
1307 /// from computeKnownBits in that it doesn't necessarily determine which bit
1309 bool isKnownToBeAPowerOfTwo(SDValue Val) const;
1311 /// Return the number of times the sign bit of the register is replicated into
1312 /// the other bits. We know that at least 1 bit is always equal to the sign
1313 /// bit (itself), but other cases can give us information. For example,
1314 /// immediately after an "SRA X, 2", we know that the top 3 bits are all equal
1315 /// to each other, so we return 3. Targets can implement the
1316 /// ComputeNumSignBitsForTarget method in the TargetLowering class to allow
1317 /// target nodes to be understood.
1318 unsigned ComputeNumSignBits(SDValue Op, unsigned Depth = 0) const;
1320 /// Return the number of times the sign bit of the register is replicated into
1321 /// the other bits. We know that at least 1 bit is always equal to the sign
1322 /// bit (itself), but other cases can give us information. For example,
1323 /// immediately after an "SRA X, 2", we know that the top 3 bits are all equal
1324 /// to each other, so we return 3. The DemandedElts argument allows
1325 /// us to only collect the minimum sign bits of the requested vector elements.
1326 /// Targets can implement the ComputeNumSignBitsForTarget method in the
1327 /// TargetLowering class to allow target nodes to be understood.
1328 unsigned ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
1329 unsigned Depth = 0) const;
1331 /// Return true if the specified operand is an ISD::ADD with a ConstantSDNode
1332 /// on the right-hand side, or if it is an ISD::OR with a ConstantSDNode that
1333 /// is guaranteed to have the same semantics as an ADD. This handles the
1335 /// X|Cst == X+Cst iff X&Cst = 0.
1336 bool isBaseWithConstantOffset(SDValue Op) const;
1338 /// Test whether the given SDValue is known to never be NaN.
1339 bool isKnownNeverNaN(SDValue Op) const;
1341 /// Test whether the given SDValue is known to never be positive or negative
1343 bool isKnownNeverZero(SDValue Op) const;
1345 /// Test whether two SDValues are known to compare equal. This
1346 /// is true if they are the same value, or if one is negative zero and the
1347 /// other positive zero.
1348 bool isEqualTo(SDValue A, SDValue B) const;
1350 /// Return true if A and B have no common bits set. As an example, this can
1351 /// allow an 'add' to be transformed into an 'or'.
1352 bool haveNoCommonBitsSet(SDValue A, SDValue B) const;
1354 /// Utility function used by legalize and lowering to
1355 /// "unroll" a vector operation by splitting out the scalars and operating
1356 /// on each element individually. If the ResNE is 0, fully unroll the vector
1357 /// op. If ResNE is less than the width of the vector op, unroll up to ResNE.
1358 /// If the ResNE is greater than the width of the vector op, unroll the
1359 /// vector op and fill the end of the resulting vector with UNDEFS.
1360 SDValue UnrollVectorOp(SDNode *N, unsigned ResNE = 0);
1362 /// Return true if loads are next to each other and can be
1363 /// merged. Check that both are nonvolatile and if LD is loading
1364 /// 'Bytes' bytes from a location that is 'Dist' units away from the
1365 /// location that the 'Base' load is loading from.
1366 bool areNonVolatileConsecutiveLoads(LoadSDNode *LD, LoadSDNode *Base,
1367 unsigned Bytes, int Dist) const;
1369 /// Infer alignment of a load / store address. Return 0 if
1370 /// it cannot be inferred.
1371 unsigned InferPtrAlignment(SDValue Ptr) const;
1373 /// Compute the VTs needed for the low/hi parts of a type
1374 /// which is split (or expanded) into two not necessarily identical pieces.
1375 std::pair<EVT, EVT> GetSplitDestVTs(const EVT &VT) const;
1377 /// Split the vector with EXTRACT_SUBVECTOR using the provides
1378 /// VTs and return the low/high part.
1379 std::pair<SDValue, SDValue> SplitVector(const SDValue &N, const SDLoc &DL,
1380 const EVT &LoVT, const EVT &HiVT);
1382 /// Split the vector with EXTRACT_SUBVECTOR and return the low/high part.
1383 std::pair<SDValue, SDValue> SplitVector(const SDValue &N, const SDLoc &DL) {
1385 std::tie(LoVT, HiVT) = GetSplitDestVTs(N.getValueType());
1386 return SplitVector(N, DL, LoVT, HiVT);
1389 /// Split the node's operand with EXTRACT_SUBVECTOR and
1390 /// return the low/high part.
1391 std::pair<SDValue, SDValue> SplitVectorOperand(const SDNode *N, unsigned OpNo)
1393 return SplitVector(N->getOperand(OpNo), SDLoc(N));
1396 /// Append the extracted elements from Start to Count out of the vector Op
1397 /// in Args. If Count is 0, all of the elements will be extracted.
1398 void ExtractVectorElements(SDValue Op, SmallVectorImpl<SDValue> &Args,
1399 unsigned Start = 0, unsigned Count = 0);
1401 /// Compute the default alignment value for the given type.
1402 unsigned getEVTAlignment(EVT MemoryVT) const;
1404 /// Test whether the given value is a constant int or similar node.
1405 SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N);
1407 /// Test whether the given value is a constant FP or similar node.
1408 SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N);
1410 /// \returns true if \p N is any kind of constant or build_vector of
1411 /// constants, int or float. If a vector, it may not necessarily be a splat.
1412 inline bool isConstantValueOfAnyType(SDValue N) {
1413 return isConstantIntBuildVectorOrConstantInt(N) ||
1414 isConstantFPBuildVectorOrConstantFP(N);
1418 void InsertNode(SDNode *N);
1419 bool RemoveNodeFromCSEMaps(SDNode *N);
1420 void AddModifiedNodeToCSEMaps(SDNode *N);
1421 SDNode *FindModifiedNodeSlot(SDNode *N, SDValue Op, void *&InsertPos);
1422 SDNode *FindModifiedNodeSlot(SDNode *N, SDValue Op1, SDValue Op2,
1424 SDNode *FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1426 SDNode *UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &loc);
1428 void DeleteNodeNotInCSEMaps(SDNode *N);
1429 void DeallocateNode(SDNode *N);
1431 void allnodes_clear();
1433 SDNode *GetBinarySDNode(unsigned Opcode, const SDLoc &DL, SDVTList VTs,
1434 SDValue N1, SDValue N2,
1435 const SDNodeFlags *Flags = nullptr);
1437 /// Look up the node specified by ID in CSEMap. If it exists, return it. If
1438 /// not, return the insertion token that will make insertion faster. This
1439 /// overload is for nodes other than Constant or ConstantFP, use the other one
1441 SDNode *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos);
1443 /// Look up the node specified by ID in CSEMap. If it exists, return it. If
1444 /// not, return the insertion token that will make insertion faster. Performs
1445 /// additional processing for constant nodes.
1446 SDNode *FindNodeOrInsertPos(const FoldingSetNodeID &ID, const SDLoc &DL,
1449 /// List of non-single value types.
1450 FoldingSet<SDVTListNode> VTListMap;
1452 /// Maps to auto-CSE operations.
1453 std::vector<CondCodeSDNode*> CondCodeNodes;
1455 std::vector<SDNode*> ValueTypeNodes;
1456 std::map<EVT, SDNode*, EVT::compareRawBits> ExtendedValueTypeNodes;
1457 StringMap<SDNode*> ExternalSymbols;
1459 std::map<std::pair<std::string, unsigned char>,SDNode*> TargetExternalSymbols;
1460 DenseMap<MCSymbol *, SDNode *> MCSymbols;
1463 template <> struct GraphTraits<SelectionDAG*> : public GraphTraits<SDNode*> {
1464 typedef pointer_iterator<SelectionDAG::allnodes_iterator> nodes_iterator;
1465 static nodes_iterator nodes_begin(SelectionDAG *G) {
1466 return nodes_iterator(G->allnodes_begin());
1468 static nodes_iterator nodes_end(SelectionDAG *G) {
1469 return nodes_iterator(G->allnodes_end());
1473 template <class TargetMemSDNode>
1474 SDValue SelectionDAG::getTargetMemSDNode(SDVTList VTs,
1475 ArrayRef<SDValue> Ops,
1476 const SDLoc &dl, EVT MemVT,
1477 MachineMemOperand *MMO) {
1479 /// Compose node ID and try to find an existing node.
1480 FoldingSetNodeID ID;
1482 TargetMemSDNode(dl.getIROrder(), DebugLoc(), VTs, MemVT, MMO).getOpcode();
1483 ID.AddInteger(Opcode);
1484 ID.AddPointer(VTs.VTs);
1485 for (auto& Op : Ops) {
1486 ID.AddPointer(Op.getNode());
1487 ID.AddInteger(Op.getResNo());
1489 ID.AddInteger(MemVT.getRawBits());
1490 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
1491 ID.AddInteger(getSyntheticNodeSubclassData<TargetMemSDNode>(
1492 dl.getIROrder(), VTs, MemVT, MMO));
1495 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
1496 cast<TargetMemSDNode>(E)->refineAlignment(MMO);
1497 return SDValue(E, 0);
1500 /// Existing node was not found. Create a new one.
1501 auto *N = newSDNode<TargetMemSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
1503 createOperands(N, Ops);
1504 CSEMap.InsertNode(N, IP);
1506 return SDValue(N, 0);
1509 } // end namespace llvm