49dbd4347a14f0708f98b19d57373df74e67827c
[oota-llvm.git] / 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/ilist.h"
19 #include "llvm/ADT/FoldingSet.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/CodeGen/SelectionDAGNodes.h"
22
23 #include <cassert>
24 #include <list>
25 #include <vector>
26 #include <map>
27 #include <string>
28
29 namespace llvm {
30
31 class AliasAnalysis;
32 class TargetLowering;
33 class TargetMachine;
34 class MachineModuleInfo;
35 class MachineFunction;
36 class MachineConstantPoolValue;
37 class FunctionLoweringInfo;
38
39 /// NodeAllocatorType - The AllocatorType for allocating SDNodes. We use
40 /// pool allocation with recycling.
41 ///
42 typedef RecyclingAllocator<BumpPtrAllocator, SDNode, sizeof(LargestSDNode),
43                            AlignOf<MostAlignedSDNode>::Alignment>
44   NodeAllocatorType;
45
46 template<> class ilist_traits<SDNode> : public ilist_default_traits<SDNode> {
47   mutable SDNode Sentinel;
48 public:
49   ilist_traits() : Sentinel(ISD::DELETED_NODE, SDVTList()) {}
50
51   SDNode *createSentinel() const {
52     return &Sentinel;
53   }
54   static void destroySentinel(SDNode *) {}
55
56   static void deleteNode(SDNode *) {
57     assert(0 && "ilist_traits<SDNode> shouldn't see a deleteNode call!");
58   }
59 private:
60   static void createNode(const SDNode &);
61 };
62
63 /// SelectionDAG class - This is used to represent a portion of an LLVM function
64 /// in a low-level Data Dependence DAG representation suitable for instruction
65 /// selection.  This DAG is constructed as the first step of instruction
66 /// selection in order to allow implementation of machine specific optimizations
67 /// and code simplifications.
68 ///
69 /// The representation used by the SelectionDAG is a target-independent
70 /// representation, which has some similarities to the GCC RTL representation,
71 /// but is significantly more simple, powerful, and is a graph form instead of a
72 /// linear form.
73 ///
74 class SelectionDAG {
75   TargetLowering &TLI;
76   MachineFunction &MF;
77   FunctionLoweringInfo &FLI;
78   MachineModuleInfo *MMI;
79
80   /// Root - The root of the entire DAG.  EntryNode - The starting token.
81   SDValue Root, EntryNode;
82
83   /// AllNodes - A linked list of nodes in the current DAG.
84   ilist<SDNode> AllNodes;
85
86   /// NodeAllocator - Pool allocation for nodes. The allocator isn't
87   /// allocated inside this class because we want to reuse a single
88   /// recycler across multiple SelectionDAG runs.
89   NodeAllocatorType &NodeAllocator;
90
91   /// CSEMap - This structure is used to memoize nodes, automatically performing
92   /// CSE with existing nodes with a duplicate is requested.
93   FoldingSet<SDNode> CSEMap;
94
95   /// Allocator - Pool allocation for misc. objects that are created once per
96   /// SelectionDAG.
97   BumpPtrAllocator Allocator;
98
99   /// VerifyNode - Sanity check the given node.  Aborts if it is invalid.
100   void VerifyNode(SDNode *N);
101
102 public:
103   SelectionDAG(TargetLowering &tli, MachineFunction &mf, 
104                FunctionLoweringInfo &fli, MachineModuleInfo *mmi,
105                NodeAllocatorType &nodeallocator)
106   : TLI(tli), MF(mf), FLI(fli), MMI(mmi), NodeAllocator(nodeallocator) {
107     EntryNode = Root = getNode(ISD::EntryToken, MVT::Other);
108   }
109   ~SelectionDAG();
110
111   MachineFunction &getMachineFunction() const { return MF; }
112   const TargetMachine &getTarget() const;
113   TargetLowering &getTargetLoweringInfo() const { return TLI; }
114   FunctionLoweringInfo &getFunctionLoweringInfo() const { return FLI; }
115   MachineModuleInfo *getMachineModuleInfo() const { return MMI; }
116
117   /// viewGraph - Pop up a GraphViz/gv window with the DAG rendered using 'dot'.
118   ///
119   void viewGraph(const std::string &Title);
120   void viewGraph() { return viewGraph(""); }
121   
122 #ifndef NDEBUG
123   std::map<const SDNode *, std::string> NodeGraphAttrs;
124 #endif
125
126   /// clearGraphAttrs - Clear all previously defined node graph attributes.
127   /// Intended to be used from a debugging tool (eg. gdb).
128   void clearGraphAttrs();
129   
130   /// setGraphAttrs - Set graph attributes for a node. (eg. "color=red".)
131   ///
132   void setGraphAttrs(const SDNode *N, const char *Attrs);
133   
134   /// getGraphAttrs - Get graph attributes for a node. (eg. "color=red".)
135   /// Used from getNodeAttributes.
136   const std::string getGraphAttrs(const SDNode *N) const;
137   
138   /// setGraphColor - Convenience for setting node color attribute.
139   ///
140   void setGraphColor(const SDNode *N, const char *Color);
141
142   typedef ilist<SDNode>::const_iterator allnodes_const_iterator;
143   allnodes_const_iterator allnodes_begin() const { return AllNodes.begin(); }
144   allnodes_const_iterator allnodes_end() const { return AllNodes.end(); }
145   typedef ilist<SDNode>::iterator allnodes_iterator;
146   allnodes_iterator allnodes_begin() { return AllNodes.begin(); }
147   allnodes_iterator allnodes_end() { return AllNodes.end(); }
148   ilist<SDNode>::size_type allnodes_size() const {
149     return AllNodes.size();
150   }
151   
152   /// getRoot - Return the root tag of the SelectionDAG.
153   ///
154   const SDValue &getRoot() const { return Root; }
155
156   /// getEntryNode - Return the token chain corresponding to the entry of the
157   /// function.
158   const SDValue &getEntryNode() const { return EntryNode; }
159
160   /// setRoot - Set the current root tag of the SelectionDAG.
161   ///
162   const SDValue &setRoot(SDValue N) {
163     assert((!N.Val || N.getValueType() == MVT::Other) &&
164            "DAG root value is not a chain!");
165     return Root = N;
166   }
167
168   /// Combine - This iterates over the nodes in the SelectionDAG, folding
169   /// certain types of nodes together, or eliminating superfluous nodes.  When
170   /// the AfterLegalize argument is set to 'true', Combine takes care not to
171   /// generate any nodes that will be illegal on the target.
172   void Combine(bool AfterLegalize, AliasAnalysis &AA);
173   
174   /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
175   /// only uses types natively supported by the target.
176   ///
177   /// Note that this is an involved process that may invalidate pointers into
178   /// the graph.
179   void LegalizeTypes();
180   
181   /// Legalize - This transforms the SelectionDAG into a SelectionDAG that is
182   /// compatible with the target instruction selector, as indicated by the
183   /// TargetLowering object.
184   ///
185   /// Note that this is an involved process that may invalidate pointers into
186   /// the graph.
187   void Legalize();
188
189   /// RemoveDeadNodes - This method deletes all unreachable nodes in the
190   /// SelectionDAG.
191   void RemoveDeadNodes();
192
193   /// DeleteNode - Remove the specified node from the system.  This node must
194   /// have no referrers.
195   void DeleteNode(SDNode *N);
196
197   /// getVTList - Return an SDVTList that represents the list of values
198   /// specified.
199   SDVTList getVTList(MVT VT);
200   SDVTList getVTList(MVT VT1, MVT VT2);
201   SDVTList getVTList(MVT VT1, MVT VT2, MVT VT3);
202   SDVTList getVTList(const MVT *VTs, unsigned NumVTs);
203   
204   /// getNodeValueTypes - These are obsolete, use getVTList instead.
205   const MVT *getNodeValueTypes(MVT VT) {
206     return getVTList(VT).VTs;
207   }
208   const MVT *getNodeValueTypes(MVT VT1, MVT VT2) {
209     return getVTList(VT1, VT2).VTs;
210   }
211   const MVT *getNodeValueTypes(MVT VT1, MVT VT2, MVT VT3) {
212     return getVTList(VT1, VT2, VT3).VTs;
213   }
214   const MVT *getNodeValueTypes(const std::vector<MVT> &vtList) {
215     return getVTList(&vtList[0], (unsigned)vtList.size()).VTs;
216   }
217   
218   
219   //===--------------------------------------------------------------------===//
220   // Node creation methods.
221   //
222   SDValue getConstant(uint64_t Val, MVT VT, bool isTarget = false);
223   SDValue getConstant(const APInt &Val, MVT VT, bool isTarget = false);
224   SDValue getIntPtrConstant(uint64_t Val, bool isTarget = false);
225   SDValue getTargetConstant(uint64_t Val, MVT VT) {
226     return getConstant(Val, VT, true);
227   }
228   SDValue getTargetConstant(const APInt &Val, MVT VT) {
229     return getConstant(Val, VT, true);
230   }
231   SDValue getConstantFP(double Val, MVT VT, bool isTarget = false);
232   SDValue getConstantFP(const APFloat& Val, MVT VT, bool isTarget = false);
233   SDValue getTargetConstantFP(double Val, MVT VT) {
234     return getConstantFP(Val, VT, true);
235   }
236   SDValue getTargetConstantFP(const APFloat& Val, MVT VT) {
237     return getConstantFP(Val, VT, true);
238   }
239   SDValue getGlobalAddress(const GlobalValue *GV, MVT VT,
240                              int offset = 0, bool isTargetGA = false);
241   SDValue getTargetGlobalAddress(const GlobalValue *GV, MVT VT,
242                                    int offset = 0) {
243     return getGlobalAddress(GV, VT, offset, true);
244   }
245   SDValue getFrameIndex(int FI, MVT VT, bool isTarget = false);
246   SDValue getTargetFrameIndex(int FI, MVT VT) {
247     return getFrameIndex(FI, VT, true);
248   }
249   SDValue getJumpTable(int JTI, MVT VT, bool isTarget = false);
250   SDValue getTargetJumpTable(int JTI, MVT VT) {
251     return getJumpTable(JTI, VT, true);
252   }
253   SDValue getConstantPool(Constant *C, MVT VT,
254                             unsigned Align = 0, int Offs = 0, bool isT=false);
255   SDValue getTargetConstantPool(Constant *C, MVT VT,
256                                   unsigned Align = 0, int Offset = 0) {
257     return getConstantPool(C, VT, Align, Offset, true);
258   }
259   SDValue getConstantPool(MachineConstantPoolValue *C, MVT VT,
260                             unsigned Align = 0, int Offs = 0, bool isT=false);
261   SDValue getTargetConstantPool(MachineConstantPoolValue *C,
262                                   MVT VT, unsigned Align = 0,
263                                   int Offset = 0) {
264     return getConstantPool(C, VT, Align, Offset, true);
265   }
266   SDValue getBasicBlock(MachineBasicBlock *MBB);
267   SDValue getExternalSymbol(const char *Sym, MVT VT);
268   SDValue getTargetExternalSymbol(const char *Sym, MVT VT);
269   SDValue getArgFlags(ISD::ArgFlagsTy Flags);
270   SDValue getValueType(MVT);
271   SDValue getRegister(unsigned Reg, MVT VT);
272   SDValue getDbgStopPoint(SDValue Root, unsigned Line, unsigned Col,
273                             const CompileUnitDesc *CU);
274   SDValue getLabel(unsigned Opcode, SDValue Root, unsigned LabelID);
275
276   SDValue getCopyToReg(SDValue Chain, unsigned Reg, SDValue N) {
277     return getNode(ISD::CopyToReg, MVT::Other, Chain,
278                    getRegister(Reg, N.getValueType()), N);
279   }
280
281   // This version of the getCopyToReg method takes an extra operand, which
282   // indicates that there is potentially an incoming flag value (if Flag is not
283   // null) and that there should be a flag result.
284   SDValue getCopyToReg(SDValue Chain, unsigned Reg, SDValue N,
285                          SDValue Flag) {
286     const MVT *VTs = getNodeValueTypes(MVT::Other, MVT::Flag);
287     SDValue Ops[] = { Chain, getRegister(Reg, N.getValueType()), N, Flag };
288     return getNode(ISD::CopyToReg, VTs, 2, Ops, Flag.Val ? 4 : 3);
289   }
290
291   // Similar to last getCopyToReg() except parameter Reg is a SDValue
292   SDValue getCopyToReg(SDValue Chain, SDValue Reg, SDValue N,
293                          SDValue Flag) {
294     const MVT *VTs = getNodeValueTypes(MVT::Other, MVT::Flag);
295     SDValue Ops[] = { Chain, Reg, N, Flag };
296     return getNode(ISD::CopyToReg, VTs, 2, Ops, Flag.Val ? 4 : 3);
297   }
298   
299   SDValue getCopyFromReg(SDValue Chain, unsigned Reg, MVT VT) {
300     const MVT *VTs = getNodeValueTypes(VT, MVT::Other);
301     SDValue Ops[] = { Chain, getRegister(Reg, VT) };
302     return getNode(ISD::CopyFromReg, VTs, 2, Ops, 2);
303   }
304   
305   // This version of the getCopyFromReg method takes an extra operand, which
306   // indicates that there is potentially an incoming flag value (if Flag is not
307   // null) and that there should be a flag result.
308   SDValue getCopyFromReg(SDValue Chain, unsigned Reg, MVT VT,
309                            SDValue Flag) {
310     const MVT *VTs = getNodeValueTypes(VT, MVT::Other, MVT::Flag);
311     SDValue Ops[] = { Chain, getRegister(Reg, VT), Flag };
312     return getNode(ISD::CopyFromReg, VTs, 3, Ops, Flag.Val ? 3 : 2);
313   }
314
315   SDValue getCondCode(ISD::CondCode Cond);
316
317   /// getZeroExtendInReg - Return the expression required to zero extend the Op
318   /// value assuming it was the smaller SrcTy value.
319   SDValue getZeroExtendInReg(SDValue Op, MVT SrcTy);
320   
321   /// getCALLSEQ_START - Return a new CALLSEQ_START node, which always must have
322   /// a flag result (to ensure it's not CSE'd).
323   SDValue getCALLSEQ_START(SDValue Chain, SDValue Op) {
324     const MVT *VTs = getNodeValueTypes(MVT::Other, MVT::Flag);
325     SDValue Ops[] = { Chain,  Op };
326     return getNode(ISD::CALLSEQ_START, VTs, 2, Ops, 2);
327   }
328
329   /// getCALLSEQ_END - Return a new CALLSEQ_END node, which always must have a
330   /// flag result (to ensure it's not CSE'd).
331   SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2,
332                            SDValue InFlag) {
333     SDVTList NodeTys = getVTList(MVT::Other, MVT::Flag);
334     SmallVector<SDValue, 4> Ops;
335     Ops.push_back(Chain);
336     Ops.push_back(Op1);
337     Ops.push_back(Op2);
338     Ops.push_back(InFlag);
339     return getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0],
340                    (unsigned)Ops.size() - (InFlag.Val == 0 ? 1 : 0));
341   }
342
343   /// getNode - Gets or creates the specified node.
344   ///
345   SDValue getNode(unsigned Opcode, MVT VT);
346   SDValue getNode(unsigned Opcode, MVT VT, SDValue N);
347   SDValue getNode(unsigned Opcode, MVT VT, SDValue N1, SDValue N2);
348   SDValue getNode(unsigned Opcode, MVT VT,
349                     SDValue N1, SDValue N2, SDValue N3);
350   SDValue getNode(unsigned Opcode, MVT VT,
351                     SDValue N1, SDValue N2, SDValue N3, SDValue N4);
352   SDValue getNode(unsigned Opcode, MVT VT,
353                     SDValue N1, SDValue N2, SDValue N3, SDValue N4,
354                     SDValue N5);
355   SDValue getNode(unsigned Opcode, MVT VT,
356                     const SDValue *Ops, unsigned NumOps);
357   SDValue getNode(unsigned Opcode, MVT VT,
358                     const SDUse *Ops, unsigned NumOps);
359   SDValue getNode(unsigned Opcode, const std::vector<MVT> &ResultTys,
360                     const SDValue *Ops, unsigned NumOps);
361   SDValue getNode(unsigned Opcode, const MVT *VTs, unsigned NumVTs,
362                     const SDValue *Ops, unsigned NumOps);
363   SDValue getNode(unsigned Opcode, SDVTList VTs);
364   SDValue getNode(unsigned Opcode, SDVTList VTs, SDValue N);
365   SDValue getNode(unsigned Opcode, SDVTList VTs, SDValue N1, SDValue N2);
366   SDValue getNode(unsigned Opcode, SDVTList VTs,
367                     SDValue N1, SDValue N2, SDValue N3);
368   SDValue getNode(unsigned Opcode, SDVTList VTs,
369                     SDValue N1, SDValue N2, SDValue N3, SDValue N4);
370   SDValue getNode(unsigned Opcode, SDVTList VTs,
371                     SDValue N1, SDValue N2, SDValue N3, SDValue N4,
372                     SDValue N5);
373   SDValue getNode(unsigned Opcode, SDVTList VTs,
374                     const SDValue *Ops, unsigned NumOps);
375
376   SDValue getMemcpy(SDValue Chain, SDValue Dst, SDValue Src,
377                       SDValue Size, unsigned Align,
378                       bool AlwaysInline,
379                       const Value *DstSV, uint64_t DstSVOff,
380                       const Value *SrcSV, uint64_t SrcSVOff);
381
382   SDValue getMemmove(SDValue Chain, SDValue Dst, SDValue Src,
383                        SDValue Size, unsigned Align,
384                        const Value *DstSV, uint64_t DstOSVff,
385                        const Value *SrcSV, uint64_t SrcSVOff);
386
387   SDValue getMemset(SDValue Chain, SDValue Dst, SDValue Src,
388                       SDValue Size, unsigned Align,
389                       const Value *DstSV, uint64_t DstSVOff);
390
391   /// getSetCC - Helper function to make it easier to build SetCC's if you just
392   /// have an ISD::CondCode instead of an SDValue.
393   ///
394   SDValue getSetCC(MVT VT, SDValue LHS, SDValue RHS,
395                      ISD::CondCode Cond) {
396     return getNode(ISD::SETCC, VT, LHS, RHS, getCondCode(Cond));
397   }
398
399   /// getVSetCC - Helper function to make it easier to build VSetCC's nodes
400   /// if you just have an ISD::CondCode instead of an SDValue.
401   ///
402   SDValue getVSetCC(MVT VT, SDValue LHS, SDValue RHS,
403                       ISD::CondCode Cond) {
404     return getNode(ISD::VSETCC, VT, LHS, RHS, getCondCode(Cond));
405   }
406
407   /// getSelectCC - Helper function to make it easier to build SelectCC's if you
408   /// just have an ISD::CondCode instead of an SDValue.
409   ///
410   SDValue getSelectCC(SDValue LHS, SDValue RHS,
411                         SDValue True, SDValue False, ISD::CondCode Cond) {
412     return getNode(ISD::SELECT_CC, True.getValueType(), LHS, RHS, True, False,
413                    getCondCode(Cond));
414   }
415   
416   /// getVAArg - VAArg produces a result and token chain, and takes a pointer
417   /// and a source value as input.
418   SDValue getVAArg(MVT VT, SDValue Chain, SDValue Ptr,
419                      SDValue SV);
420
421   /// getAtomic - Gets a node for an atomic op, produces result and chain, takes
422   /// 3 operands
423   SDValue getAtomic(unsigned Opcode, SDValue Chain, SDValue Ptr, 
424                       SDValue Cmp, SDValue Swp, const Value* PtrVal,
425                       unsigned Alignment=0);
426
427   /// getAtomic - Gets a node for an atomic op, produces result and chain, takes
428   /// 2 operands
429   SDValue getAtomic(unsigned Opcode, SDValue Chain, SDValue Ptr, 
430                       SDValue Val, const Value* PtrVal,
431                       unsigned Alignment = 0);
432
433   /// getMergeValues - Create a MERGE_VALUES node from the given operands.
434   /// Allowed to return something different (and simpler) if Simplify is true.
435   SDValue getMergeValues(const SDValue *Ops, unsigned NumOps,
436                            bool Simplify = true);
437
438   /// getMergeValues - Create a MERGE_VALUES node from the given types and ops.
439   /// Allowed to return something different (and simpler) if Simplify is true.
440   /// May be faster than the above version if VTs is known and NumOps is large.
441   SDValue getMergeValues(SDVTList VTs, const SDValue *Ops, unsigned NumOps,
442                            bool Simplify = true) {
443     if (Simplify && NumOps == 1)
444       return Ops[0];
445     return getNode(ISD::MERGE_VALUES, VTs, Ops, NumOps);
446   }
447
448   /// getLoad - Loads are not normal binary operators: their result type is not
449   /// determined by their operands, and they produce a value AND a token chain.
450   ///
451   SDValue getLoad(MVT VT, SDValue Chain, SDValue Ptr,
452                     const Value *SV, int SVOffset, bool isVolatile=false,
453                     unsigned Alignment=0);
454   SDValue getExtLoad(ISD::LoadExtType ExtType, MVT VT,
455                        SDValue Chain, SDValue Ptr, const Value *SV,
456                        int SVOffset, MVT EVT, bool isVolatile=false,
457                        unsigned Alignment=0);
458   SDValue getIndexedLoad(SDValue OrigLoad, SDValue Base,
459                            SDValue Offset, ISD::MemIndexedMode AM);
460   SDValue getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
461                     MVT VT, SDValue Chain,
462                     SDValue Ptr, SDValue Offset,
463                     const Value *SV, int SVOffset, MVT EVT,
464                     bool isVolatile=false, unsigned Alignment=0);
465
466   /// getStore - Helper function to build ISD::STORE nodes.
467   ///
468   SDValue getStore(SDValue Chain, SDValue Val, SDValue Ptr,
469                      const Value *SV, int SVOffset, bool isVolatile=false,
470                      unsigned Alignment=0);
471   SDValue getTruncStore(SDValue Chain, SDValue Val, SDValue Ptr,
472                           const Value *SV, int SVOffset, MVT TVT,
473                           bool isVolatile=false, unsigned Alignment=0);
474   SDValue getIndexedStore(SDValue OrigStoe, SDValue Base,
475                            SDValue Offset, ISD::MemIndexedMode AM);
476
477   // getSrcValue - Construct a node to track a Value* through the backend.
478   SDValue getSrcValue(const Value *v);
479
480   // getMemOperand - Construct a node to track a memory reference
481   // through the backend.
482   SDValue getMemOperand(const MachineMemOperand &MO);
483
484   /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
485   /// specified operands.  If the resultant node already exists in the DAG,
486   /// this does not modify the specified node, instead it returns the node that
487   /// already exists.  If the resultant node does not exist in the DAG, the
488   /// input node is returned.  As a degenerate case, if you specify the same
489   /// input operands as the node already has, the input node is returned.
490   SDValue UpdateNodeOperands(SDValue N, SDValue Op);
491   SDValue UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2);
492   SDValue UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
493                                SDValue Op3);
494   SDValue UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
495                                SDValue Op3, SDValue Op4);
496   SDValue UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
497                                SDValue Op3, SDValue Op4, SDValue Op5);
498   SDValue UpdateNodeOperands(SDValue N,
499                                const SDValue *Ops, unsigned NumOps);
500   
501   /// SelectNodeTo - These are used for target selectors to *mutate* the
502   /// specified node to have the specified return type, Target opcode, and
503   /// operands.  Note that target opcodes are stored as
504   /// ~TargetOpcode in the node opcode field.  The resultant node is returned.
505   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, MVT VT);
506   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, MVT VT, SDValue Op1);
507   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, MVT VT,
508                        SDValue Op1, SDValue Op2);
509   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, MVT VT,
510                        SDValue Op1, SDValue Op2, SDValue Op3);
511   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, MVT VT,
512                        const SDValue *Ops, unsigned NumOps);
513   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, MVT VT1, MVT VT2);
514   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, MVT VT1,
515                        MVT VT2, const SDValue *Ops, unsigned NumOps);
516   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, MVT VT1,
517                        MVT VT2, MVT VT3, const SDValue *Ops, unsigned NumOps);
518   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, MVT VT1,
519                        MVT VT2, SDValue Op1);
520   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, MVT VT1,
521                        MVT VT2, SDValue Op1, SDValue Op2);
522   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, MVT VT1,
523                        MVT VT2, SDValue Op1, SDValue Op2, SDValue Op3);
524   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, SDVTList VTs,
525                        const SDValue *Ops, unsigned NumOps);
526
527   /// MorphNodeTo - These *mutate* the specified node to have the specified
528   /// return type, opcode, and operands.
529   SDNode *MorphNodeTo(SDNode *N, unsigned Opc, MVT VT);
530   SDNode *MorphNodeTo(SDNode *N, unsigned Opc, MVT VT, SDValue Op1);
531   SDNode *MorphNodeTo(SDNode *N, unsigned Opc, MVT VT,
532                       SDValue Op1, SDValue Op2);
533   SDNode *MorphNodeTo(SDNode *N, unsigned Opc, MVT VT,
534                       SDValue Op1, SDValue Op2, SDValue Op3);
535   SDNode *MorphNodeTo(SDNode *N, unsigned Opc, MVT VT,
536                       const SDValue *Ops, unsigned NumOps);
537   SDNode *MorphNodeTo(SDNode *N, unsigned Opc, MVT VT1, MVT VT2);
538   SDNode *MorphNodeTo(SDNode *N, unsigned Opc, MVT VT1,
539                       MVT VT2, const SDValue *Ops, unsigned NumOps);
540   SDNode *MorphNodeTo(SDNode *N, unsigned Opc, MVT VT1,
541                       MVT VT2, MVT VT3, const SDValue *Ops, unsigned NumOps);
542   SDNode *MorphNodeTo(SDNode *N, unsigned Opc, MVT VT1,
543                       MVT VT2, SDValue Op1);
544   SDNode *MorphNodeTo(SDNode *N, unsigned Opc, MVT VT1,
545                       MVT VT2, SDValue Op1, SDValue Op2);
546   SDNode *MorphNodeTo(SDNode *N, unsigned Opc, MVT VT1,
547                       MVT VT2, SDValue Op1, SDValue Op2, SDValue Op3);
548   SDNode *MorphNodeTo(SDNode *N, unsigned Opc, SDVTList VTs,
549                       const SDValue *Ops, unsigned NumOps);
550
551   /// getTargetNode - These are used for target selectors to create a new node
552   /// with specified return type(s), target opcode, and operands.
553   ///
554   /// Note that getTargetNode returns the resultant node.  If there is already a
555   /// node of the specified opcode and operands, it returns that node instead of
556   /// the current one.
557   SDNode *getTargetNode(unsigned Opcode, MVT VT);
558   SDNode *getTargetNode(unsigned Opcode, MVT VT, SDValue Op1);
559   SDNode *getTargetNode(unsigned Opcode, MVT VT, SDValue Op1, SDValue Op2);
560   SDNode *getTargetNode(unsigned Opcode, MVT VT,
561                         SDValue Op1, SDValue Op2, SDValue Op3);
562   SDNode *getTargetNode(unsigned Opcode, MVT VT,
563                         const SDValue *Ops, unsigned NumOps);
564   SDNode *getTargetNode(unsigned Opcode, MVT VT1, MVT VT2);
565   SDNode *getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, SDValue Op1);
566   SDNode *getTargetNode(unsigned Opcode, MVT VT1,
567                         MVT VT2, SDValue Op1, SDValue Op2);
568   SDNode *getTargetNode(unsigned Opcode, MVT VT1,
569                         MVT VT2, SDValue Op1, SDValue Op2, SDValue Op3);
570   SDNode *getTargetNode(unsigned Opcode, MVT VT1, MVT VT2,
571                         const SDValue *Ops, unsigned NumOps);
572   SDNode *getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
573                         SDValue Op1, SDValue Op2);
574   SDNode *getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
575                         SDValue Op1, SDValue Op2, SDValue Op3);
576   SDNode *getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
577                         const SDValue *Ops, unsigned NumOps);
578   SDNode *getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3, MVT VT4,
579                         const SDValue *Ops, unsigned NumOps);
580   SDNode *getTargetNode(unsigned Opcode, const std::vector<MVT> &ResultTys,
581                         const SDValue *Ops, unsigned NumOps);
582
583   /// getNodeIfExists - Get the specified node if it's already available, or
584   /// else return NULL.
585   SDNode *getNodeIfExists(unsigned Opcode, SDVTList VTs,
586                           const SDValue *Ops, unsigned NumOps);
587   
588   /// DAGUpdateListener - Clients of various APIs that cause global effects on
589   /// the DAG can optionally implement this interface.  This allows the clients
590   /// to handle the various sorts of updates that happen.
591   class DAGUpdateListener {
592   public:
593     virtual ~DAGUpdateListener();
594
595     /// NodeDeleted - The node N that was deleted and, if E is not null, an
596     /// equivalent node E that replaced it.
597     virtual void NodeDeleted(SDNode *N, SDNode *E) = 0;
598
599     /// NodeUpdated - The node N that was updated.
600     virtual void NodeUpdated(SDNode *N) = 0;
601   };
602   
603   /// RemoveDeadNode - Remove the specified node from the system. If any of its
604   /// operands then becomes dead, remove them as well. Inform UpdateListener
605   /// for each node deleted.
606   void RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener = 0);
607   
608   /// RemoveDeadNodes - This method deletes the unreachable nodes in the
609   /// given list, and any nodes that become unreachable as a result.
610   void RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
611                        DAGUpdateListener *UpdateListener = 0);
612
613   /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
614   /// This can cause recursive merging of nodes in the DAG.  Use the first
615   /// version if 'From' is known to have a single result, use the second
616   /// if you have two nodes with identical results, use the third otherwise.
617   ///
618   /// These methods all take an optional UpdateListener, which (if not null) is 
619   /// informed about nodes that are deleted and modified due to recursive
620   /// changes in the dag.
621   ///
622   void ReplaceAllUsesWith(SDValue From, SDValue Op,
623                           DAGUpdateListener *UpdateListener = 0);
624   void ReplaceAllUsesWith(SDNode *From, SDNode *To,
625                           DAGUpdateListener *UpdateListener = 0);
626   void ReplaceAllUsesWith(SDNode *From, const SDValue *To,
627                           DAGUpdateListener *UpdateListener = 0);
628
629   /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
630   /// uses of other values produced by From.Val alone.
631   void ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
632                                  DAGUpdateListener *UpdateListener = 0);
633
634   /// ReplaceAllUsesOfValuesWith - Like ReplaceAllUsesOfValueWith, but
635   /// for multiple values at once. This correctly handles the case where
636   /// there is an overlap between the From values and the To values.
637   void ReplaceAllUsesOfValuesWith(const SDValue *From, const SDValue *To,
638                                   unsigned Num,
639                                   DAGUpdateListener *UpdateListener = 0);
640
641   /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
642   /// based on their topological order. It returns the maximum id and a vector
643   /// of the SDNodes* in assigned order by reference.
644   unsigned AssignTopologicalOrder(std::vector<SDNode*> &TopOrder);
645
646   /// isCommutativeBinOp - Returns true if the opcode is a commutative binary
647   /// operation.
648   static bool isCommutativeBinOp(unsigned Opcode) {
649     // FIXME: This should get its info from the td file, so that we can include
650     // target info.
651     switch (Opcode) {
652     case ISD::ADD:
653     case ISD::MUL:
654     case ISD::MULHU:
655     case ISD::MULHS:
656     case ISD::SMUL_LOHI:
657     case ISD::UMUL_LOHI:
658     case ISD::FADD:
659     case ISD::FMUL:
660     case ISD::AND:
661     case ISD::OR:
662     case ISD::XOR:
663     case ISD::ADDC: 
664     case ISD::ADDE: return true;
665     default: return false;
666     }
667   }
668
669   void dump() const;
670
671   /// CreateStackTemporary - Create a stack temporary, suitable for holding the
672   /// specified value type.  If minAlign is specified, the slot size will have
673   /// at least that alignment.
674   SDValue CreateStackTemporary(MVT VT, unsigned minAlign = 1);
675   
676   /// FoldSetCC - Constant fold a setcc to true or false.
677   SDValue FoldSetCC(MVT VT, SDValue N1,
678                       SDValue N2, ISD::CondCode Cond);
679   
680   /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
681   /// use this predicate to simplify operations downstream.
682   bool SignBitIsZero(SDValue Op, unsigned Depth = 0) const;
683
684   /// MaskedValueIsZero - Return true if 'Op & Mask' is known to be zero.  We
685   /// use this predicate to simplify operations downstream.  Op and Mask are
686   /// known to be the same type.
687   bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth = 0)
688     const;
689   
690   /// ComputeMaskedBits - Determine which of the bits specified in Mask are
691   /// known to be either zero or one and return them in the KnownZero/KnownOne
692   /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
693   /// processing.  Targets can implement the computeMaskedBitsForTargetNode 
694   /// method in the TargetLowering class to allow target nodes to be understood.
695   void ComputeMaskedBits(SDValue Op, const APInt &Mask, APInt &KnownZero,
696                          APInt &KnownOne, unsigned Depth = 0) const;
697
698   /// ComputeNumSignBits - Return the number of times the sign bit of the
699   /// register is replicated into the other bits.  We know that at least 1 bit
700   /// is always equal to the sign bit (itself), but other cases can give us
701   /// information.  For example, immediately after an "SRA X, 2", we know that
702   /// the top 3 bits are all equal to each other, so we return 3.  Targets can
703   /// implement the ComputeNumSignBitsForTarget method in the TargetLowering
704   /// class to allow target nodes to be understood.
705   unsigned ComputeNumSignBits(SDValue Op, unsigned Depth = 0) const;
706
707   /// isVerifiedDebugInfoDesc - Returns true if the specified SDValue has
708   /// been verified as a debug information descriptor.
709   bool isVerifiedDebugInfoDesc(SDValue Op) const;
710
711   /// getShuffleScalarElt - Returns the scalar element that will make up the ith
712   /// element of the result of the vector shuffle.
713   SDValue getShuffleScalarElt(const SDNode *N, unsigned Idx);
714   
715 private:
716   void RemoveNodeFromCSEMaps(SDNode *N);
717   SDNode *AddNonLeafNodeToCSEMaps(SDNode *N);
718   SDNode *FindModifiedNodeSlot(SDNode *N, SDValue Op, void *&InsertPos);
719   SDNode *FindModifiedNodeSlot(SDNode *N, SDValue Op1, SDValue Op2,
720                                void *&InsertPos);
721   SDNode *FindModifiedNodeSlot(SDNode *N, const SDValue *Ops, unsigned NumOps,
722                                void *&InsertPos);
723
724   void DeleteNodeNotInCSEMaps(SDNode *N);
725
726   unsigned getMVTAlignment(MVT MemoryVT) const;
727   
728   // List of non-single value types.
729   std::vector<SDVTList> VTList;
730   
731   // Maps to auto-CSE operations.
732   std::vector<CondCodeSDNode*> CondCodeNodes;
733
734   std::vector<SDNode*> ValueTypeNodes;
735   std::map<MVT, SDNode*, MVT::compareRawBits> ExtendedValueTypeNodes;
736   StringMap<SDNode*> ExternalSymbols;
737   StringMap<SDNode*> TargetExternalSymbols;
738 };
739
740 template <> struct GraphTraits<SelectionDAG*> : public GraphTraits<SDNode*> {
741   typedef SelectionDAG::allnodes_iterator nodes_iterator;
742   static nodes_iterator nodes_begin(SelectionDAG *G) {
743     return G->allnodes_begin();
744   }
745   static nodes_iterator nodes_end(SelectionDAG *G) {
746     return G->allnodes_end();
747   }
748 };
749
750 }  // end namespace llvm
751
752 #endif