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