66be160afecdc81fb91baf43034917f7502fe5be
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAG.cpp
1 //===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
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 implements the SelectionDAG class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "SDNodeDbgValue.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/Assembly/Writer.h"
24 #include "llvm/CodeGen/MachineBasicBlock.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/DebugInfo.h"
29 #include "llvm/IR/CallingConv.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GlobalAlias.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/ManagedStatic.h"
41 #include "llvm/Support/MathExtras.h"
42 #include "llvm/Support/Mutex.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetIntrinsicInfo.h"
46 #include "llvm/Target/TargetLowering.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Target/TargetRegisterInfo.h"
50 #include "llvm/Target/TargetSelectionDAGInfo.h"
51 #include <algorithm>
52 #include <cmath>
53 using namespace llvm;
54
55 /// makeVTList - Return an instance of the SDVTList struct initialized with the
56 /// specified members.
57 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
58   SDVTList Res = {VTs, NumVTs};
59   return Res;
60 }
61
62 // Default null implementations of the callbacks.
63 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
64 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
65
66 //===----------------------------------------------------------------------===//
67 //                              ConstantFPSDNode Class
68 //===----------------------------------------------------------------------===//
69
70 /// isExactlyValue - We don't rely on operator== working on double values, as
71 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
72 /// As such, this method can be used to do an exact bit-for-bit comparison of
73 /// two floating point values.
74 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
75   return getValueAPF().bitwiseIsEqual(V);
76 }
77
78 bool ConstantFPSDNode::isValueValidForType(EVT VT,
79                                            const APFloat& Val) {
80   assert(VT.isFloatingPoint() && "Can only convert between FP types");
81
82   // convert modifies in place, so make a copy.
83   APFloat Val2 = APFloat(Val);
84   bool losesInfo;
85   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
86                       APFloat::rmNearestTiesToEven,
87                       &losesInfo);
88   return !losesInfo;
89 }
90
91 //===----------------------------------------------------------------------===//
92 //                              ISD Namespace
93 //===----------------------------------------------------------------------===//
94
95 /// isBuildVectorAllOnes - Return true if the specified node is a
96 /// BUILD_VECTOR where all of the elements are ~0 or undef.
97 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
98   // Look through a bit convert.
99   if (N->getOpcode() == ISD::BITCAST)
100     N = N->getOperand(0).getNode();
101
102   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
103
104   unsigned i = 0, e = N->getNumOperands();
105
106   // Skip over all of the undef values.
107   while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
108     ++i;
109
110   // Do not accept an all-undef vector.
111   if (i == e) return false;
112
113   // Do not accept build_vectors that aren't all constants or which have non-~0
114   // elements. We have to be a bit careful here, as the type of the constant
115   // may not be the same as the type of the vector elements due to type
116   // legalization (the elements are promoted to a legal type for the target and
117   // a vector of a type may be legal when the base element type is not).
118   // We only want to check enough bits to cover the vector elements, because
119   // we care if the resultant vector is all ones, not whether the individual
120   // constants are.
121   SDValue NotZero = N->getOperand(i);
122   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
123   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
124     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
125       return false;
126   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
127     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
128       return false;
129   } else
130     return false;
131
132   // Okay, we have at least one ~0 value, check to see if the rest match or are
133   // undefs. Even with the above element type twiddling, this should be OK, as
134   // the same type legalization should have applied to all the elements.
135   for (++i; i != e; ++i)
136     if (N->getOperand(i) != NotZero &&
137         N->getOperand(i).getOpcode() != ISD::UNDEF)
138       return false;
139   return true;
140 }
141
142
143 /// isBuildVectorAllZeros - Return true if the specified node is a
144 /// BUILD_VECTOR where all of the elements are 0 or undef.
145 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
146   // Look through a bit convert.
147   if (N->getOpcode() == ISD::BITCAST)
148     N = N->getOperand(0).getNode();
149
150   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
151
152   unsigned i = 0, e = N->getNumOperands();
153
154   // Skip over all of the undef values.
155   while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
156     ++i;
157
158   // Do not accept an all-undef vector.
159   if (i == e) return false;
160
161   // Do not accept build_vectors that aren't all constants or which have non-0
162   // elements.
163   SDValue Zero = N->getOperand(i);
164   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Zero)) {
165     if (!CN->isNullValue())
166       return false;
167   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Zero)) {
168     if (!CFPN->getValueAPF().isPosZero())
169       return false;
170   } else
171     return false;
172
173   // Okay, we have at least one 0 value, check to see if the rest match or are
174   // undefs.
175   for (++i; i != e; ++i)
176     if (N->getOperand(i) != Zero &&
177         N->getOperand(i).getOpcode() != ISD::UNDEF)
178       return false;
179   return true;
180 }
181
182 /// isScalarToVector - Return true if the specified node is a
183 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
184 /// element is not an undef.
185 bool ISD::isScalarToVector(const SDNode *N) {
186   if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
187     return true;
188
189   if (N->getOpcode() != ISD::BUILD_VECTOR)
190     return false;
191   if (N->getOperand(0).getOpcode() == ISD::UNDEF)
192     return false;
193   unsigned NumElems = N->getNumOperands();
194   if (NumElems == 1)
195     return false;
196   for (unsigned i = 1; i < NumElems; ++i) {
197     SDValue V = N->getOperand(i);
198     if (V.getOpcode() != ISD::UNDEF)
199       return false;
200   }
201   return true;
202 }
203
204 /// allOperandsUndef - Return true if the node has at least one operand
205 /// and all operands of the specified node are ISD::UNDEF.
206 bool ISD::allOperandsUndef(const SDNode *N) {
207   // Return false if the node has no operands.
208   // This is "logically inconsistent" with the definition of "all" but
209   // is probably the desired behavior.
210   if (N->getNumOperands() == 0)
211     return false;
212
213   for (unsigned i = 0, e = N->getNumOperands(); i != e ; ++i)
214     if (N->getOperand(i).getOpcode() != ISD::UNDEF)
215       return false;
216
217   return true;
218 }
219
220 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
221 /// when given the operation for (X op Y).
222 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
223   // To perform this operation, we just need to swap the L and G bits of the
224   // operation.
225   unsigned OldL = (Operation >> 2) & 1;
226   unsigned OldG = (Operation >> 1) & 1;
227   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
228                        (OldL << 1) |       // New G bit
229                        (OldG << 2));       // New L bit.
230 }
231
232 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
233 /// 'op' is a valid SetCC operation.
234 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
235   unsigned Operation = Op;
236   if (isInteger)
237     Operation ^= 7;   // Flip L, G, E bits, but not U.
238   else
239     Operation ^= 15;  // Flip all of the condition bits.
240
241   if (Operation > ISD::SETTRUE2)
242     Operation &= ~8;  // Don't let N and U bits get set.
243
244   return ISD::CondCode(Operation);
245 }
246
247
248 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
249 /// signed operation and 2 if the result is an unsigned comparison.  Return zero
250 /// if the operation does not depend on the sign of the input (setne and seteq).
251 static int isSignedOp(ISD::CondCode Opcode) {
252   switch (Opcode) {
253   default: llvm_unreachable("Illegal integer setcc operation!");
254   case ISD::SETEQ:
255   case ISD::SETNE: return 0;
256   case ISD::SETLT:
257   case ISD::SETLE:
258   case ISD::SETGT:
259   case ISD::SETGE: return 1;
260   case ISD::SETULT:
261   case ISD::SETULE:
262   case ISD::SETUGT:
263   case ISD::SETUGE: return 2;
264   }
265 }
266
267 /// getSetCCOrOperation - Return the result of a logical OR between different
268 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This function
269 /// returns SETCC_INVALID if it is not possible to represent the resultant
270 /// comparison.
271 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
272                                        bool isInteger) {
273   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
274     // Cannot fold a signed integer setcc with an unsigned integer setcc.
275     return ISD::SETCC_INVALID;
276
277   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
278
279   // If the N and U bits get set then the resultant comparison DOES suddenly
280   // care about orderedness, and is true when ordered.
281   if (Op > ISD::SETTRUE2)
282     Op &= ~16;     // Clear the U bit if the N bit is set.
283
284   // Canonicalize illegal integer setcc's.
285   if (isInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
286     Op = ISD::SETNE;
287
288   return ISD::CondCode(Op);
289 }
290
291 /// getSetCCAndOperation - Return the result of a logical AND between different
292 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
293 /// function returns zero if it is not possible to represent the resultant
294 /// comparison.
295 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
296                                         bool isInteger) {
297   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
298     // Cannot fold a signed setcc with an unsigned setcc.
299     return ISD::SETCC_INVALID;
300
301   // Combine all of the condition bits.
302   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
303
304   // Canonicalize illegal integer setcc's.
305   if (isInteger) {
306     switch (Result) {
307     default: break;
308     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
309     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
310     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
311     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
312     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
313     }
314   }
315
316   return Result;
317 }
318
319 //===----------------------------------------------------------------------===//
320 //                           SDNode Profile Support
321 //===----------------------------------------------------------------------===//
322
323 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
324 ///
325 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
326   ID.AddInteger(OpC);
327 }
328
329 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
330 /// solely with their pointer.
331 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
332   ID.AddPointer(VTList.VTs);
333 }
334
335 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
336 ///
337 static void AddNodeIDOperands(FoldingSetNodeID &ID,
338                               const SDValue *Ops, unsigned NumOps) {
339   for (; NumOps; --NumOps, ++Ops) {
340     ID.AddPointer(Ops->getNode());
341     ID.AddInteger(Ops->getResNo());
342   }
343 }
344
345 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
346 ///
347 static void AddNodeIDOperands(FoldingSetNodeID &ID,
348                               const SDUse *Ops, unsigned NumOps) {
349   for (; NumOps; --NumOps, ++Ops) {
350     ID.AddPointer(Ops->getNode());
351     ID.AddInteger(Ops->getResNo());
352   }
353 }
354
355 static void AddNodeIDNode(FoldingSetNodeID &ID,
356                           unsigned short OpC, SDVTList VTList,
357                           const SDValue *OpList, unsigned N) {
358   AddNodeIDOpcode(ID, OpC);
359   AddNodeIDValueTypes(ID, VTList);
360   AddNodeIDOperands(ID, OpList, N);
361 }
362
363 /// AddNodeIDCustom - If this is an SDNode with special info, add this info to
364 /// the NodeID data.
365 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
366   switch (N->getOpcode()) {
367   case ISD::TargetExternalSymbol:
368   case ISD::ExternalSymbol:
369     llvm_unreachable("Should only be used on nodes with operands");
370   default: break;  // Normal nodes don't need extra info.
371   case ISD::TargetConstant:
372   case ISD::Constant:
373     ID.AddPointer(cast<ConstantSDNode>(N)->getConstantIntValue());
374     break;
375   case ISD::TargetConstantFP:
376   case ISD::ConstantFP: {
377     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
378     break;
379   }
380   case ISD::TargetGlobalAddress:
381   case ISD::GlobalAddress:
382   case ISD::TargetGlobalTLSAddress:
383   case ISD::GlobalTLSAddress: {
384     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
385     ID.AddPointer(GA->getGlobal());
386     ID.AddInteger(GA->getOffset());
387     ID.AddInteger(GA->getTargetFlags());
388     ID.AddInteger(GA->getAddressSpace());
389     break;
390   }
391   case ISD::BasicBlock:
392     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
393     break;
394   case ISD::Register:
395     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
396     break;
397   case ISD::RegisterMask:
398     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
399     break;
400   case ISD::SRCVALUE:
401     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
402     break;
403   case ISD::FrameIndex:
404   case ISD::TargetFrameIndex:
405     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
406     break;
407   case ISD::JumpTable:
408   case ISD::TargetJumpTable:
409     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
410     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
411     break;
412   case ISD::ConstantPool:
413   case ISD::TargetConstantPool: {
414     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
415     ID.AddInteger(CP->getAlignment());
416     ID.AddInteger(CP->getOffset());
417     if (CP->isMachineConstantPoolEntry())
418       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
419     else
420       ID.AddPointer(CP->getConstVal());
421     ID.AddInteger(CP->getTargetFlags());
422     break;
423   }
424   case ISD::TargetIndex: {
425     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
426     ID.AddInteger(TI->getIndex());
427     ID.AddInteger(TI->getOffset());
428     ID.AddInteger(TI->getTargetFlags());
429     break;
430   }
431   case ISD::LOAD: {
432     const LoadSDNode *LD = cast<LoadSDNode>(N);
433     ID.AddInteger(LD->getMemoryVT().getRawBits());
434     ID.AddInteger(LD->getRawSubclassData());
435     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
436     break;
437   }
438   case ISD::STORE: {
439     const StoreSDNode *ST = cast<StoreSDNode>(N);
440     ID.AddInteger(ST->getMemoryVT().getRawBits());
441     ID.AddInteger(ST->getRawSubclassData());
442     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
443     break;
444   }
445   case ISD::ATOMIC_CMP_SWAP:
446   case ISD::ATOMIC_SWAP:
447   case ISD::ATOMIC_LOAD_ADD:
448   case ISD::ATOMIC_LOAD_SUB:
449   case ISD::ATOMIC_LOAD_AND:
450   case ISD::ATOMIC_LOAD_OR:
451   case ISD::ATOMIC_LOAD_XOR:
452   case ISD::ATOMIC_LOAD_NAND:
453   case ISD::ATOMIC_LOAD_MIN:
454   case ISD::ATOMIC_LOAD_MAX:
455   case ISD::ATOMIC_LOAD_UMIN:
456   case ISD::ATOMIC_LOAD_UMAX:
457   case ISD::ATOMIC_LOAD:
458   case ISD::ATOMIC_STORE: {
459     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
460     ID.AddInteger(AT->getMemoryVT().getRawBits());
461     ID.AddInteger(AT->getRawSubclassData());
462     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
463     break;
464   }
465   case ISD::PREFETCH: {
466     const MemSDNode *PF = cast<MemSDNode>(N);
467     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
468     break;
469   }
470   case ISD::VECTOR_SHUFFLE: {
471     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
472     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
473          i != e; ++i)
474       ID.AddInteger(SVN->getMaskElt(i));
475     break;
476   }
477   case ISD::TargetBlockAddress:
478   case ISD::BlockAddress: {
479     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
480     ID.AddPointer(BA->getBlockAddress());
481     ID.AddInteger(BA->getOffset());
482     ID.AddInteger(BA->getTargetFlags());
483     break;
484   }
485   } // end switch (N->getOpcode())
486
487   // Target specific memory nodes could also have address spaces to check.
488   if (N->isTargetMemoryOpcode())
489     ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
490 }
491
492 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
493 /// data.
494 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
495   AddNodeIDOpcode(ID, N->getOpcode());
496   // Add the return value info.
497   AddNodeIDValueTypes(ID, N->getVTList());
498   // Add the operand info.
499   AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
500
501   // Handle SDNode leafs with special info.
502   AddNodeIDCustom(ID, N);
503 }
504
505 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in
506 /// the CSE map that carries volatility, temporalness, indexing mode, and
507 /// extension/truncation information.
508 ///
509 static inline unsigned
510 encodeMemSDNodeFlags(int ConvType, ISD::MemIndexedMode AM, bool isVolatile,
511                      bool isNonTemporal, bool isInvariant) {
512   assert((ConvType & 3) == ConvType &&
513          "ConvType may not require more than 2 bits!");
514   assert((AM & 7) == AM &&
515          "AM may not require more than 3 bits!");
516   return ConvType |
517          (AM << 2) |
518          (isVolatile << 5) |
519          (isNonTemporal << 6) |
520          (isInvariant << 7);
521 }
522
523 //===----------------------------------------------------------------------===//
524 //                              SelectionDAG Class
525 //===----------------------------------------------------------------------===//
526
527 /// doNotCSE - Return true if CSE should not be performed for this node.
528 static bool doNotCSE(SDNode *N) {
529   if (N->getValueType(0) == MVT::Glue)
530     return true; // Never CSE anything that produces a flag.
531
532   switch (N->getOpcode()) {
533   default: break;
534   case ISD::HANDLENODE:
535   case ISD::EH_LABEL:
536     return true;   // Never CSE these nodes.
537   }
538
539   // Check that remaining values produced are not flags.
540   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
541     if (N->getValueType(i) == MVT::Glue)
542       return true; // Never CSE anything that produces a flag.
543
544   return false;
545 }
546
547 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
548 /// SelectionDAG.
549 void SelectionDAG::RemoveDeadNodes() {
550   // Create a dummy node (which is not added to allnodes), that adds a reference
551   // to the root node, preventing it from being deleted.
552   HandleSDNode Dummy(getRoot());
553
554   SmallVector<SDNode*, 128> DeadNodes;
555
556   // Add all obviously-dead nodes to the DeadNodes worklist.
557   for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
558     if (I->use_empty())
559       DeadNodes.push_back(I);
560
561   RemoveDeadNodes(DeadNodes);
562
563   // If the root changed (e.g. it was a dead load, update the root).
564   setRoot(Dummy.getValue());
565 }
566
567 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
568 /// given list, and any nodes that become unreachable as a result.
569 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
570
571   // Process the worklist, deleting the nodes and adding their uses to the
572   // worklist.
573   while (!DeadNodes.empty()) {
574     SDNode *N = DeadNodes.pop_back_val();
575
576     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
577       DUL->NodeDeleted(N, 0);
578
579     // Take the node out of the appropriate CSE map.
580     RemoveNodeFromCSEMaps(N);
581
582     // Next, brutally remove the operand list.  This is safe to do, as there are
583     // no cycles in the graph.
584     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
585       SDUse &Use = *I++;
586       SDNode *Operand = Use.getNode();
587       Use.set(SDValue());
588
589       // Now that we removed this operand, see if there are no uses of it left.
590       if (Operand->use_empty())
591         DeadNodes.push_back(Operand);
592     }
593
594     DeallocateNode(N);
595   }
596 }
597
598 void SelectionDAG::RemoveDeadNode(SDNode *N){
599   SmallVector<SDNode*, 16> DeadNodes(1, N);
600
601   // Create a dummy node that adds a reference to the root node, preventing
602   // it from being deleted.  (This matters if the root is an operand of the
603   // dead node.)
604   HandleSDNode Dummy(getRoot());
605
606   RemoveDeadNodes(DeadNodes);
607 }
608
609 void SelectionDAG::DeleteNode(SDNode *N) {
610   // First take this out of the appropriate CSE map.
611   RemoveNodeFromCSEMaps(N);
612
613   // Finally, remove uses due to operands of this node, remove from the
614   // AllNodes list, and delete the node.
615   DeleteNodeNotInCSEMaps(N);
616 }
617
618 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
619   assert(N != AllNodes.begin() && "Cannot delete the entry node!");
620   assert(N->use_empty() && "Cannot delete a node that is not dead!");
621
622   // Drop all of the operands and decrement used node's use counts.
623   N->DropOperands();
624
625   DeallocateNode(N);
626 }
627
628 void SelectionDAG::DeallocateNode(SDNode *N) {
629   if (N->OperandsNeedDelete)
630     delete[] N->OperandList;
631
632   // Set the opcode to DELETED_NODE to help catch bugs when node
633   // memory is reallocated.
634   N->NodeType = ISD::DELETED_NODE;
635
636   NodeAllocator.Deallocate(AllNodes.remove(N));
637
638   // If any of the SDDbgValue nodes refer to this SDNode, invalidate them.
639   ArrayRef<SDDbgValue*> DbgVals = DbgInfo->getSDDbgValues(N);
640   for (unsigned i = 0, e = DbgVals.size(); i != e; ++i)
641     DbgVals[i]->setIsInvalidated();
642 }
643
644 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
645 /// correspond to it.  This is useful when we're about to delete or repurpose
646 /// the node.  We don't want future request for structurally identical nodes
647 /// to return N anymore.
648 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
649   bool Erased = false;
650   switch (N->getOpcode()) {
651   case ISD::HANDLENODE: return false;  // noop.
652   case ISD::CONDCODE:
653     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
654            "Cond code doesn't exist!");
655     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
656     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
657     break;
658   case ISD::ExternalSymbol:
659     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
660     break;
661   case ISD::TargetExternalSymbol: {
662     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
663     Erased = TargetExternalSymbols.erase(
664                std::pair<std::string,unsigned char>(ESN->getSymbol(),
665                                                     ESN->getTargetFlags()));
666     break;
667   }
668   case ISD::VALUETYPE: {
669     EVT VT = cast<VTSDNode>(N)->getVT();
670     if (VT.isExtended()) {
671       Erased = ExtendedValueTypeNodes.erase(VT);
672     } else {
673       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != 0;
674       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = 0;
675     }
676     break;
677   }
678   default:
679     // Remove it from the CSE Map.
680     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
681     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
682     Erased = CSEMap.RemoveNode(N);
683     break;
684   }
685 #ifndef NDEBUG
686   // Verify that the node was actually in one of the CSE maps, unless it has a
687   // flag result (which cannot be CSE'd) or is one of the special cases that are
688   // not subject to CSE.
689   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
690       !N->isMachineOpcode() && !doNotCSE(N)) {
691     N->dump(this);
692     dbgs() << "\n";
693     llvm_unreachable("Node is not in map!");
694   }
695 #endif
696   return Erased;
697 }
698
699 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
700 /// maps and modified in place. Add it back to the CSE maps, unless an identical
701 /// node already exists, in which case transfer all its users to the existing
702 /// node. This transfer can potentially trigger recursive merging.
703 ///
704 void
705 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
706   // For node types that aren't CSE'd, just act as if no identical node
707   // already exists.
708   if (!doNotCSE(N)) {
709     SDNode *Existing = CSEMap.GetOrInsertNode(N);
710     if (Existing != N) {
711       // If there was already an existing matching node, use ReplaceAllUsesWith
712       // to replace the dead one with the existing one.  This can cause
713       // recursive merging of other unrelated nodes down the line.
714       ReplaceAllUsesWith(N, Existing);
715
716       // N is now dead. Inform the listeners and delete it.
717       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
718         DUL->NodeDeleted(N, Existing);
719       DeleteNodeNotInCSEMaps(N);
720       return;
721     }
722   }
723
724   // If the node doesn't already exist, we updated it.  Inform listeners.
725   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
726     DUL->NodeUpdated(N);
727 }
728
729 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
730 /// were replaced with those specified.  If this node is never memoized,
731 /// return null, otherwise return a pointer to the slot it would take.  If a
732 /// node already exists with these operands, the slot will be non-null.
733 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
734                                            void *&InsertPos) {
735   if (doNotCSE(N))
736     return 0;
737
738   SDValue Ops[] = { Op };
739   FoldingSetNodeID ID;
740   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
741   AddNodeIDCustom(ID, N);
742   SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
743   return Node;
744 }
745
746 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
747 /// were replaced with those specified.  If this node is never memoized,
748 /// return null, otherwise return a pointer to the slot it would take.  If a
749 /// node already exists with these operands, the slot will be non-null.
750 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
751                                            SDValue Op1, SDValue Op2,
752                                            void *&InsertPos) {
753   if (doNotCSE(N))
754     return 0;
755
756   SDValue Ops[] = { Op1, Op2 };
757   FoldingSetNodeID ID;
758   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
759   AddNodeIDCustom(ID, N);
760   SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
761   return Node;
762 }
763
764
765 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
766 /// were replaced with those specified.  If this node is never memoized,
767 /// return null, otherwise return a pointer to the slot it would take.  If a
768 /// node already exists with these operands, the slot will be non-null.
769 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
770                                            const SDValue *Ops,unsigned NumOps,
771                                            void *&InsertPos) {
772   if (doNotCSE(N))
773     return 0;
774
775   FoldingSetNodeID ID;
776   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
777   AddNodeIDCustom(ID, N);
778   SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
779   return Node;
780 }
781
782 #ifndef NDEBUG
783 /// VerifyNodeCommon - Sanity check the given node.  Aborts if it is invalid.
784 static void VerifyNodeCommon(SDNode *N) {
785   switch (N->getOpcode()) {
786   default:
787     break;
788   case ISD::BUILD_PAIR: {
789     EVT VT = N->getValueType(0);
790     assert(N->getNumValues() == 1 && "Too many results!");
791     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
792            "Wrong return type!");
793     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
794     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
795            "Mismatched operand types!");
796     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
797            "Wrong operand type!");
798     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
799            "Wrong return type size");
800     break;
801   }
802   case ISD::BUILD_VECTOR: {
803     assert(N->getNumValues() == 1 && "Too many results!");
804     assert(N->getValueType(0).isVector() && "Wrong return type!");
805     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
806            "Wrong number of operands!");
807     EVT EltVT = N->getValueType(0).getVectorElementType();
808     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
809       assert((I->getValueType() == EltVT ||
810              (EltVT.isInteger() && I->getValueType().isInteger() &&
811               EltVT.bitsLE(I->getValueType()))) &&
812             "Wrong operand type!");
813       assert(I->getValueType() == N->getOperand(0).getValueType() &&
814              "Operands must all have the same type");
815     }
816     break;
817   }
818   }
819 }
820
821 /// VerifySDNode - Sanity check the given SDNode.  Aborts if it is invalid.
822 static void VerifySDNode(SDNode *N) {
823   // The SDNode allocators cannot be used to allocate nodes with fields that are
824   // not present in an SDNode!
825   assert(!isa<MemSDNode>(N) && "Bad MemSDNode!");
826   assert(!isa<ShuffleVectorSDNode>(N) && "Bad ShuffleVectorSDNode!");
827   assert(!isa<ConstantSDNode>(N) && "Bad ConstantSDNode!");
828   assert(!isa<ConstantFPSDNode>(N) && "Bad ConstantFPSDNode!");
829   assert(!isa<GlobalAddressSDNode>(N) && "Bad GlobalAddressSDNode!");
830   assert(!isa<FrameIndexSDNode>(N) && "Bad FrameIndexSDNode!");
831   assert(!isa<JumpTableSDNode>(N) && "Bad JumpTableSDNode!");
832   assert(!isa<ConstantPoolSDNode>(N) && "Bad ConstantPoolSDNode!");
833   assert(!isa<BasicBlockSDNode>(N) && "Bad BasicBlockSDNode!");
834   assert(!isa<SrcValueSDNode>(N) && "Bad SrcValueSDNode!");
835   assert(!isa<MDNodeSDNode>(N) && "Bad MDNodeSDNode!");
836   assert(!isa<RegisterSDNode>(N) && "Bad RegisterSDNode!");
837   assert(!isa<BlockAddressSDNode>(N) && "Bad BlockAddressSDNode!");
838   assert(!isa<EHLabelSDNode>(N) && "Bad EHLabelSDNode!");
839   assert(!isa<ExternalSymbolSDNode>(N) && "Bad ExternalSymbolSDNode!");
840   assert(!isa<CondCodeSDNode>(N) && "Bad CondCodeSDNode!");
841   assert(!isa<CvtRndSatSDNode>(N) && "Bad CvtRndSatSDNode!");
842   assert(!isa<VTSDNode>(N) && "Bad VTSDNode!");
843   assert(!isa<MachineSDNode>(N) && "Bad MachineSDNode!");
844
845   VerifyNodeCommon(N);
846 }
847
848 /// VerifyMachineNode - Sanity check the given MachineNode.  Aborts if it is
849 /// invalid.
850 static void VerifyMachineNode(SDNode *N) {
851   // The MachineNode allocators cannot be used to allocate nodes with fields
852   // that are not present in a MachineNode!
853   // Currently there are no such nodes.
854
855   VerifyNodeCommon(N);
856 }
857 #endif // NDEBUG
858
859 /// getEVTAlignment - Compute the default alignment value for the
860 /// given type.
861 ///
862 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
863   Type *Ty = VT == MVT::iPTR ?
864                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
865                    VT.getTypeForEVT(*getContext());
866
867   return TM.getTargetLowering()->getDataLayout()->getABITypeAlignment(Ty);
868 }
869
870 // EntryNode could meaningfully have debug info if we can find it...
871 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
872   : TM(tm), TSI(*tm.getSelectionDAGInfo()), TTI(0), OptLevel(OL),
873     EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
874     Root(getEntryNode()), UpdateListeners(0) {
875   AllNodes.push_back(&EntryNode);
876   DbgInfo = new SDDbgInfo();
877 }
878
879 void SelectionDAG::init(MachineFunction &mf, const TargetTransformInfo *tti) {
880   MF = &mf;
881   TTI = tti;
882   Context = &mf.getFunction()->getContext();
883 }
884
885 SelectionDAG::~SelectionDAG() {
886   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
887   allnodes_clear();
888   delete DbgInfo;
889 }
890
891 void SelectionDAG::allnodes_clear() {
892   assert(&*AllNodes.begin() == &EntryNode);
893   AllNodes.remove(AllNodes.begin());
894   while (!AllNodes.empty())
895     DeallocateNode(AllNodes.begin());
896 }
897
898 void SelectionDAG::clear() {
899   allnodes_clear();
900   OperandAllocator.Reset();
901   CSEMap.clear();
902
903   ExtendedValueTypeNodes.clear();
904   ExternalSymbols.clear();
905   TargetExternalSymbols.clear();
906   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
907             static_cast<CondCodeSDNode*>(0));
908   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
909             static_cast<SDNode*>(0));
910
911   EntryNode.UseList = 0;
912   AllNodes.push_back(&EntryNode);
913   Root = getEntryNode();
914   DbgInfo->clear();
915 }
916
917 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, SDLoc DL, EVT VT) {
918   return VT.bitsGT(Op.getValueType()) ?
919     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
920     getNode(ISD::TRUNCATE, DL, VT, Op);
921 }
922
923 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, SDLoc DL, EVT VT) {
924   return VT.bitsGT(Op.getValueType()) ?
925     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
926     getNode(ISD::TRUNCATE, DL, VT, Op);
927 }
928
929 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, SDLoc DL, EVT VT) {
930   return VT.bitsGT(Op.getValueType()) ?
931     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
932     getNode(ISD::TRUNCATE, DL, VT, Op);
933 }
934
935 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, SDLoc DL, EVT VT) {
936   assert(!VT.isVector() &&
937          "getZeroExtendInReg should use the vector element type instead of "
938          "the vector type!");
939   if (Op.getValueType() == VT) return Op;
940   unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
941   APInt Imm = APInt::getLowBitsSet(BitWidth,
942                                    VT.getSizeInBits());
943   return getNode(ISD::AND, DL, Op.getValueType(), Op,
944                  getConstant(Imm, Op.getValueType()));
945 }
946
947 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
948 ///
949 SDValue SelectionDAG::getNOT(SDLoc DL, SDValue Val, EVT VT) {
950   EVT EltVT = VT.getScalarType();
951   SDValue NegOne =
952     getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
953   return getNode(ISD::XOR, DL, VT, Val, NegOne);
954 }
955
956 SDValue SelectionDAG::getConstant(uint64_t Val, EVT VT, bool isT) {
957   EVT EltVT = VT.getScalarType();
958   assert((EltVT.getSizeInBits() >= 64 ||
959          (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
960          "getConstant with a uint64_t value that doesn't fit in the type!");
961   return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
962 }
963
964 SDValue SelectionDAG::getConstant(const APInt &Val, EVT VT, bool isT) {
965   return getConstant(*ConstantInt::get(*Context, Val), VT, isT);
966 }
967
968 SDValue SelectionDAG::getConstant(const ConstantInt &Val, EVT VT, bool isT) {
969   assert(VT.isInteger() && "Cannot create FP integer constant!");
970
971   EVT EltVT = VT.getScalarType();
972   const ConstantInt *Elt = &Val;
973
974   const TargetLowering *TLI = TM.getTargetLowering();
975
976   // In some cases the vector type is legal but the element type is illegal and
977   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
978   // inserted value (the type does not need to match the vector element type).
979   // Any extra bits introduced will be truncated away.
980   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
981       TargetLowering::TypePromoteInteger) {
982    EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
983    APInt NewVal = Elt->getValue().zext(EltVT.getSizeInBits());
984    Elt = ConstantInt::get(*getContext(), NewVal);
985   }
986
987   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
988          "APInt size does not match type size!");
989   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
990   FoldingSetNodeID ID;
991   AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
992   ID.AddPointer(Elt);
993   void *IP = 0;
994   SDNode *N = NULL;
995   if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
996     if (!VT.isVector())
997       return SDValue(N, 0);
998
999   if (!N) {
1000     N = new (NodeAllocator) ConstantSDNode(isT, Elt, EltVT);
1001     CSEMap.InsertNode(N, IP);
1002     AllNodes.push_back(N);
1003   }
1004
1005   SDValue Result(N, 0);
1006   if (VT.isVector()) {
1007     SmallVector<SDValue, 8> Ops;
1008     Ops.assign(VT.getVectorNumElements(), Result);
1009     Result = getNode(ISD::BUILD_VECTOR, SDLoc(), VT, &Ops[0], Ops.size());
1010   }
1011   return Result;
1012 }
1013
1014 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
1015   return getConstant(Val, TM.getTargetLowering()->getPointerTy(), isTarget);
1016 }
1017
1018
1019 SDValue SelectionDAG::getConstantFP(const APFloat& V, EVT VT, bool isTarget) {
1020   return getConstantFP(*ConstantFP::get(*getContext(), V), VT, isTarget);
1021 }
1022
1023 SDValue SelectionDAG::getConstantFP(const ConstantFP& V, EVT VT, bool isTarget){
1024   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1025
1026   EVT EltVT = VT.getScalarType();
1027
1028   // Do the map lookup using the actual bit pattern for the floating point
1029   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1030   // we don't have issues with SNANs.
1031   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1032   FoldingSetNodeID ID;
1033   AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
1034   ID.AddPointer(&V);
1035   void *IP = 0;
1036   SDNode *N = NULL;
1037   if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
1038     if (!VT.isVector())
1039       return SDValue(N, 0);
1040
1041   if (!N) {
1042     N = new (NodeAllocator) ConstantFPSDNode(isTarget, &V, EltVT);
1043     CSEMap.InsertNode(N, IP);
1044     AllNodes.push_back(N);
1045   }
1046
1047   SDValue Result(N, 0);
1048   if (VT.isVector()) {
1049     SmallVector<SDValue, 8> Ops;
1050     Ops.assign(VT.getVectorNumElements(), Result);
1051     // FIXME SDLoc info might be appropriate here
1052     Result = getNode(ISD::BUILD_VECTOR, SDLoc(), VT, &Ops[0], Ops.size());
1053   }
1054   return Result;
1055 }
1056
1057 SDValue SelectionDAG::getConstantFP(double Val, EVT VT, bool isTarget) {
1058   EVT EltVT = VT.getScalarType();
1059   if (EltVT==MVT::f32)
1060     return getConstantFP(APFloat((float)Val), VT, isTarget);
1061   else if (EltVT==MVT::f64)
1062     return getConstantFP(APFloat(Val), VT, isTarget);
1063   else if (EltVT==MVT::f80 || EltVT==MVT::f128 || EltVT==MVT::ppcf128 ||
1064            EltVT==MVT::f16) {
1065     bool ignored;
1066     APFloat apf = APFloat(Val);
1067     apf.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1068                 &ignored);
1069     return getConstantFP(apf, VT, isTarget);
1070   } else
1071     llvm_unreachable("Unsupported type in getConstantFP");
1072 }
1073
1074 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, SDLoc DL,
1075                                        EVT VT, int64_t Offset,
1076                                        bool isTargetGA,
1077                                        unsigned char TargetFlags) {
1078   assert((TargetFlags == 0 || isTargetGA) &&
1079          "Cannot set target flags on target-independent globals");
1080
1081   // Truncate (with sign-extension) the offset value to the pointer size.
1082   unsigned BitWidth = TM.getTargetLowering()->getPointerTy().getSizeInBits();
1083   if (BitWidth < 64)
1084     Offset = SignExtend64(Offset, BitWidth);
1085
1086   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
1087   if (!GVar) {
1088     // If GV is an alias then use the aliasee for determining thread-localness.
1089     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
1090       GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
1091   }
1092
1093   unsigned Opc;
1094   if (GVar && GVar->isThreadLocal())
1095     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1096   else
1097     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1098
1099   FoldingSetNodeID ID;
1100   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1101   ID.AddPointer(GV);
1102   ID.AddInteger(Offset);
1103   ID.AddInteger(TargetFlags);
1104   ID.AddInteger(GV->getType()->getAddressSpace());
1105   void *IP = 0;
1106   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1107     return SDValue(E, 0);
1108
1109   SDNode *N = new (NodeAllocator) GlobalAddressSDNode(Opc, DL.getIROrder(),
1110                                                       DL.getDebugLoc(), GV, VT,
1111                                                       Offset, TargetFlags);
1112   CSEMap.InsertNode(N, IP);
1113   AllNodes.push_back(N);
1114   return SDValue(N, 0);
1115 }
1116
1117 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1118   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1119   FoldingSetNodeID ID;
1120   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1121   ID.AddInteger(FI);
1122   void *IP = 0;
1123   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1124     return SDValue(E, 0);
1125
1126   SDNode *N = new (NodeAllocator) FrameIndexSDNode(FI, VT, isTarget);
1127   CSEMap.InsertNode(N, IP);
1128   AllNodes.push_back(N);
1129   return SDValue(N, 0);
1130 }
1131
1132 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1133                                    unsigned char TargetFlags) {
1134   assert((TargetFlags == 0 || isTarget) &&
1135          "Cannot set target flags on target-independent jump tables");
1136   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1137   FoldingSetNodeID ID;
1138   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1139   ID.AddInteger(JTI);
1140   ID.AddInteger(TargetFlags);
1141   void *IP = 0;
1142   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1143     return SDValue(E, 0);
1144
1145   SDNode *N = new (NodeAllocator) JumpTableSDNode(JTI, VT, isTarget,
1146                                                   TargetFlags);
1147   CSEMap.InsertNode(N, IP);
1148   AllNodes.push_back(N);
1149   return SDValue(N, 0);
1150 }
1151
1152 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1153                                       unsigned Alignment, int Offset,
1154                                       bool isTarget,
1155                                       unsigned char TargetFlags) {
1156   assert((TargetFlags == 0 || isTarget) &&
1157          "Cannot set target flags on target-independent globals");
1158   if (Alignment == 0)
1159     Alignment =
1160     TM.getTargetLowering()->getDataLayout()->getPrefTypeAlignment(C->getType());
1161   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1162   FoldingSetNodeID ID;
1163   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1164   ID.AddInteger(Alignment);
1165   ID.AddInteger(Offset);
1166   ID.AddPointer(C);
1167   ID.AddInteger(TargetFlags);
1168   void *IP = 0;
1169   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1170     return SDValue(E, 0);
1171
1172   SDNode *N = new (NodeAllocator) ConstantPoolSDNode(isTarget, C, VT, Offset,
1173                                                      Alignment, TargetFlags);
1174   CSEMap.InsertNode(N, IP);
1175   AllNodes.push_back(N);
1176   return SDValue(N, 0);
1177 }
1178
1179
1180 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1181                                       unsigned Alignment, int Offset,
1182                                       bool isTarget,
1183                                       unsigned char TargetFlags) {
1184   assert((TargetFlags == 0 || isTarget) &&
1185          "Cannot set target flags on target-independent globals");
1186   if (Alignment == 0)
1187     Alignment =
1188     TM.getTargetLowering()->getDataLayout()->getPrefTypeAlignment(C->getType());
1189   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1190   FoldingSetNodeID ID;
1191   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1192   ID.AddInteger(Alignment);
1193   ID.AddInteger(Offset);
1194   C->addSelectionDAGCSEId(ID);
1195   ID.AddInteger(TargetFlags);
1196   void *IP = 0;
1197   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1198     return SDValue(E, 0);
1199
1200   SDNode *N = new (NodeAllocator) ConstantPoolSDNode(isTarget, C, VT, Offset,
1201                                                      Alignment, TargetFlags);
1202   CSEMap.InsertNode(N, IP);
1203   AllNodes.push_back(N);
1204   return SDValue(N, 0);
1205 }
1206
1207 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1208                                      unsigned char TargetFlags) {
1209   FoldingSetNodeID ID;
1210   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), 0, 0);
1211   ID.AddInteger(Index);
1212   ID.AddInteger(Offset);
1213   ID.AddInteger(TargetFlags);
1214   void *IP = 0;
1215   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1216     return SDValue(E, 0);
1217
1218   SDNode *N = new (NodeAllocator) TargetIndexSDNode(Index, VT, Offset,
1219                                                     TargetFlags);
1220   CSEMap.InsertNode(N, IP);
1221   AllNodes.push_back(N);
1222   return SDValue(N, 0);
1223 }
1224
1225 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1226   FoldingSetNodeID ID;
1227   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
1228   ID.AddPointer(MBB);
1229   void *IP = 0;
1230   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1231     return SDValue(E, 0);
1232
1233   SDNode *N = new (NodeAllocator) BasicBlockSDNode(MBB);
1234   CSEMap.InsertNode(N, IP);
1235   AllNodes.push_back(N);
1236   return SDValue(N, 0);
1237 }
1238
1239 SDValue SelectionDAG::getValueType(EVT VT) {
1240   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1241       ValueTypeNodes.size())
1242     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1243
1244   SDNode *&N = VT.isExtended() ?
1245     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1246
1247   if (N) return SDValue(N, 0);
1248   N = new (NodeAllocator) VTSDNode(VT);
1249   AllNodes.push_back(N);
1250   return SDValue(N, 0);
1251 }
1252
1253 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1254   SDNode *&N = ExternalSymbols[Sym];
1255   if (N) return SDValue(N, 0);
1256   N = new (NodeAllocator) ExternalSymbolSDNode(false, Sym, 0, VT);
1257   AllNodes.push_back(N);
1258   return SDValue(N, 0);
1259 }
1260
1261 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1262                                               unsigned char TargetFlags) {
1263   SDNode *&N =
1264     TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1265                                                                TargetFlags)];
1266   if (N) return SDValue(N, 0);
1267   N = new (NodeAllocator) ExternalSymbolSDNode(true, Sym, TargetFlags, VT);
1268   AllNodes.push_back(N);
1269   return SDValue(N, 0);
1270 }
1271
1272 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1273   if ((unsigned)Cond >= CondCodeNodes.size())
1274     CondCodeNodes.resize(Cond+1);
1275
1276   if (CondCodeNodes[Cond] == 0) {
1277     CondCodeSDNode *N = new (NodeAllocator) CondCodeSDNode(Cond);
1278     CondCodeNodes[Cond] = N;
1279     AllNodes.push_back(N);
1280   }
1281
1282   return SDValue(CondCodeNodes[Cond], 0);
1283 }
1284
1285 // commuteShuffle - swaps the values of N1 and N2, and swaps all indices in
1286 // the shuffle mask M that point at N1 to point at N2, and indices that point
1287 // N2 to point at N1.
1288 static void commuteShuffle(SDValue &N1, SDValue &N2, SmallVectorImpl<int> &M) {
1289   std::swap(N1, N2);
1290   int NElts = M.size();
1291   for (int i = 0; i != NElts; ++i) {
1292     if (M[i] >= NElts)
1293       M[i] -= NElts;
1294     else if (M[i] >= 0)
1295       M[i] += NElts;
1296   }
1297 }
1298
1299 SDValue SelectionDAG::getVectorShuffle(EVT VT, SDLoc dl, SDValue N1,
1300                                        SDValue N2, const int *Mask) {
1301   assert(N1.getValueType() == N2.getValueType() && "Invalid VECTOR_SHUFFLE");
1302   assert(VT.isVector() && N1.getValueType().isVector() &&
1303          "Vector Shuffle VTs must be a vectors");
1304   assert(VT.getVectorElementType() == N1.getValueType().getVectorElementType()
1305          && "Vector Shuffle VTs must have same element type");
1306
1307   // Canonicalize shuffle undef, undef -> undef
1308   if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() == ISD::UNDEF)
1309     return getUNDEF(VT);
1310
1311   // Validate that all indices in Mask are within the range of the elements
1312   // input to the shuffle.
1313   unsigned NElts = VT.getVectorNumElements();
1314   SmallVector<int, 8> MaskVec;
1315   for (unsigned i = 0; i != NElts; ++i) {
1316     assert(Mask[i] < (int)(NElts * 2) && "Index out of range");
1317     MaskVec.push_back(Mask[i]);
1318   }
1319
1320   // Canonicalize shuffle v, v -> v, undef
1321   if (N1 == N2) {
1322     N2 = getUNDEF(VT);
1323     for (unsigned i = 0; i != NElts; ++i)
1324       if (MaskVec[i] >= (int)NElts) MaskVec[i] -= NElts;
1325   }
1326
1327   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1328   if (N1.getOpcode() == ISD::UNDEF)
1329     commuteShuffle(N1, N2, MaskVec);
1330
1331   // Canonicalize all index into lhs, -> shuffle lhs, undef
1332   // Canonicalize all index into rhs, -> shuffle rhs, undef
1333   bool AllLHS = true, AllRHS = true;
1334   bool N2Undef = N2.getOpcode() == ISD::UNDEF;
1335   for (unsigned i = 0; i != NElts; ++i) {
1336     if (MaskVec[i] >= (int)NElts) {
1337       if (N2Undef)
1338         MaskVec[i] = -1;
1339       else
1340         AllLHS = false;
1341     } else if (MaskVec[i] >= 0) {
1342       AllRHS = false;
1343     }
1344   }
1345   if (AllLHS && AllRHS)
1346     return getUNDEF(VT);
1347   if (AllLHS && !N2Undef)
1348     N2 = getUNDEF(VT);
1349   if (AllRHS) {
1350     N1 = getUNDEF(VT);
1351     commuteShuffle(N1, N2, MaskVec);
1352   }
1353
1354   // If Identity shuffle return that node.
1355   bool Identity = true;
1356   for (unsigned i = 0; i != NElts; ++i) {
1357     if (MaskVec[i] >= 0 && MaskVec[i] != (int)i) Identity = false;
1358   }
1359   if (Identity && NElts == N1.getValueType().getVectorNumElements())
1360     return N1;
1361
1362   FoldingSetNodeID ID;
1363   SDValue Ops[2] = { N1, N2 };
1364   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops, 2);
1365   for (unsigned i = 0; i != NElts; ++i)
1366     ID.AddInteger(MaskVec[i]);
1367
1368   void* IP = 0;
1369   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1370     return SDValue(E, 0);
1371
1372   // Allocate the mask array for the node out of the BumpPtrAllocator, since
1373   // SDNode doesn't have access to it.  This memory will be "leaked" when
1374   // the node is deallocated, but recovered when the NodeAllocator is released.
1375   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1376   memcpy(MaskAlloc, &MaskVec[0], NElts * sizeof(int));
1377
1378   ShuffleVectorSDNode *N =
1379     new (NodeAllocator) ShuffleVectorSDNode(VT, dl.getIROrder(), dl.getDebugLoc(), N1, N2, MaskAlloc);
1380   CSEMap.InsertNode(N, IP);
1381   AllNodes.push_back(N);
1382   return SDValue(N, 0);
1383 }
1384
1385 SDValue SelectionDAG::getConvertRndSat(EVT VT, SDLoc dl,
1386                                        SDValue Val, SDValue DTy,
1387                                        SDValue STy, SDValue Rnd, SDValue Sat,
1388                                        ISD::CvtCode Code) {
1389   // If the src and dest types are the same and the conversion is between
1390   // integer types of the same sign or two floats, no conversion is necessary.
1391   if (DTy == STy &&
1392       (Code == ISD::CVT_UU || Code == ISD::CVT_SS || Code == ISD::CVT_FF))
1393     return Val;
1394
1395   FoldingSetNodeID ID;
1396   SDValue Ops[] = { Val, DTy, STy, Rnd, Sat };
1397   AddNodeIDNode(ID, ISD::CONVERT_RNDSAT, getVTList(VT), &Ops[0], 5);
1398   void* IP = 0;
1399   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1400     return SDValue(E, 0);
1401
1402   CvtRndSatSDNode *N = new (NodeAllocator) CvtRndSatSDNode(VT, dl.getIROrder(), dl.getDebugLoc(), Ops, 5,
1403                                                            Code);
1404   CSEMap.InsertNode(N, IP);
1405   AllNodes.push_back(N);
1406   return SDValue(N, 0);
1407 }
1408
1409 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1410   FoldingSetNodeID ID;
1411   AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
1412   ID.AddInteger(RegNo);
1413   void *IP = 0;
1414   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1415     return SDValue(E, 0);
1416
1417   SDNode *N = new (NodeAllocator) RegisterSDNode(RegNo, VT);
1418   CSEMap.InsertNode(N, IP);
1419   AllNodes.push_back(N);
1420   return SDValue(N, 0);
1421 }
1422
1423 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1424   FoldingSetNodeID ID;
1425   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), 0, 0);
1426   ID.AddPointer(RegMask);
1427   void *IP = 0;
1428   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1429     return SDValue(E, 0);
1430
1431   SDNode *N = new (NodeAllocator) RegisterMaskSDNode(RegMask);
1432   CSEMap.InsertNode(N, IP);
1433   AllNodes.push_back(N);
1434   return SDValue(N, 0);
1435 }
1436
1437 SDValue SelectionDAG::getEHLabel(SDLoc dl, SDValue Root, MCSymbol *Label) {
1438   FoldingSetNodeID ID;
1439   SDValue Ops[] = { Root };
1440   AddNodeIDNode(ID, ISD::EH_LABEL, getVTList(MVT::Other), &Ops[0], 1);
1441   ID.AddPointer(Label);
1442   void *IP = 0;
1443   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1444     return SDValue(E, 0);
1445
1446   SDNode *N = new (NodeAllocator) EHLabelSDNode(dl.getIROrder(), dl.getDebugLoc(), Root, Label);
1447   CSEMap.InsertNode(N, IP);
1448   AllNodes.push_back(N);
1449   return SDValue(N, 0);
1450 }
1451
1452
1453 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
1454                                       int64_t Offset,
1455                                       bool isTarget,
1456                                       unsigned char TargetFlags) {
1457   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1458
1459   FoldingSetNodeID ID;
1460   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1461   ID.AddPointer(BA);
1462   ID.AddInteger(Offset);
1463   ID.AddInteger(TargetFlags);
1464   void *IP = 0;
1465   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1466     return SDValue(E, 0);
1467
1468   SDNode *N = new (NodeAllocator) BlockAddressSDNode(Opc, VT, BA, Offset,
1469                                                      TargetFlags);
1470   CSEMap.InsertNode(N, IP);
1471   AllNodes.push_back(N);
1472   return SDValue(N, 0);
1473 }
1474
1475 SDValue SelectionDAG::getSrcValue(const Value *V) {
1476   assert((!V || V->getType()->isPointerTy()) &&
1477          "SrcValue is not a pointer?");
1478
1479   FoldingSetNodeID ID;
1480   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1481   ID.AddPointer(V);
1482
1483   void *IP = 0;
1484   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1485     return SDValue(E, 0);
1486
1487   SDNode *N = new (NodeAllocator) SrcValueSDNode(V);
1488   CSEMap.InsertNode(N, IP);
1489   AllNodes.push_back(N);
1490   return SDValue(N, 0);
1491 }
1492
1493 /// getMDNode - Return an MDNodeSDNode which holds an MDNode.
1494 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
1495   FoldingSetNodeID ID;
1496   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), 0, 0);
1497   ID.AddPointer(MD);
1498
1499   void *IP = 0;
1500   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1501     return SDValue(E, 0);
1502
1503   SDNode *N = new (NodeAllocator) MDNodeSDNode(MD);
1504   CSEMap.InsertNode(N, IP);
1505   AllNodes.push_back(N);
1506   return SDValue(N, 0);
1507 }
1508
1509
1510 /// getShiftAmountOperand - Return the specified value casted to
1511 /// the target's desired shift amount type.
1512 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
1513   EVT OpTy = Op.getValueType();
1514   EVT ShTy = TM.getTargetLowering()->getShiftAmountTy(LHSTy);
1515   if (OpTy == ShTy || OpTy.isVector()) return Op;
1516
1517   ISD::NodeType Opcode = OpTy.bitsGT(ShTy) ?  ISD::TRUNCATE : ISD::ZERO_EXTEND;
1518   return getNode(Opcode, SDLoc(Op), ShTy, Op);
1519 }
1520
1521 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1522 /// specified value type.
1523 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1524   MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1525   unsigned ByteSize = VT.getStoreSize();
1526   Type *Ty = VT.getTypeForEVT(*getContext());
1527   const TargetLowering *TLI = TM.getTargetLowering();
1528   unsigned StackAlign =
1529   std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty), minAlign);
1530
1531   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
1532   return getFrameIndex(FrameIdx, TLI->getPointerTy());
1533 }
1534
1535 /// CreateStackTemporary - Create a stack temporary suitable for holding
1536 /// either of the specified value types.
1537 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1538   unsigned Bytes = std::max(VT1.getStoreSizeInBits(),
1539                             VT2.getStoreSizeInBits())/8;
1540   Type *Ty1 = VT1.getTypeForEVT(*getContext());
1541   Type *Ty2 = VT2.getTypeForEVT(*getContext());
1542   const TargetLowering *TLI = TM.getTargetLowering();
1543   const DataLayout *TD = TLI->getDataLayout();
1544   unsigned Align = std::max(TD->getPrefTypeAlignment(Ty1),
1545                             TD->getPrefTypeAlignment(Ty2));
1546
1547   MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1548   int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align, false);
1549   return getFrameIndex(FrameIdx, TLI->getPointerTy());
1550 }
1551
1552 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1,
1553                                 SDValue N2, ISD::CondCode Cond, SDLoc dl) {
1554   // These setcc operations always fold.
1555   switch (Cond) {
1556   default: break;
1557   case ISD::SETFALSE:
1558   case ISD::SETFALSE2: return getConstant(0, VT);
1559   case ISD::SETTRUE:
1560   case ISD::SETTRUE2:  return getConstant(1, VT);
1561
1562   case ISD::SETOEQ:
1563   case ISD::SETOGT:
1564   case ISD::SETOGE:
1565   case ISD::SETOLT:
1566   case ISD::SETOLE:
1567   case ISD::SETONE:
1568   case ISD::SETO:
1569   case ISD::SETUO:
1570   case ISD::SETUEQ:
1571   case ISD::SETUNE:
1572     assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1573     break;
1574   }
1575
1576   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) {
1577     const APInt &C2 = N2C->getAPIntValue();
1578     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1579       const APInt &C1 = N1C->getAPIntValue();
1580
1581       switch (Cond) {
1582       default: llvm_unreachable("Unknown integer setcc!");
1583       case ISD::SETEQ:  return getConstant(C1 == C2, VT);
1584       case ISD::SETNE:  return getConstant(C1 != C2, VT);
1585       case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1586       case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1587       case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1588       case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1589       case ISD::SETLT:  return getConstant(C1.slt(C2), VT);
1590       case ISD::SETGT:  return getConstant(C1.sgt(C2), VT);
1591       case ISD::SETLE:  return getConstant(C1.sle(C2), VT);
1592       case ISD::SETGE:  return getConstant(C1.sge(C2), VT);
1593       }
1594     }
1595   }
1596   if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1597     if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) {
1598       APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1599       switch (Cond) {
1600       default: break;
1601       case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
1602                           return getUNDEF(VT);
1603                         // fall through
1604       case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1605       case ISD::SETNE:  if (R==APFloat::cmpUnordered)
1606                           return getUNDEF(VT);
1607                         // fall through
1608       case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1609                                            R==APFloat::cmpLessThan, VT);
1610       case ISD::SETLT:  if (R==APFloat::cmpUnordered)
1611                           return getUNDEF(VT);
1612                         // fall through
1613       case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1614       case ISD::SETGT:  if (R==APFloat::cmpUnordered)
1615                           return getUNDEF(VT);
1616                         // fall through
1617       case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1618       case ISD::SETLE:  if (R==APFloat::cmpUnordered)
1619                           return getUNDEF(VT);
1620                         // fall through
1621       case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1622                                            R==APFloat::cmpEqual, VT);
1623       case ISD::SETGE:  if (R==APFloat::cmpUnordered)
1624                           return getUNDEF(VT);
1625                         // fall through
1626       case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1627                                            R==APFloat::cmpEqual, VT);
1628       case ISD::SETO:   return getConstant(R!=APFloat::cmpUnordered, VT);
1629       case ISD::SETUO:  return getConstant(R==APFloat::cmpUnordered, VT);
1630       case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1631                                            R==APFloat::cmpEqual, VT);
1632       case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1633       case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1634                                            R==APFloat::cmpLessThan, VT);
1635       case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1636                                            R==APFloat::cmpUnordered, VT);
1637       case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1638       case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1639       }
1640     } else {
1641       // Ensure that the constant occurs on the RHS.
1642       return getSetCC(dl, VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1643     }
1644   }
1645
1646   // Could not fold it.
1647   return SDValue();
1648 }
1649
1650 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
1651 /// use this predicate to simplify operations downstream.
1652 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1653   // This predicate is not safe for vector operations.
1654   if (Op.getValueType().isVector())
1655     return false;
1656
1657   unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
1658   return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1659 }
1660
1661 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
1662 /// this predicate to simplify operations downstream.  Mask is known to be zero
1663 /// for bits that V cannot have.
1664 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1665                                      unsigned Depth) const {
1666   APInt KnownZero, KnownOne;
1667   ComputeMaskedBits(Op, KnownZero, KnownOne, Depth);
1668   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1669   return (KnownZero & Mask) == Mask;
1670 }
1671
1672 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1673 /// known to be either zero or one and return them in the KnownZero/KnownOne
1674 /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
1675 /// processing.
1676 void SelectionDAG::ComputeMaskedBits(SDValue Op, APInt &KnownZero,
1677                                      APInt &KnownOne, unsigned Depth) const {
1678   const TargetLowering *TLI = TM.getTargetLowering();
1679   unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
1680
1681   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
1682   if (Depth == 6)
1683     return;  // Limit search depth.
1684
1685   APInt KnownZero2, KnownOne2;
1686
1687   switch (Op.getOpcode()) {
1688   case ISD::Constant:
1689     // We know all of the bits for a constant!
1690     KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
1691     KnownZero = ~KnownOne;
1692     return;
1693   case ISD::AND:
1694     // If either the LHS or the RHS are Zero, the result is zero.
1695     ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
1696     ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
1697     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1698     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1699
1700     // Output known-1 bits are only known if set in both the LHS & RHS.
1701     KnownOne &= KnownOne2;
1702     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1703     KnownZero |= KnownZero2;
1704     return;
1705   case ISD::OR:
1706     ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
1707     ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
1708     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1709     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1710
1711     // Output known-0 bits are only known if clear in both the LHS & RHS.
1712     KnownZero &= KnownZero2;
1713     // Output known-1 are known to be set if set in either the LHS | RHS.
1714     KnownOne |= KnownOne2;
1715     return;
1716   case ISD::XOR: {
1717     ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
1718     ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
1719     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1720     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1721
1722     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1723     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1724     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1725     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1726     KnownZero = KnownZeroOut;
1727     return;
1728   }
1729   case ISD::MUL: {
1730     ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
1731     ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
1732     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1733     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1734
1735     // If low bits are zero in either operand, output low known-0 bits.
1736     // Also compute a conserative estimate for high known-0 bits.
1737     // More trickiness is possible, but this is sufficient for the
1738     // interesting case of alignment computation.
1739     KnownOne.clearAllBits();
1740     unsigned TrailZ = KnownZero.countTrailingOnes() +
1741                       KnownZero2.countTrailingOnes();
1742     unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
1743                                KnownZero2.countLeadingOnes(),
1744                                BitWidth) - BitWidth;
1745
1746     TrailZ = std::min(TrailZ, BitWidth);
1747     LeadZ = std::min(LeadZ, BitWidth);
1748     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1749                 APInt::getHighBitsSet(BitWidth, LeadZ);
1750     return;
1751   }
1752   case ISD::UDIV: {
1753     // For the purposes of computing leading zeros we can conservatively
1754     // treat a udiv as a logical right shift by the power of 2 known to
1755     // be less than the denominator.
1756     ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
1757     unsigned LeadZ = KnownZero2.countLeadingOnes();
1758
1759     KnownOne2.clearAllBits();
1760     KnownZero2.clearAllBits();
1761     ComputeMaskedBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
1762     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1763     if (RHSUnknownLeadingOnes != BitWidth)
1764       LeadZ = std::min(BitWidth,
1765                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1766
1767     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
1768     return;
1769   }
1770   case ISD::SELECT:
1771     ComputeMaskedBits(Op.getOperand(2), KnownZero, KnownOne, Depth+1);
1772     ComputeMaskedBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
1773     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1774     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1775
1776     // Only known if known in both the LHS and RHS.
1777     KnownOne &= KnownOne2;
1778     KnownZero &= KnownZero2;
1779     return;
1780   case ISD::SELECT_CC:
1781     ComputeMaskedBits(Op.getOperand(3), KnownZero, KnownOne, Depth+1);
1782     ComputeMaskedBits(Op.getOperand(2), KnownZero2, KnownOne2, Depth+1);
1783     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1784     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1785
1786     // Only known if known in both the LHS and RHS.
1787     KnownOne &= KnownOne2;
1788     KnownZero &= KnownZero2;
1789     return;
1790   case ISD::SADDO:
1791   case ISD::UADDO:
1792   case ISD::SSUBO:
1793   case ISD::USUBO:
1794   case ISD::SMULO:
1795   case ISD::UMULO:
1796     if (Op.getResNo() != 1)
1797       return;
1798     // The boolean result conforms to getBooleanContents.  Fall through.
1799   case ISD::SETCC:
1800     // If we know the result of a setcc has the top bits zero, use this info.
1801     if (TLI->getBooleanContents(Op.getValueType().isVector()) ==
1802         TargetLowering::ZeroOrOneBooleanContent && BitWidth > 1)
1803       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1804     return;
1805   case ISD::SHL:
1806     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
1807     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1808       unsigned ShAmt = SA->getZExtValue();
1809
1810       // If the shift count is an invalid immediate, don't do anything.
1811       if (ShAmt >= BitWidth)
1812         return;
1813
1814       ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
1815       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1816       KnownZero <<= ShAmt;
1817       KnownOne  <<= ShAmt;
1818       // low bits known zero.
1819       KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1820     }
1821     return;
1822   case ISD::SRL:
1823     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
1824     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1825       unsigned ShAmt = SA->getZExtValue();
1826
1827       // If the shift count is an invalid immediate, don't do anything.
1828       if (ShAmt >= BitWidth)
1829         return;
1830
1831       ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
1832       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1833       KnownZero = KnownZero.lshr(ShAmt);
1834       KnownOne  = KnownOne.lshr(ShAmt);
1835
1836       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
1837       KnownZero |= HighBits;  // High bits known zero.
1838     }
1839     return;
1840   case ISD::SRA:
1841     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1842       unsigned ShAmt = SA->getZExtValue();
1843
1844       // If the shift count is an invalid immediate, don't do anything.
1845       if (ShAmt >= BitWidth)
1846         return;
1847
1848       // If any of the demanded bits are produced by the sign extension, we also
1849       // demand the input sign bit.
1850       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
1851
1852       ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
1853       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1854       KnownZero = KnownZero.lshr(ShAmt);
1855       KnownOne  = KnownOne.lshr(ShAmt);
1856
1857       // Handle the sign bits.
1858       APInt SignBit = APInt::getSignBit(BitWidth);
1859       SignBit = SignBit.lshr(ShAmt);  // Adjust to where it is now in the mask.
1860
1861       if (KnownZero.intersects(SignBit)) {
1862         KnownZero |= HighBits;  // New bits are known zero.
1863       } else if (KnownOne.intersects(SignBit)) {
1864         KnownOne  |= HighBits;  // New bits are known one.
1865       }
1866     }
1867     return;
1868   case ISD::SIGN_EXTEND_INREG: {
1869     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1870     unsigned EBits = EVT.getScalarType().getSizeInBits();
1871
1872     // Sign extension.  Compute the demanded bits in the result that are not
1873     // present in the input.
1874     APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
1875
1876     APInt InSignBit = APInt::getSignBit(EBits);
1877     APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits);
1878
1879     // If the sign extended bits are demanded, we know that the sign
1880     // bit is demanded.
1881     InSignBit = InSignBit.zext(BitWidth);
1882     if (NewBits.getBoolValue())
1883       InputDemandedBits |= InSignBit;
1884
1885     ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
1886     KnownOne &= InputDemandedBits;
1887     KnownZero &= InputDemandedBits;
1888     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1889
1890     // If the sign bit of the input is known set or clear, then we know the
1891     // top bits of the result.
1892     if (KnownZero.intersects(InSignBit)) {         // Input sign bit known clear
1893       KnownZero |= NewBits;
1894       KnownOne  &= ~NewBits;
1895     } else if (KnownOne.intersects(InSignBit)) {   // Input sign bit known set
1896       KnownOne  |= NewBits;
1897       KnownZero &= ~NewBits;
1898     } else {                              // Input sign bit unknown
1899       KnownZero &= ~NewBits;
1900       KnownOne  &= ~NewBits;
1901     }
1902     return;
1903   }
1904   case ISD::CTTZ:
1905   case ISD::CTTZ_ZERO_UNDEF:
1906   case ISD::CTLZ:
1907   case ISD::CTLZ_ZERO_UNDEF:
1908   case ISD::CTPOP: {
1909     unsigned LowBits = Log2_32(BitWidth)+1;
1910     KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1911     KnownOne.clearAllBits();
1912     return;
1913   }
1914   case ISD::LOAD: {
1915     LoadSDNode *LD = cast<LoadSDNode>(Op);
1916     // If this is a ZEXTLoad and we are looking at the loaded value.
1917     if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
1918       EVT VT = LD->getMemoryVT();
1919       unsigned MemBits = VT.getScalarType().getSizeInBits();
1920       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1921     } else if (const MDNode *Ranges = LD->getRanges()) {
1922       computeMaskedBitsLoad(*Ranges, KnownZero);
1923     }
1924     return;
1925   }
1926   case ISD::ZERO_EXTEND: {
1927     EVT InVT = Op.getOperand(0).getValueType();
1928     unsigned InBits = InVT.getScalarType().getSizeInBits();
1929     APInt NewBits   = APInt::getHighBitsSet(BitWidth, BitWidth - InBits);
1930     KnownZero = KnownZero.trunc(InBits);
1931     KnownOne = KnownOne.trunc(InBits);
1932     ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
1933     KnownZero = KnownZero.zext(BitWidth);
1934     KnownOne = KnownOne.zext(BitWidth);
1935     KnownZero |= NewBits;
1936     return;
1937   }
1938   case ISD::SIGN_EXTEND: {
1939     EVT InVT = Op.getOperand(0).getValueType();
1940     unsigned InBits = InVT.getScalarType().getSizeInBits();
1941     APInt InSignBit = APInt::getSignBit(InBits);
1942     APInt NewBits   = APInt::getHighBitsSet(BitWidth, BitWidth - InBits);
1943
1944     KnownZero = KnownZero.trunc(InBits);
1945     KnownOne = KnownOne.trunc(InBits);
1946     ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
1947
1948     // Note if the sign bit is known to be zero or one.
1949     bool SignBitKnownZero = KnownZero.isNegative();
1950     bool SignBitKnownOne  = KnownOne.isNegative();
1951     assert(!(SignBitKnownZero && SignBitKnownOne) &&
1952            "Sign bit can't be known to be both zero and one!");
1953
1954     KnownZero = KnownZero.zext(BitWidth);
1955     KnownOne = KnownOne.zext(BitWidth);
1956
1957     // If the sign bit is known zero or one, the top bits match.
1958     if (SignBitKnownZero)
1959       KnownZero |= NewBits;
1960     else if (SignBitKnownOne)
1961       KnownOne  |= NewBits;
1962     return;
1963   }
1964   case ISD::ANY_EXTEND: {
1965     EVT InVT = Op.getOperand(0).getValueType();
1966     unsigned InBits = InVT.getScalarType().getSizeInBits();
1967     KnownZero = KnownZero.trunc(InBits);
1968     KnownOne = KnownOne.trunc(InBits);
1969     ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
1970     KnownZero = KnownZero.zext(BitWidth);
1971     KnownOne = KnownOne.zext(BitWidth);
1972     return;
1973   }
1974   case ISD::TRUNCATE: {
1975     EVT InVT = Op.getOperand(0).getValueType();
1976     unsigned InBits = InVT.getScalarType().getSizeInBits();
1977     KnownZero = KnownZero.zext(InBits);
1978     KnownOne = KnownOne.zext(InBits);
1979     ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
1980     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1981     KnownZero = KnownZero.trunc(BitWidth);
1982     KnownOne = KnownOne.trunc(BitWidth);
1983     break;
1984   }
1985   case ISD::AssertZext: {
1986     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1987     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1988     ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
1989     KnownZero |= (~InMask);
1990     KnownOne  &= (~KnownZero);
1991     return;
1992   }
1993   case ISD::FGETSIGN:
1994     // All bits are zero except the low bit.
1995     KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1996     return;
1997
1998   case ISD::SUB: {
1999     if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
2000       // We know that the top bits of C-X are clear if X contains less bits
2001       // than C (i.e. no wrap-around can happen).  For example, 20-X is
2002       // positive if we can prove that X is >= 0 and < 16.
2003       if (CLHS->getAPIntValue().isNonNegative()) {
2004         unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
2005         // NLZ can't be BitWidth with no sign bit
2006         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
2007         ComputeMaskedBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2008
2009         // If all of the MaskV bits are known to be zero, then we know the
2010         // output top bits are zero, because we now know that the output is
2011         // from [0-C].
2012         if ((KnownZero2 & MaskV) == MaskV) {
2013           unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
2014           // Top bits known zero.
2015           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
2016         }
2017       }
2018     }
2019   }
2020   // fall through
2021   case ISD::ADD:
2022   case ISD::ADDE: {
2023     // Output known-0 bits are known if clear or set in both the low clear bits
2024     // common to both LHS & RHS.  For example, 8+(X<<3) is known to have the
2025     // low 3 bits clear.
2026     ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
2027     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
2028     unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
2029
2030     ComputeMaskedBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2031     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
2032     KnownZeroOut = std::min(KnownZeroOut,
2033                             KnownZero2.countTrailingOnes());
2034
2035     if (Op.getOpcode() == ISD::ADD) {
2036       KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
2037       return;
2038     }
2039
2040     // With ADDE, a carry bit may be added in, so we can only use this
2041     // information if we know (at least) that the low two bits are clear.  We
2042     // then return to the caller that the low bit is unknown but that other bits
2043     // are known zero.
2044     if (KnownZeroOut >= 2) // ADDE
2045       KnownZero |= APInt::getBitsSet(BitWidth, 1, KnownZeroOut);
2046     return;
2047   }
2048   case ISD::SREM:
2049     if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2050       const APInt &RA = Rem->getAPIntValue().abs();
2051       if (RA.isPowerOf2()) {
2052         APInt LowBits = RA - 1;
2053         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
2054         ComputeMaskedBits(Op.getOperand(0), KnownZero2,KnownOne2,Depth+1);
2055
2056         // The low bits of the first operand are unchanged by the srem.
2057         KnownZero = KnownZero2 & LowBits;
2058         KnownOne = KnownOne2 & LowBits;
2059
2060         // If the first operand is non-negative or has all low bits zero, then
2061         // the upper bits are all zero.
2062         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
2063           KnownZero |= ~LowBits;
2064
2065         // If the first operand is negative and not all low bits are zero, then
2066         // the upper bits are all one.
2067         if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
2068           KnownOne |= ~LowBits;
2069         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
2070       }
2071     }
2072     return;
2073   case ISD::UREM: {
2074     if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2075       const APInt &RA = Rem->getAPIntValue();
2076       if (RA.isPowerOf2()) {
2077         APInt LowBits = (RA - 1);
2078         KnownZero |= ~LowBits;
2079         ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne,Depth+1);
2080         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
2081         break;
2082       }
2083     }
2084
2085     // Since the result is less than or equal to either operand, any leading
2086     // zero bits in either operand must also exist in the result.
2087     ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2088     ComputeMaskedBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2089
2090     uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
2091                                 KnownZero2.countLeadingOnes());
2092     KnownOne.clearAllBits();
2093     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
2094     return;
2095   }
2096   case ISD::FrameIndex:
2097   case ISD::TargetFrameIndex:
2098     if (unsigned Align = InferPtrAlignment(Op)) {
2099       // The low bits are known zero if the pointer is aligned.
2100       KnownZero = APInt::getLowBitsSet(BitWidth, Log2_32(Align));
2101       return;
2102     }
2103     break;
2104
2105   default:
2106     if (Op.getOpcode() < ISD::BUILTIN_OP_END)
2107       break;
2108     // Fallthrough
2109   case ISD::INTRINSIC_WO_CHAIN:
2110   case ISD::INTRINSIC_W_CHAIN:
2111   case ISD::INTRINSIC_VOID:
2112     // Allow the target to implement this method for its nodes.
2113     TLI->computeMaskedBitsForTargetNode(Op, KnownZero, KnownOne, *this, Depth);
2114     return;
2115   }
2116 }
2117
2118 /// ComputeNumSignBits - Return the number of times the sign bit of the
2119 /// register is replicated into the other bits.  We know that at least 1 bit
2120 /// is always equal to the sign bit (itself), but other cases can give us
2121 /// information.  For example, immediately after an "SRA X, 2", we know that
2122 /// the top 3 bits are all equal to each other, so we return 3.
2123 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
2124   const TargetLowering *TLI = TM.getTargetLowering();
2125   EVT VT = Op.getValueType();
2126   assert(VT.isInteger() && "Invalid VT!");
2127   unsigned VTBits = VT.getScalarType().getSizeInBits();
2128   unsigned Tmp, Tmp2;
2129   unsigned FirstAnswer = 1;
2130
2131   if (Depth == 6)
2132     return 1;  // Limit search depth.
2133
2134   switch (Op.getOpcode()) {
2135   default: break;
2136   case ISD::AssertSext:
2137     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2138     return VTBits-Tmp+1;
2139   case ISD::AssertZext:
2140     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2141     return VTBits-Tmp;
2142
2143   case ISD::Constant: {
2144     const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
2145     return Val.getNumSignBits();
2146   }
2147
2148   case ISD::SIGN_EXTEND:
2149     Tmp = VTBits-Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
2150     return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
2151
2152   case ISD::SIGN_EXTEND_INREG:
2153     // Max of the input and what this extends.
2154     Tmp =
2155       cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarType().getSizeInBits();
2156     Tmp = VTBits-Tmp+1;
2157
2158     Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2159     return std::max(Tmp, Tmp2);
2160
2161   case ISD::SRA:
2162     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2163     // SRA X, C   -> adds C sign bits.
2164     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2165       Tmp += C->getZExtValue();
2166       if (Tmp > VTBits) Tmp = VTBits;
2167     }
2168     return Tmp;
2169   case ISD::SHL:
2170     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2171       // shl destroys sign bits.
2172       Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2173       if (C->getZExtValue() >= VTBits ||      // Bad shift.
2174           C->getZExtValue() >= Tmp) break;    // Shifted all sign bits out.
2175       return Tmp - C->getZExtValue();
2176     }
2177     break;
2178   case ISD::AND:
2179   case ISD::OR:
2180   case ISD::XOR:    // NOT is handled here.
2181     // Logical binary ops preserve the number of sign bits at the worst.
2182     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2183     if (Tmp != 1) {
2184       Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2185       FirstAnswer = std::min(Tmp, Tmp2);
2186       // We computed what we know about the sign bits as our first
2187       // answer. Now proceed to the generic code that uses
2188       // ComputeMaskedBits, and pick whichever answer is better.
2189     }
2190     break;
2191
2192   case ISD::SELECT:
2193     Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2194     if (Tmp == 1) return 1;  // Early out.
2195     Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
2196     return std::min(Tmp, Tmp2);
2197
2198   case ISD::SADDO:
2199   case ISD::UADDO:
2200   case ISD::SSUBO:
2201   case ISD::USUBO:
2202   case ISD::SMULO:
2203   case ISD::UMULO:
2204     if (Op.getResNo() != 1)
2205       break;
2206     // The boolean result conforms to getBooleanContents.  Fall through.
2207   case ISD::SETCC:
2208     // If setcc returns 0/-1, all bits are sign bits.
2209     if (TLI->getBooleanContents(Op.getValueType().isVector()) ==
2210         TargetLowering::ZeroOrNegativeOneBooleanContent)
2211       return VTBits;
2212     break;
2213   case ISD::ROTL:
2214   case ISD::ROTR:
2215     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2216       unsigned RotAmt = C->getZExtValue() & (VTBits-1);
2217
2218       // Handle rotate right by N like a rotate left by 32-N.
2219       if (Op.getOpcode() == ISD::ROTR)
2220         RotAmt = (VTBits-RotAmt) & (VTBits-1);
2221
2222       // If we aren't rotating out all of the known-in sign bits, return the
2223       // number that are left.  This handles rotl(sext(x), 1) for example.
2224       Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2225       if (Tmp > RotAmt+1) return Tmp-RotAmt;
2226     }
2227     break;
2228   case ISD::ADD:
2229     // Add can have at most one carry bit.  Thus we know that the output
2230     // is, at worst, one more bit than the inputs.
2231     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2232     if (Tmp == 1) return 1;  // Early out.
2233
2234     // Special case decrementing a value (ADD X, -1):
2235     if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2236       if (CRHS->isAllOnesValue()) {
2237         APInt KnownZero, KnownOne;
2238         ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2239
2240         // If the input is known to be 0 or 1, the output is 0/-1, which is all
2241         // sign bits set.
2242         if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue())
2243           return VTBits;
2244
2245         // If we are subtracting one from a positive number, there is no carry
2246         // out of the result.
2247         if (KnownZero.isNegative())
2248           return Tmp;
2249       }
2250
2251     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2252     if (Tmp2 == 1) return 1;
2253     return std::min(Tmp, Tmp2)-1;
2254
2255   case ISD::SUB:
2256     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2257     if (Tmp2 == 1) return 1;
2258
2259     // Handle NEG.
2260     if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
2261       if (CLHS->isNullValue()) {
2262         APInt KnownZero, KnownOne;
2263         ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
2264         // If the input is known to be 0 or 1, the output is 0/-1, which is all
2265         // sign bits set.
2266         if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue())
2267           return VTBits;
2268
2269         // If the input is known to be positive (the sign bit is known clear),
2270         // the output of the NEG has the same number of sign bits as the input.
2271         if (KnownZero.isNegative())
2272           return Tmp2;
2273
2274         // Otherwise, we treat this like a SUB.
2275       }
2276
2277     // Sub can have at most one carry bit.  Thus we know that the output
2278     // is, at worst, one more bit than the inputs.
2279     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2280     if (Tmp == 1) return 1;  // Early out.
2281     return std::min(Tmp, Tmp2)-1;
2282   case ISD::TRUNCATE:
2283     // FIXME: it's tricky to do anything useful for this, but it is an important
2284     // case for targets like X86.
2285     break;
2286   }
2287
2288   // If we are looking at the loaded value of the SDNode.
2289   if (Op.getResNo() == 0) {
2290     // Handle LOADX separately here. EXTLOAD case will fallthrough.
2291     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
2292       unsigned ExtType = LD->getExtensionType();
2293       switch (ExtType) {
2294         default: break;
2295         case ISD::SEXTLOAD:    // '17' bits known
2296           Tmp = LD->getMemoryVT().getScalarType().getSizeInBits();
2297           return VTBits-Tmp+1;
2298         case ISD::ZEXTLOAD:    // '16' bits known
2299           Tmp = LD->getMemoryVT().getScalarType().getSizeInBits();
2300           return VTBits-Tmp;
2301       }
2302     }
2303   }
2304
2305   // Allow the target to implement this method for its nodes.
2306   if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2307       Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2308       Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2309       Op.getOpcode() == ISD::INTRINSIC_VOID) {
2310     unsigned NumBits = TLI->ComputeNumSignBitsForTargetNode(Op, Depth);
2311     if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
2312   }
2313
2314   // Finally, if we can prove that the top bits of the result are 0's or 1's,
2315   // use this information.
2316   APInt KnownZero, KnownOne;
2317   ComputeMaskedBits(Op, KnownZero, KnownOne, Depth);
2318
2319   APInt Mask;
2320   if (KnownZero.isNegative()) {        // sign bit is 0
2321     Mask = KnownZero;
2322   } else if (KnownOne.isNegative()) {  // sign bit is 1;
2323     Mask = KnownOne;
2324   } else {
2325     // Nothing known.
2326     return FirstAnswer;
2327   }
2328
2329   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
2330   // the number of identical bits in the top of the input value.
2331   Mask = ~Mask;
2332   Mask <<= Mask.getBitWidth()-VTBits;
2333   // Return # leading zeros.  We use 'min' here in case Val was zero before
2334   // shifting.  We don't want to return '64' as for an i32 "0".
2335   return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
2336 }
2337
2338 /// isBaseWithConstantOffset - Return true if the specified operand is an
2339 /// ISD::ADD with a ConstantSDNode on the right-hand side, or if it is an
2340 /// ISD::OR with a ConstantSDNode that is guaranteed to have the same
2341 /// semantics as an ADD.  This handles the equivalence:
2342 ///     X|Cst == X+Cst iff X&Cst = 0.
2343 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
2344   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
2345       !isa<ConstantSDNode>(Op.getOperand(1)))
2346     return false;
2347
2348   if (Op.getOpcode() == ISD::OR &&
2349       !MaskedValueIsZero(Op.getOperand(0),
2350                      cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue()))
2351     return false;
2352
2353   return true;
2354 }
2355
2356
2357 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
2358   // If we're told that NaNs won't happen, assume they won't.
2359   if (getTarget().Options.NoNaNsFPMath)
2360     return true;
2361
2362   // If the value is a constant, we can obviously see if it is a NaN or not.
2363   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2364     return !C->getValueAPF().isNaN();
2365
2366   // TODO: Recognize more cases here.
2367
2368   return false;
2369 }
2370
2371 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
2372   // If the value is a constant, we can obviously see if it is a zero or not.
2373   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2374     return !C->isZero();
2375
2376   // TODO: Recognize more cases here.
2377   switch (Op.getOpcode()) {
2378   default: break;
2379   case ISD::OR:
2380     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2381       return !C->isNullValue();
2382     break;
2383   }
2384
2385   return false;
2386 }
2387
2388 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
2389   // Check the obvious case.
2390   if (A == B) return true;
2391
2392   // For for negative and positive zero.
2393   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
2394     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
2395       if (CA->isZero() && CB->isZero()) return true;
2396
2397   // Otherwise they may not be equal.
2398   return false;
2399 }
2400
2401 /// getNode - Gets or creates the specified node.
2402 ///
2403 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT) {
2404   FoldingSetNodeID ID;
2405   AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
2406   void *IP = 0;
2407   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2408     return SDValue(E, 0);
2409
2410   SDNode *N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), getVTList(VT));
2411   CSEMap.InsertNode(N, IP);
2412
2413   AllNodes.push_back(N);
2414 #ifndef NDEBUG
2415   VerifySDNode(N);
2416 #endif
2417   return SDValue(N, 0);
2418 }
2419
2420 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL,
2421                               EVT VT, SDValue Operand) {
2422   // Constant fold unary operations with an integer constant operand.
2423   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) {
2424     const APInt &Val = C->getAPIntValue();
2425     switch (Opcode) {
2426     default: break;
2427     case ISD::SIGN_EXTEND:
2428       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), VT);
2429     case ISD::ANY_EXTEND:
2430     case ISD::ZERO_EXTEND:
2431     case ISD::TRUNCATE:
2432       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), VT);
2433     case ISD::UINT_TO_FP:
2434     case ISD::SINT_TO_FP: {
2435       APFloat apf(EVTToAPFloatSemantics(VT),
2436                   APInt::getNullValue(VT.getSizeInBits()));
2437       (void)apf.convertFromAPInt(Val,
2438                                  Opcode==ISD::SINT_TO_FP,
2439                                  APFloat::rmNearestTiesToEven);
2440       return getConstantFP(apf, VT);
2441     }
2442     case ISD::BITCAST:
2443       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2444         return getConstantFP(APFloat(APFloat::IEEEsingle, Val), VT);
2445       else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2446         return getConstantFP(APFloat(APFloat::IEEEdouble, Val), VT);
2447       break;
2448     case ISD::BSWAP:
2449       return getConstant(Val.byteSwap(), VT);
2450     case ISD::CTPOP:
2451       return getConstant(Val.countPopulation(), VT);
2452     case ISD::CTLZ:
2453     case ISD::CTLZ_ZERO_UNDEF:
2454       return getConstant(Val.countLeadingZeros(), VT);
2455     case ISD::CTTZ:
2456     case ISD::CTTZ_ZERO_UNDEF:
2457       return getConstant(Val.countTrailingZeros(), VT);
2458     }
2459   }
2460
2461   // Constant fold unary operations with a floating point constant operand.
2462   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
2463     APFloat V = C->getValueAPF();    // make copy
2464     switch (Opcode) {
2465     case ISD::FNEG:
2466       V.changeSign();
2467       return getConstantFP(V, VT);
2468     case ISD::FABS:
2469       V.clearSign();
2470       return getConstantFP(V, VT);
2471     case ISD::FCEIL: {
2472       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
2473       if (fs == APFloat::opOK || fs == APFloat::opInexact)
2474         return getConstantFP(V, VT);
2475       break;
2476     }
2477     case ISD::FTRUNC: {
2478       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
2479       if (fs == APFloat::opOK || fs == APFloat::opInexact)
2480         return getConstantFP(V, VT);
2481       break;
2482     }
2483     case ISD::FFLOOR: {
2484       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
2485       if (fs == APFloat::opOK || fs == APFloat::opInexact)
2486         return getConstantFP(V, VT);
2487       break;
2488     }
2489     case ISD::FP_EXTEND: {
2490       bool ignored;
2491       // This can return overflow, underflow, or inexact; we don't care.
2492       // FIXME need to be more flexible about rounding mode.
2493       (void)V.convert(EVTToAPFloatSemantics(VT),
2494                       APFloat::rmNearestTiesToEven, &ignored);
2495       return getConstantFP(V, VT);
2496     }
2497     case ISD::FP_TO_SINT:
2498     case ISD::FP_TO_UINT: {
2499       integerPart x[2];
2500       bool ignored;
2501       assert(integerPartWidth >= 64);
2502       // FIXME need to be more flexible about rounding mode.
2503       APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(),
2504                             Opcode==ISD::FP_TO_SINT,
2505                             APFloat::rmTowardZero, &ignored);
2506       if (s==APFloat::opInvalidOp)     // inexact is OK, in fact usual
2507         break;
2508       APInt api(VT.getSizeInBits(), x);
2509       return getConstant(api, VT);
2510     }
2511     case ISD::BITCAST:
2512       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2513         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT);
2514       else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2515         return getConstant(V.bitcastToAPInt().getZExtValue(), VT);
2516       break;
2517     }
2518   }
2519
2520   unsigned OpOpcode = Operand.getNode()->getOpcode();
2521   switch (Opcode) {
2522   case ISD::TokenFactor:
2523   case ISD::MERGE_VALUES:
2524   case ISD::CONCAT_VECTORS:
2525     return Operand;         // Factor, merge or concat of one node?  No need.
2526   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
2527   case ISD::FP_EXTEND:
2528     assert(VT.isFloatingPoint() &&
2529            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2530     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
2531     assert((!VT.isVector() ||
2532             VT.getVectorNumElements() ==
2533             Operand.getValueType().getVectorNumElements()) &&
2534            "Vector element count mismatch!");
2535     if (Operand.getOpcode() == ISD::UNDEF)
2536       return getUNDEF(VT);
2537     break;
2538   case ISD::SIGN_EXTEND:
2539     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2540            "Invalid SIGN_EXTEND!");
2541     if (Operand.getValueType() == VT) return Operand;   // noop extension
2542     assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2543            "Invalid sext node, dst < src!");
2544     assert((!VT.isVector() ||
2545             VT.getVectorNumElements() ==
2546             Operand.getValueType().getVectorNumElements()) &&
2547            "Vector element count mismatch!");
2548     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2549       return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2550     else if (OpOpcode == ISD::UNDEF)
2551       // sext(undef) = 0, because the top bits will all be the same.
2552       return getConstant(0, VT);
2553     break;
2554   case ISD::ZERO_EXTEND:
2555     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2556            "Invalid ZERO_EXTEND!");
2557     if (Operand.getValueType() == VT) return Operand;   // noop extension
2558     assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2559            "Invalid zext node, dst < src!");
2560     assert((!VT.isVector() ||
2561             VT.getVectorNumElements() ==
2562             Operand.getValueType().getVectorNumElements()) &&
2563            "Vector element count mismatch!");
2564     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
2565       return getNode(ISD::ZERO_EXTEND, DL, VT,
2566                      Operand.getNode()->getOperand(0));
2567     else if (OpOpcode == ISD::UNDEF)
2568       // zext(undef) = 0, because the top bits will be zero.
2569       return getConstant(0, VT);
2570     break;
2571   case ISD::ANY_EXTEND:
2572     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2573            "Invalid ANY_EXTEND!");
2574     if (Operand.getValueType() == VT) return Operand;   // noop extension
2575     assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2576            "Invalid anyext node, dst < src!");
2577     assert((!VT.isVector() ||
2578             VT.getVectorNumElements() ==
2579             Operand.getValueType().getVectorNumElements()) &&
2580            "Vector element count mismatch!");
2581
2582     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2583         OpOpcode == ISD::ANY_EXTEND)
2584       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
2585       return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2586     else if (OpOpcode == ISD::UNDEF)
2587       return getUNDEF(VT);
2588
2589     // (ext (trunx x)) -> x
2590     if (OpOpcode == ISD::TRUNCATE) {
2591       SDValue OpOp = Operand.getNode()->getOperand(0);
2592       if (OpOp.getValueType() == VT)
2593         return OpOp;
2594     }
2595     break;
2596   case ISD::TRUNCATE:
2597     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2598            "Invalid TRUNCATE!");
2599     if (Operand.getValueType() == VT) return Operand;   // noop truncate
2600     assert(Operand.getValueType().getScalarType().bitsGT(VT.getScalarType()) &&
2601            "Invalid truncate node, src < dst!");
2602     assert((!VT.isVector() ||
2603             VT.getVectorNumElements() ==
2604             Operand.getValueType().getVectorNumElements()) &&
2605            "Vector element count mismatch!");
2606     if (OpOpcode == ISD::TRUNCATE)
2607       return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2608     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2609         OpOpcode == ISD::ANY_EXTEND) {
2610       // If the source is smaller than the dest, we still need an extend.
2611       if (Operand.getNode()->getOperand(0).getValueType().getScalarType()
2612             .bitsLT(VT.getScalarType()))
2613         return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2614       if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
2615         return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2616       return Operand.getNode()->getOperand(0);
2617     }
2618     if (OpOpcode == ISD::UNDEF)
2619       return getUNDEF(VT);
2620     break;
2621   case ISD::BITCAST:
2622     // Basic sanity checking.
2623     assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2624            && "Cannot BITCAST between types of different sizes!");
2625     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
2626     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
2627       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
2628     if (OpOpcode == ISD::UNDEF)
2629       return getUNDEF(VT);
2630     break;
2631   case ISD::SCALAR_TO_VECTOR:
2632     assert(VT.isVector() && !Operand.getValueType().isVector() &&
2633            (VT.getVectorElementType() == Operand.getValueType() ||
2634             (VT.getVectorElementType().isInteger() &&
2635              Operand.getValueType().isInteger() &&
2636              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
2637            "Illegal SCALAR_TO_VECTOR node!");
2638     if (OpOpcode == ISD::UNDEF)
2639       return getUNDEF(VT);
2640     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2641     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2642         isa<ConstantSDNode>(Operand.getOperand(1)) &&
2643         Operand.getConstantOperandVal(1) == 0 &&
2644         Operand.getOperand(0).getValueType() == VT)
2645       return Operand.getOperand(0);
2646     break;
2647   case ISD::FNEG:
2648     // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
2649     if (getTarget().Options.UnsafeFPMath && OpOpcode == ISD::FSUB)
2650       return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
2651                      Operand.getNode()->getOperand(0));
2652     if (OpOpcode == ISD::FNEG)  // --X -> X
2653       return Operand.getNode()->getOperand(0);
2654     break;
2655   case ISD::FABS:
2656     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
2657       return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
2658     break;
2659   }
2660
2661   SDNode *N;
2662   SDVTList VTs = getVTList(VT);
2663   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
2664     FoldingSetNodeID ID;
2665     SDValue Ops[1] = { Operand };
2666     AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2667     void *IP = 0;
2668     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2669       return SDValue(E, 0);
2670
2671     N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, Operand);
2672     CSEMap.InsertNode(N, IP);
2673   } else {
2674     N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, Operand);
2675   }
2676
2677   AllNodes.push_back(N);
2678 #ifndef NDEBUG
2679   VerifySDNode(N);
2680 #endif
2681   return SDValue(N, 0);
2682 }
2683
2684 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, EVT VT,
2685                                              SDNode *Cst1, SDNode *Cst2) {
2686   SmallVector<std::pair<ConstantSDNode *, ConstantSDNode *>, 4> Inputs;
2687   SmallVector<SDValue, 4> Outputs;
2688   EVT SVT = VT.getScalarType();
2689
2690   ConstantSDNode *Scalar1 = dyn_cast<ConstantSDNode>(Cst1);
2691   ConstantSDNode *Scalar2 = dyn_cast<ConstantSDNode>(Cst2);
2692   if (Scalar1 && Scalar2) {
2693     // Scalar instruction.
2694     Inputs.push_back(std::make_pair(Scalar1, Scalar2));
2695   } else {
2696     // For vectors extract each constant element into Inputs so we can constant
2697     // fold them individually.
2698     BuildVectorSDNode *BV1 = dyn_cast<BuildVectorSDNode>(Cst1);
2699     BuildVectorSDNode *BV2 = dyn_cast<BuildVectorSDNode>(Cst2);
2700     if (!BV1 || !BV2)
2701       return SDValue();
2702
2703     assert(BV1->getNumOperands() == BV2->getNumOperands() && "Out of sync!");
2704
2705     for (unsigned I = 0, E = BV1->getNumOperands(); I != E; ++I) {
2706       ConstantSDNode *V1 = dyn_cast<ConstantSDNode>(BV1->getOperand(I));
2707       ConstantSDNode *V2 = dyn_cast<ConstantSDNode>(BV2->getOperand(I));
2708       if (!V1 || !V2) // Not a constant, bail.
2709         return SDValue();
2710
2711       // Avoid BUILD_VECTOR nodes that perform implicit truncation.
2712       // FIXME: This is valid and could be handled by truncating the APInts.
2713       if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
2714         return SDValue();
2715
2716       Inputs.push_back(std::make_pair(V1, V2));
2717     }
2718   }
2719
2720   // We have a number of constant values, constant fold them element by element.
2721   for (unsigned I = 0, E = Inputs.size(); I != E; ++I) {
2722     const APInt &C1 = Inputs[I].first->getAPIntValue();
2723     const APInt &C2 = Inputs[I].second->getAPIntValue();
2724
2725     switch (Opcode) {
2726     case ISD::ADD:
2727       Outputs.push_back(getConstant(C1 + C2, SVT));
2728       break;
2729     case ISD::SUB:
2730       Outputs.push_back(getConstant(C1 - C2, SVT));
2731       break;
2732     case ISD::MUL:
2733       Outputs.push_back(getConstant(C1 * C2, SVT));
2734       break;
2735     case ISD::UDIV:
2736       if (!C2.getBoolValue())
2737         return SDValue();
2738       Outputs.push_back(getConstant(C1.udiv(C2), SVT));
2739       break;
2740     case ISD::UREM:
2741       if (!C2.getBoolValue())
2742         return SDValue();
2743       Outputs.push_back(getConstant(C1.urem(C2), SVT));
2744       break;
2745     case ISD::SDIV:
2746       if (!C2.getBoolValue())
2747         return SDValue();
2748       Outputs.push_back(getConstant(C1.sdiv(C2), SVT));
2749       break;
2750     case ISD::SREM:
2751       if (!C2.getBoolValue())
2752         return SDValue();
2753       Outputs.push_back(getConstant(C1.srem(C2), SVT));
2754       break;
2755     case ISD::AND:
2756       Outputs.push_back(getConstant(C1 & C2, SVT));
2757       break;
2758     case ISD::OR:
2759       Outputs.push_back(getConstant(C1 | C2, SVT));
2760       break;
2761     case ISD::XOR:
2762       Outputs.push_back(getConstant(C1 ^ C2, SVT));
2763       break;
2764     case ISD::SHL:
2765       Outputs.push_back(getConstant(C1 << C2, SVT));
2766       break;
2767     case ISD::SRL:
2768       Outputs.push_back(getConstant(C1.lshr(C2), SVT));
2769       break;
2770     case ISD::SRA:
2771       Outputs.push_back(getConstant(C1.ashr(C2), SVT));
2772       break;
2773     case ISD::ROTL:
2774       Outputs.push_back(getConstant(C1.rotl(C2), SVT));
2775       break;
2776     case ISD::ROTR:
2777       Outputs.push_back(getConstant(C1.rotr(C2), SVT));
2778       break;
2779     default:
2780       return SDValue();
2781     }
2782   }
2783
2784   // Handle the scalar case first.
2785   if (Scalar1 && Scalar2)
2786     return Outputs.back();
2787
2788   // Otherwise build a big vector out of the scalar elements we generated.
2789   return getNode(ISD::BUILD_VECTOR, SDLoc(), VT, Outputs.data(),
2790                  Outputs.size());
2791 }
2792
2793 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT, SDValue N1,
2794                               SDValue N2) {
2795   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2796   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2797   switch (Opcode) {
2798   default: break;
2799   case ISD::TokenFactor:
2800     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2801            N2.getValueType() == MVT::Other && "Invalid token factor!");
2802     // Fold trivial token factors.
2803     if (N1.getOpcode() == ISD::EntryToken) return N2;
2804     if (N2.getOpcode() == ISD::EntryToken) return N1;
2805     if (N1 == N2) return N1;
2806     break;
2807   case ISD::CONCAT_VECTORS:
2808     // Concat of UNDEFs is UNDEF.
2809     if (N1.getOpcode() == ISD::UNDEF &&
2810         N2.getOpcode() == ISD::UNDEF)
2811       return getUNDEF(VT);
2812
2813     // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2814     // one big BUILD_VECTOR.
2815     if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2816         N2.getOpcode() == ISD::BUILD_VECTOR) {
2817       SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(),
2818                                     N1.getNode()->op_end());
2819       Elts.append(N2.getNode()->op_begin(), N2.getNode()->op_end());
2820       return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
2821     }
2822     break;
2823   case ISD::AND:
2824     assert(VT.isInteger() && "This operator does not apply to FP types!");
2825     assert(N1.getValueType() == N2.getValueType() &&
2826            N1.getValueType() == VT && "Binary operator types must match!");
2827     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
2828     // worth handling here.
2829     if (N2C && N2C->isNullValue())
2830       return N2;
2831     if (N2C && N2C->isAllOnesValue())  // X & -1 -> X
2832       return N1;
2833     break;
2834   case ISD::OR:
2835   case ISD::XOR:
2836   case ISD::ADD:
2837   case ISD::SUB:
2838     assert(VT.isInteger() && "This operator does not apply to FP types!");
2839     assert(N1.getValueType() == N2.getValueType() &&
2840            N1.getValueType() == VT && "Binary operator types must match!");
2841     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
2842     // it's worth handling here.
2843     if (N2C && N2C->isNullValue())
2844       return N1;
2845     break;
2846   case ISD::UDIV:
2847   case ISD::UREM:
2848   case ISD::MULHU:
2849   case ISD::MULHS:
2850   case ISD::MUL:
2851   case ISD::SDIV:
2852   case ISD::SREM:
2853     assert(VT.isInteger() && "This operator does not apply to FP types!");
2854     assert(N1.getValueType() == N2.getValueType() &&
2855            N1.getValueType() == VT && "Binary operator types must match!");
2856     break;
2857   case ISD::FADD:
2858   case ISD::FSUB:
2859   case ISD::FMUL:
2860   case ISD::FDIV:
2861   case ISD::FREM:
2862     if (getTarget().Options.UnsafeFPMath) {
2863       if (Opcode == ISD::FADD) {
2864         // 0+x --> x
2865         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1))
2866           if (CFP->getValueAPF().isZero())
2867             return N2;
2868         // x+0 --> x
2869         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2870           if (CFP->getValueAPF().isZero())
2871             return N1;
2872       } else if (Opcode == ISD::FSUB) {
2873         // x-0 --> x
2874         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2875           if (CFP->getValueAPF().isZero())
2876             return N1;
2877       } else if (Opcode == ISD::FMUL) {
2878         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1);
2879         SDValue V = N2;
2880
2881         // If the first operand isn't the constant, try the second
2882         if (!CFP) {
2883           CFP = dyn_cast<ConstantFPSDNode>(N2);
2884           V = N1;
2885         }
2886
2887         if (CFP) {
2888           // 0*x --> 0
2889           if (CFP->isZero())
2890             return SDValue(CFP,0);
2891           // 1*x --> x
2892           if (CFP->isExactlyValue(1.0))
2893             return V;
2894         }
2895       }
2896     }
2897     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
2898     assert(N1.getValueType() == N2.getValueType() &&
2899            N1.getValueType() == VT && "Binary operator types must match!");
2900     break;
2901   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
2902     assert(N1.getValueType() == VT &&
2903            N1.getValueType().isFloatingPoint() &&
2904            N2.getValueType().isFloatingPoint() &&
2905            "Invalid FCOPYSIGN!");
2906     break;
2907   case ISD::SHL:
2908   case ISD::SRA:
2909   case ISD::SRL:
2910   case ISD::ROTL:
2911   case ISD::ROTR:
2912     assert(VT == N1.getValueType() &&
2913            "Shift operators return type must be the same as their first arg");
2914     assert(VT.isInteger() && N2.getValueType().isInteger() &&
2915            "Shifts only work on integers");
2916     assert((!VT.isVector() || VT == N2.getValueType()) &&
2917            "Vector shift amounts must be in the same as their first arg");
2918     // Verify that the shift amount VT is bit enough to hold valid shift
2919     // amounts.  This catches things like trying to shift an i1024 value by an
2920     // i8, which is easy to fall into in generic code that uses
2921     // TLI.getShiftAmount().
2922     assert(N2.getValueType().getSizeInBits() >=
2923                    Log2_32_Ceil(N1.getValueType().getSizeInBits()) &&
2924            "Invalid use of small shift amount with oversized value!");
2925
2926     // Always fold shifts of i1 values so the code generator doesn't need to
2927     // handle them.  Since we know the size of the shift has to be less than the
2928     // size of the value, the shift/rotate count is guaranteed to be zero.
2929     if (VT == MVT::i1)
2930       return N1;
2931     if (N2C && N2C->isNullValue())
2932       return N1;
2933     break;
2934   case ISD::FP_ROUND_INREG: {
2935     EVT EVT = cast<VTSDNode>(N2)->getVT();
2936     assert(VT == N1.getValueType() && "Not an inreg round!");
2937     assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2938            "Cannot FP_ROUND_INREG integer types");
2939     assert(EVT.isVector() == VT.isVector() &&
2940            "FP_ROUND_INREG type should be vector iff the operand "
2941            "type is vector!");
2942     assert((!EVT.isVector() ||
2943             EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
2944            "Vector element counts must match in FP_ROUND_INREG");
2945     assert(EVT.bitsLE(VT) && "Not rounding down!");
2946     (void)EVT;
2947     if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
2948     break;
2949   }
2950   case ISD::FP_ROUND:
2951     assert(VT.isFloatingPoint() &&
2952            N1.getValueType().isFloatingPoint() &&
2953            VT.bitsLE(N1.getValueType()) &&
2954            isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2955     if (N1.getValueType() == VT) return N1;  // noop conversion.
2956     break;
2957   case ISD::AssertSext:
2958   case ISD::AssertZext: {
2959     EVT EVT = cast<VTSDNode>(N2)->getVT();
2960     assert(VT == N1.getValueType() && "Not an inreg extend!");
2961     assert(VT.isInteger() && EVT.isInteger() &&
2962            "Cannot *_EXTEND_INREG FP types");
2963     assert(!EVT.isVector() &&
2964            "AssertSExt/AssertZExt type should be the vector element type "
2965            "rather than the vector type!");
2966     assert(EVT.bitsLE(VT) && "Not extending!");
2967     if (VT == EVT) return N1; // noop assertion.
2968     break;
2969   }
2970   case ISD::SIGN_EXTEND_INREG: {
2971     EVT EVT = cast<VTSDNode>(N2)->getVT();
2972     assert(VT == N1.getValueType() && "Not an inreg extend!");
2973     assert(VT.isInteger() && EVT.isInteger() &&
2974            "Cannot *_EXTEND_INREG FP types");
2975     assert(EVT.isVector() == VT.isVector() &&
2976            "SIGN_EXTEND_INREG type should be vector iff the operand "
2977            "type is vector!");
2978     assert((!EVT.isVector() ||
2979             EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
2980            "Vector element counts must match in SIGN_EXTEND_INREG");
2981     assert(EVT.bitsLE(VT) && "Not extending!");
2982     if (EVT == VT) return N1;  // Not actually extending
2983
2984     if (N1C) {
2985       APInt Val = N1C->getAPIntValue();
2986       unsigned FromBits = EVT.getScalarType().getSizeInBits();
2987       Val <<= Val.getBitWidth()-FromBits;
2988       Val = Val.ashr(Val.getBitWidth()-FromBits);
2989       return getConstant(Val, VT);
2990     }
2991     break;
2992   }
2993   case ISD::EXTRACT_VECTOR_ELT:
2994     // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2995     if (N1.getOpcode() == ISD::UNDEF)
2996       return getUNDEF(VT);
2997
2998     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2999     // expanding copies of large vectors from registers.
3000     if (N2C &&
3001         N1.getOpcode() == ISD::CONCAT_VECTORS &&
3002         N1.getNumOperands() > 0) {
3003       unsigned Factor =
3004         N1.getOperand(0).getValueType().getVectorNumElements();
3005       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
3006                      N1.getOperand(N2C->getZExtValue() / Factor),
3007                      getConstant(N2C->getZExtValue() % Factor,
3008                                  N2.getValueType()));
3009     }
3010
3011     // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
3012     // expanding large vector constants.
3013     if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
3014       SDValue Elt = N1.getOperand(N2C->getZExtValue());
3015
3016       if (VT != Elt.getValueType())
3017         // If the vector element type is not legal, the BUILD_VECTOR operands
3018         // are promoted and implicitly truncated, and the result implicitly
3019         // extended. Make that explicit here.
3020         Elt = getAnyExtOrTrunc(Elt, DL, VT);
3021
3022       return Elt;
3023     }
3024
3025     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
3026     // operations are lowered to scalars.
3027     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
3028       // If the indices are the same, return the inserted element else
3029       // if the indices are known different, extract the element from
3030       // the original vector.
3031       SDValue N1Op2 = N1.getOperand(2);
3032       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2.getNode());
3033
3034       if (N1Op2C && N2C) {
3035         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
3036           if (VT == N1.getOperand(1).getValueType())
3037             return N1.getOperand(1);
3038           else
3039             return getSExtOrTrunc(N1.getOperand(1), DL, VT);
3040         }
3041
3042         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
3043       }
3044     }
3045     break;
3046   case ISD::EXTRACT_ELEMENT:
3047     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
3048     assert(!N1.getValueType().isVector() && !VT.isVector() &&
3049            (N1.getValueType().isInteger() == VT.isInteger()) &&
3050            N1.getValueType() != VT &&
3051            "Wrong types for EXTRACT_ELEMENT!");
3052
3053     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
3054     // 64-bit integers into 32-bit parts.  Instead of building the extract of
3055     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
3056     if (N1.getOpcode() == ISD::BUILD_PAIR)
3057       return N1.getOperand(N2C->getZExtValue());
3058
3059     // EXTRACT_ELEMENT of a constant int is also very common.
3060     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3061       unsigned ElementSize = VT.getSizeInBits();
3062       unsigned Shift = ElementSize * N2C->getZExtValue();
3063       APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
3064       return getConstant(ShiftedVal.trunc(ElementSize), VT);
3065     }
3066     break;
3067   case ISD::EXTRACT_SUBVECTOR: {
3068     SDValue Index = N2;
3069     if (VT.isSimple() && N1.getValueType().isSimple()) {
3070       assert(VT.isVector() && N1.getValueType().isVector() &&
3071              "Extract subvector VTs must be a vectors!");
3072       assert(VT.getVectorElementType() == N1.getValueType().getVectorElementType() &&
3073              "Extract subvector VTs must have the same element type!");
3074       assert(VT.getSimpleVT() <= N1.getValueType().getSimpleVT() &&
3075              "Extract subvector must be from larger vector to smaller vector!");
3076
3077       if (isa<ConstantSDNode>(Index.getNode())) {
3078         assert((VT.getVectorNumElements() +
3079                 cast<ConstantSDNode>(Index.getNode())->getZExtValue()
3080                 <= N1.getValueType().getVectorNumElements())
3081                && "Extract subvector overflow!");
3082       }
3083
3084       // Trivial extraction.
3085       if (VT.getSimpleVT() == N1.getValueType().getSimpleVT())
3086         return N1;
3087     }
3088     break;
3089   }
3090   }
3091
3092   // Perform trivial constant folding.
3093   SDValue SV = FoldConstantArithmetic(Opcode, VT, N1.getNode(), N2.getNode());
3094   if (SV.getNode()) return SV;
3095
3096   // Canonicalize constant to RHS if commutative.
3097   if (N1C && !N2C && isCommutativeBinOp(Opcode)) {
3098     std::swap(N1C, N2C);
3099     std::swap(N1, N2);
3100   }
3101
3102   // Constant fold FP operations.
3103   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
3104   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
3105   if (N1CFP) {
3106     if (!N2CFP && isCommutativeBinOp(Opcode)) {
3107       // Canonicalize constant to RHS if commutative.
3108       std::swap(N1CFP, N2CFP);
3109       std::swap(N1, N2);
3110     } else if (N2CFP) {
3111       APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
3112       APFloat::opStatus s;
3113       switch (Opcode) {
3114       case ISD::FADD:
3115         s = V1.add(V2, APFloat::rmNearestTiesToEven);
3116         if (s != APFloat::opInvalidOp)
3117           return getConstantFP(V1, VT);
3118         break;
3119       case ISD::FSUB:
3120         s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
3121         if (s!=APFloat::opInvalidOp)
3122           return getConstantFP(V1, VT);
3123         break;
3124       case ISD::FMUL:
3125         s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
3126         if (s!=APFloat::opInvalidOp)
3127           return getConstantFP(V1, VT);
3128         break;
3129       case ISD::FDIV:
3130         s = V1.divide(V2, APFloat::rmNearestTiesToEven);
3131         if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
3132           return getConstantFP(V1, VT);
3133         break;
3134       case ISD::FREM :
3135         s = V1.mod(V2, APFloat::rmNearestTiesToEven);
3136         if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
3137           return getConstantFP(V1, VT);
3138         break;
3139       case ISD::FCOPYSIGN:
3140         V1.copySign(V2);
3141         return getConstantFP(V1, VT);
3142       default: break;
3143       }
3144     }
3145
3146     if (Opcode == ISD::FP_ROUND) {
3147       APFloat V = N1CFP->getValueAPF();    // make copy
3148       bool ignored;
3149       // This can return overflow, underflow, or inexact; we don't care.
3150       // FIXME need to be more flexible about rounding mode.
3151       (void)V.convert(EVTToAPFloatSemantics(VT),
3152                       APFloat::rmNearestTiesToEven, &ignored);
3153       return getConstantFP(V, VT);
3154     }
3155   }
3156
3157   // Canonicalize an UNDEF to the RHS, even over a constant.
3158   if (N1.getOpcode() == ISD::UNDEF) {
3159     if (isCommutativeBinOp(Opcode)) {
3160       std::swap(N1, N2);
3161     } else {
3162       switch (Opcode) {
3163       case ISD::FP_ROUND_INREG:
3164       case ISD::SIGN_EXTEND_INREG:
3165       case ISD::SUB:
3166       case ISD::FSUB:
3167       case ISD::FDIV:
3168       case ISD::FREM:
3169       case ISD::SRA:
3170         return N1;     // fold op(undef, arg2) -> undef
3171       case ISD::UDIV:
3172       case ISD::SDIV:
3173       case ISD::UREM:
3174       case ISD::SREM:
3175       case ISD::SRL:
3176       case ISD::SHL:
3177         if (!VT.isVector())
3178           return getConstant(0, VT);    // fold op(undef, arg2) -> 0
3179         // For vectors, we can't easily build an all zero vector, just return
3180         // the LHS.
3181         return N2;
3182       }
3183     }
3184   }
3185
3186   // Fold a bunch of operators when the RHS is undef.
3187   if (N2.getOpcode() == ISD::UNDEF) {
3188     switch (Opcode) {
3189     case ISD::XOR:
3190       if (N1.getOpcode() == ISD::UNDEF)
3191         // Handle undef ^ undef -> 0 special case. This is a common
3192         // idiom (misuse).
3193         return getConstant(0, VT);
3194       // fallthrough
3195     case ISD::ADD:
3196     case ISD::ADDC:
3197     case ISD::ADDE:
3198     case ISD::SUB:
3199     case ISD::UDIV:
3200     case ISD::SDIV:
3201     case ISD::UREM:
3202     case ISD::SREM:
3203       return N2;       // fold op(arg1, undef) -> undef
3204     case ISD::FADD:
3205     case ISD::FSUB:
3206     case ISD::FMUL:
3207     case ISD::FDIV:
3208     case ISD::FREM:
3209       if (getTarget().Options.UnsafeFPMath)
3210         return N2;
3211       break;
3212     case ISD::MUL:
3213     case ISD::AND:
3214     case ISD::SRL:
3215     case ISD::SHL:
3216       if (!VT.isVector())
3217         return getConstant(0, VT);  // fold op(arg1, undef) -> 0
3218       // For vectors, we can't easily build an all zero vector, just return
3219       // the LHS.
3220       return N1;
3221     case ISD::OR:
3222       if (!VT.isVector())
3223         return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
3224       // For vectors, we can't easily build an all one vector, just return
3225       // the LHS.
3226       return N1;
3227     case ISD::SRA:
3228       return N1;
3229     }
3230   }
3231
3232   // Memoize this node if possible.
3233   SDNode *N;
3234   SDVTList VTs = getVTList(VT);
3235   if (VT != MVT::Glue) {
3236     SDValue Ops[] = { N1, N2 };
3237     FoldingSetNodeID ID;
3238     AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
3239     void *IP = 0;
3240     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3241       return SDValue(E, 0);
3242
3243     N = new (NodeAllocator) BinarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, N1, N2);
3244     CSEMap.InsertNode(N, IP);
3245   } else {
3246     N = new (NodeAllocator) BinarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, N1, N2);
3247   }
3248
3249   AllNodes.push_back(N);
3250 #ifndef NDEBUG
3251   VerifySDNode(N);
3252 #endif
3253   return SDValue(N, 0);
3254 }
3255
3256 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT,
3257                               SDValue N1, SDValue N2, SDValue N3) {
3258   // Perform various simplifications.
3259   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
3260   switch (Opcode) {
3261   case ISD::FMA: {
3262     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3263     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
3264     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
3265     if (N1CFP && N2CFP && N3CFP) {
3266       APFloat  V1 = N1CFP->getValueAPF();
3267       const APFloat &V2 = N2CFP->getValueAPF();
3268       const APFloat &V3 = N3CFP->getValueAPF();
3269       APFloat::opStatus s =
3270         V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
3271       if (s != APFloat::opInvalidOp)
3272         return getConstantFP(V1, VT);
3273     }
3274     break;
3275   }
3276   case ISD::CONCAT_VECTORS:
3277     // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
3278     // one big BUILD_VECTOR.
3279     if (N1.getOpcode() == ISD::BUILD_VECTOR &&
3280         N2.getOpcode() == ISD::BUILD_VECTOR &&
3281         N3.getOpcode() == ISD::BUILD_VECTOR) {
3282       SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(),
3283                                     N1.getNode()->op_end());
3284       Elts.append(N2.getNode()->op_begin(), N2.getNode()->op_end());
3285       Elts.append(N3.getNode()->op_begin(), N3.getNode()->op_end());
3286       return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
3287     }
3288     break;
3289   case ISD::SETCC: {
3290     // Use FoldSetCC to simplify SETCC's.
3291     SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL);
3292     if (Simp.getNode()) return Simp;
3293     break;
3294   }
3295   case ISD::SELECT:
3296     if (N1C) {
3297      if (N1C->getZExtValue())
3298        return N2;             // select true, X, Y -> X
3299      return N3;             // select false, X, Y -> Y
3300     }
3301
3302     if (N2 == N3) return N2;   // select C, X, X -> X
3303     break;
3304   case ISD::VECTOR_SHUFFLE:
3305     llvm_unreachable("should use getVectorShuffle constructor!");
3306   case ISD::INSERT_SUBVECTOR: {
3307     SDValue Index = N3;
3308     if (VT.isSimple() && N1.getValueType().isSimple()
3309         && N2.getValueType().isSimple()) {
3310       assert(VT.isVector() && N1.getValueType().isVector() &&
3311              N2.getValueType().isVector() &&
3312              "Insert subvector VTs must be a vectors");
3313       assert(VT == N1.getValueType() &&
3314              "Dest and insert subvector source types must match!");
3315       assert(N2.getValueType().getSimpleVT() <= N1.getValueType().getSimpleVT() &&
3316              "Insert subvector must be from smaller vector to larger vector!");
3317       if (isa<ConstantSDNode>(Index.getNode())) {
3318         assert((N2.getValueType().getVectorNumElements() +
3319                 cast<ConstantSDNode>(Index.getNode())->getZExtValue()
3320                 <= VT.getVectorNumElements())
3321                && "Insert subvector overflow!");
3322       }
3323
3324       // Trivial insertion.
3325       if (VT.getSimpleVT() == N2.getValueType().getSimpleVT())
3326         return N2;
3327     }
3328     break;
3329   }
3330   case ISD::BITCAST:
3331     // Fold bit_convert nodes from a type to themselves.
3332     if (N1.getValueType() == VT)
3333       return N1;
3334     break;
3335   }
3336
3337   // Memoize node if it doesn't produce a flag.
3338   SDNode *N;
3339   SDVTList VTs = getVTList(VT);
3340   if (VT != MVT::Glue) {
3341     SDValue Ops[] = { N1, N2, N3 };
3342     FoldingSetNodeID ID;
3343     AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3344     void *IP = 0;
3345     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3346       return SDValue(E, 0);
3347
3348     N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, N1, N2, N3);
3349     CSEMap.InsertNode(N, IP);
3350   } else {
3351     N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, N1, N2, N3);
3352   }
3353
3354   AllNodes.push_back(N);
3355 #ifndef NDEBUG
3356   VerifySDNode(N);
3357 #endif
3358   return SDValue(N, 0);
3359 }
3360
3361 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT,
3362                               SDValue N1, SDValue N2, SDValue N3,
3363                               SDValue N4) {
3364   SDValue Ops[] = { N1, N2, N3, N4 };
3365   return getNode(Opcode, DL, VT, Ops, 4);
3366 }
3367
3368 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT,
3369                               SDValue N1, SDValue N2, SDValue N3,
3370                               SDValue N4, SDValue N5) {
3371   SDValue Ops[] = { N1, N2, N3, N4, N5 };
3372   return getNode(Opcode, DL, VT, Ops, 5);
3373 }
3374
3375 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
3376 /// the incoming stack arguments to be loaded from the stack.
3377 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
3378   SmallVector<SDValue, 8> ArgChains;
3379
3380   // Include the original chain at the beginning of the list. When this is
3381   // used by target LowerCall hooks, this helps legalize find the
3382   // CALLSEQ_BEGIN node.
3383   ArgChains.push_back(Chain);
3384
3385   // Add a chain value for each stack argument.
3386   for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
3387        UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
3388     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3389       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3390         if (FI->getIndex() < 0)
3391           ArgChains.push_back(SDValue(L, 1));
3392
3393   // Build a tokenfactor for all the chains.
3394   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other,
3395                  &ArgChains[0], ArgChains.size());
3396 }
3397
3398 /// getMemsetValue - Vectorized representation of the memset value
3399 /// operand.
3400 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
3401                               SDLoc dl) {
3402   assert(Value.getOpcode() != ISD::UNDEF);
3403
3404   unsigned NumBits = VT.getScalarType().getSizeInBits();
3405   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3406     assert(C->getAPIntValue().getBitWidth() == 8);
3407     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
3408     if (VT.isInteger())
3409       return DAG.getConstant(Val, VT);
3410     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), VT);
3411   }
3412
3413   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Value);
3414   if (NumBits > 8) {
3415     // Use a multiplication with 0x010101... to extend the input to the
3416     // required length.
3417     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
3418     Value = DAG.getNode(ISD::MUL, dl, VT, Value, DAG.getConstant(Magic, VT));
3419   }
3420
3421   return Value;
3422 }
3423
3424 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3425 /// used when a memcpy is turned into a memset when the source is a constant
3426 /// string ptr.
3427 static SDValue getMemsetStringVal(EVT VT, SDLoc dl, SelectionDAG &DAG,
3428                                   const TargetLowering &TLI, StringRef Str) {
3429   // Handle vector with all elements zero.
3430   if (Str.empty()) {
3431     if (VT.isInteger())
3432       return DAG.getConstant(0, VT);
3433     else if (VT == MVT::f32 || VT == MVT::f64)
3434       return DAG.getConstantFP(0.0, VT);
3435     else if (VT.isVector()) {
3436       unsigned NumElts = VT.getVectorNumElements();
3437       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
3438       return DAG.getNode(ISD::BITCAST, dl, VT,
3439                          DAG.getConstant(0, EVT::getVectorVT(*DAG.getContext(),
3440                                                              EltVT, NumElts)));
3441     } else
3442       llvm_unreachable("Expected type!");
3443   }
3444
3445   assert(!VT.isVector() && "Can't handle vector type here!");
3446   unsigned NumVTBits = VT.getSizeInBits();
3447   unsigned NumVTBytes = NumVTBits / 8;
3448   unsigned NumBytes = std::min(NumVTBytes, unsigned(Str.size()));
3449
3450   APInt Val(NumVTBits, 0);
3451   if (TLI.isLittleEndian()) {
3452     for (unsigned i = 0; i != NumBytes; ++i)
3453       Val |= (uint64_t)(unsigned char)Str[i] << i*8;
3454   } else {
3455     for (unsigned i = 0; i != NumBytes; ++i)
3456       Val |= (uint64_t)(unsigned char)Str[i] << (NumVTBytes-i-1)*8;
3457   }
3458
3459   // If the "cost" of materializing the integer immediate is 1 or free, then
3460   // it is cost effective to turn the load into the immediate.
3461   const TargetTransformInfo *TTI = DAG.getTargetTransformInfo();
3462   if (TTI->getIntImmCost(Val, VT.getTypeForEVT(*DAG.getContext())) < 2)
3463     return DAG.getConstant(Val, VT);
3464   return SDValue(0, 0);
3465 }
3466
3467 /// getMemBasePlusOffset - Returns base and offset node for the
3468 ///
3469 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset, SDLoc dl,
3470                                       SelectionDAG &DAG) {
3471   EVT VT = Base.getValueType();
3472   return DAG.getNode(ISD::ADD, dl,
3473                      VT, Base, DAG.getConstant(Offset, VT));
3474 }
3475
3476 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
3477 ///
3478 static bool isMemSrcFromString(SDValue Src, StringRef &Str) {
3479   unsigned SrcDelta = 0;
3480   GlobalAddressSDNode *G = NULL;
3481   if (Src.getOpcode() == ISD::GlobalAddress)
3482     G = cast<GlobalAddressSDNode>(Src);
3483   else if (Src.getOpcode() == ISD::ADD &&
3484            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3485            Src.getOperand(1).getOpcode() == ISD::Constant) {
3486     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
3487     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
3488   }
3489   if (!G)
3490     return false;
3491
3492   return getConstantStringInfo(G->getGlobal(), Str, SrcDelta, false);
3493 }
3494
3495 /// FindOptimalMemOpLowering - Determines the optimial series memory ops
3496 /// to replace the memset / memcpy. Return true if the number of memory ops
3497 /// is below the threshold. It returns the types of the sequence of
3498 /// memory ops to perform memset / memcpy by reference.
3499 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps,
3500                                      unsigned Limit, uint64_t Size,
3501                                      unsigned DstAlign, unsigned SrcAlign,
3502                                      bool IsMemset,
3503                                      bool ZeroMemset,
3504                                      bool MemcpyStrSrc,
3505                                      bool AllowOverlap,
3506                                      SelectionDAG &DAG,
3507                                      const TargetLowering &TLI) {
3508   assert((SrcAlign == 0 || SrcAlign >= DstAlign) &&
3509          "Expecting memcpy / memset source to meet alignment requirement!");
3510   // If 'SrcAlign' is zero, that means the memory operation does not need to
3511   // load the value, i.e. memset or memcpy from constant string. Otherwise,
3512   // it's the inferred alignment of the source. 'DstAlign', on the other hand,
3513   // is the specified alignment of the memory operation. If it is zero, that
3514   // means it's possible to change the alignment of the destination.
3515   // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does
3516   // not need to be loaded.
3517   EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign,
3518                                    IsMemset, ZeroMemset, MemcpyStrSrc,
3519                                    DAG.getMachineFunction());
3520
3521   if (VT == MVT::Other) {
3522     if (DstAlign >= TLI.getDataLayout()->getPointerPrefAlignment() ||
3523         TLI.allowsUnalignedMemoryAccesses(VT)) {
3524       VT = TLI.getPointerTy();
3525     } else {
3526       switch (DstAlign & 7) {
3527       case 0:  VT = MVT::i64; break;
3528       case 4:  VT = MVT::i32; break;
3529       case 2:  VT = MVT::i16; break;
3530       default: VT = MVT::i8;  break;
3531       }
3532     }
3533
3534     MVT LVT = MVT::i64;
3535     while (!TLI.isTypeLegal(LVT))
3536       LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
3537     assert(LVT.isInteger());
3538
3539     if (VT.bitsGT(LVT))
3540       VT = LVT;
3541   }
3542
3543   unsigned NumMemOps = 0;
3544   while (Size != 0) {
3545     unsigned VTSize = VT.getSizeInBits() / 8;
3546     while (VTSize > Size) {
3547       // For now, only use non-vector load / store's for the left-over pieces.
3548       EVT NewVT = VT;
3549       unsigned NewVTSize;
3550
3551       bool Found = false;
3552       if (VT.isVector() || VT.isFloatingPoint()) {
3553         NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
3554         if (TLI.isOperationLegalOrCustom(ISD::STORE, NewVT) &&
3555             TLI.isSafeMemOpType(NewVT.getSimpleVT()))
3556           Found = true;
3557         else if (NewVT == MVT::i64 &&
3558                  TLI.isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
3559                  TLI.isSafeMemOpType(MVT::f64)) {
3560           // i64 is usually not legal on 32-bit targets, but f64 may be.
3561           NewVT = MVT::f64;
3562           Found = true;
3563         }
3564       }
3565
3566       if (!Found) {
3567         do {
3568           NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
3569           if (NewVT == MVT::i8)
3570             break;
3571         } while (!TLI.isSafeMemOpType(NewVT.getSimpleVT()));
3572       }
3573       NewVTSize = NewVT.getSizeInBits() / 8;
3574
3575       // If the new VT cannot cover all of the remaining bits, then consider
3576       // issuing a (or a pair of) unaligned and overlapping load / store.
3577       // FIXME: Only does this for 64-bit or more since we don't have proper
3578       // cost model for unaligned load / store.
3579       bool Fast;
3580       if (NumMemOps && AllowOverlap &&
3581           VTSize >= 8 && NewVTSize < Size &&
3582           TLI.allowsUnalignedMemoryAccesses(VT, &Fast) && Fast)
3583         VTSize = Size;
3584       else {
3585         VT = NewVT;
3586         VTSize = NewVTSize;
3587       }
3588     }
3589
3590     if (++NumMemOps > Limit)
3591       return false;
3592
3593     MemOps.push_back(VT);
3594     Size -= VTSize;
3595   }
3596
3597   return true;
3598 }
3599
3600 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, SDLoc dl,
3601                                        SDValue Chain, SDValue Dst,
3602                                        SDValue Src, uint64_t Size,
3603                                        unsigned Align, bool isVol,
3604                                        bool AlwaysInline,
3605                                        MachinePointerInfo DstPtrInfo,
3606                                        MachinePointerInfo SrcPtrInfo) {
3607   // Turn a memcpy of undef to nop.
3608   if (Src.getOpcode() == ISD::UNDEF)
3609     return Chain;
3610
3611   // Expand memcpy to a series of load and store ops if the size operand falls
3612   // below a certain threshold.
3613   // TODO: In the AlwaysInline case, if the size is big then generate a loop
3614   // rather than maybe a humongous number of loads and stores.
3615   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3616   std::vector<EVT> MemOps;
3617   bool DstAlignCanChange = false;
3618   MachineFunction &MF = DAG.getMachineFunction();
3619   MachineFrameInfo *MFI = MF.getFrameInfo();
3620   bool OptSize =
3621     MF.getFunction()->getAttributes().
3622       hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
3623   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
3624   if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
3625     DstAlignCanChange = true;
3626   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
3627   if (Align > SrcAlign)
3628     SrcAlign = Align;
3629   StringRef Str;
3630   bool CopyFromStr = isMemSrcFromString(Src, Str);
3631   bool isZeroStr = CopyFromStr && Str.empty();
3632   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
3633
3634   if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
3635                                 (DstAlignCanChange ? 0 : Align),
3636                                 (isZeroStr ? 0 : SrcAlign),
3637                                 false, false, CopyFromStr, true, DAG, TLI))
3638     return SDValue();
3639
3640   if (DstAlignCanChange) {
3641     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
3642     unsigned NewAlign = (unsigned) TLI.getDataLayout()->getABITypeAlignment(Ty);
3643
3644     // Don't promote to an alignment that would require dynamic stack
3645     // realignment.
3646     const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
3647     if (!TRI->needsStackRealignment(MF))
3648        while (NewAlign > Align &&
3649              TLI.getDataLayout()->exceedsNaturalStackAlignment(NewAlign))
3650           NewAlign /= 2;
3651
3652     if (NewAlign > Align) {
3653       // Give the stack frame object a larger alignment if needed.
3654       if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
3655         MFI->setObjectAlignment(FI->getIndex(), NewAlign);
3656       Align = NewAlign;
3657     }
3658   }
3659
3660   SmallVector<SDValue, 8> OutChains;
3661   unsigned NumMemOps = MemOps.size();
3662   uint64_t SrcOff = 0, DstOff = 0;
3663   for (unsigned i = 0; i != NumMemOps; ++i) {
3664     EVT VT = MemOps[i];
3665     unsigned VTSize = VT.getSizeInBits() / 8;
3666     SDValue Value, Store;
3667
3668     if (VTSize > Size) {
3669       // Issuing an unaligned load / store pair  that overlaps with the previous
3670       // pair. Adjust the offset accordingly.
3671       assert(i == NumMemOps-1 && i != 0);
3672       SrcOff -= VTSize - Size;
3673       DstOff -= VTSize - Size;
3674     }
3675
3676     if (CopyFromStr &&
3677         (isZeroStr || (VT.isInteger() && !VT.isVector()))) {
3678       // It's unlikely a store of a vector immediate can be done in a single
3679       // instruction. It would require a load from a constantpool first.
3680       // We only handle zero vectors here.
3681       // FIXME: Handle other cases where store of vector immediate is done in
3682       // a single instruction.
3683       Value = getMemsetStringVal(VT, dl, DAG, TLI, Str.substr(SrcOff));
3684       if (Value.getNode())
3685         Store = DAG.getStore(Chain, dl, Value,
3686                              getMemBasePlusOffset(Dst, DstOff, dl, DAG),
3687                              DstPtrInfo.getWithOffset(DstOff), isVol,
3688                              false, Align);
3689     }
3690
3691     if (!Store.getNode()) {
3692       // The type might not be legal for the target.  This should only happen
3693       // if the type is smaller than a legal type, as on PPC, so the right
3694       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
3695       // to Load/Store if NVT==VT.
3696       // FIXME does the case above also need this?
3697       EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
3698       assert(NVT.bitsGE(VT));
3699       Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
3700                              getMemBasePlusOffset(Src, SrcOff, dl, DAG),
3701                              SrcPtrInfo.getWithOffset(SrcOff), VT, isVol, false,
3702                              MinAlign(SrcAlign, SrcOff));
3703       Store = DAG.getTruncStore(Chain, dl, Value,
3704                                 getMemBasePlusOffset(Dst, DstOff, dl, DAG),
3705                                 DstPtrInfo.getWithOffset(DstOff), VT, isVol,
3706                                 false, Align);
3707     }
3708     OutChains.push_back(Store);
3709     SrcOff += VTSize;
3710     DstOff += VTSize;
3711     Size -= VTSize;
3712   }
3713
3714   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3715                      &OutChains[0], OutChains.size());
3716 }
3717
3718 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, SDLoc dl,
3719                                         SDValue Chain, SDValue Dst,
3720                                         SDValue Src, uint64_t Size,
3721                                         unsigned Align,  bool isVol,
3722                                         bool AlwaysInline,
3723                                         MachinePointerInfo DstPtrInfo,
3724                                         MachinePointerInfo SrcPtrInfo) {
3725   // Turn a memmove of undef to nop.
3726   if (Src.getOpcode() == ISD::UNDEF)
3727     return Chain;
3728
3729   // Expand memmove to a series of load and store ops if the size operand falls
3730   // below a certain threshold.
3731   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3732   std::vector<EVT> MemOps;
3733   bool DstAlignCanChange = false;
3734   MachineFunction &MF = DAG.getMachineFunction();
3735   MachineFrameInfo *MFI = MF.getFrameInfo();
3736   bool OptSize = MF.getFunction()->getAttributes().
3737     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
3738   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
3739   if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
3740     DstAlignCanChange = true;
3741   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
3742   if (Align > SrcAlign)
3743     SrcAlign = Align;
3744   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
3745
3746   if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
3747                                 (DstAlignCanChange ? 0 : Align), SrcAlign,
3748                                 false, false, false, false, DAG, TLI))
3749     return SDValue();
3750
3751   if (DstAlignCanChange) {
3752     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
3753     unsigned NewAlign = (unsigned) TLI.getDataLayout()->getABITypeAlignment(Ty);
3754     if (NewAlign > Align) {
3755       // Give the stack frame object a larger alignment if needed.
3756       if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
3757         MFI->setObjectAlignment(FI->getIndex(), NewAlign);
3758       Align = NewAlign;
3759     }
3760   }
3761
3762   uint64_t SrcOff = 0, DstOff = 0;
3763   SmallVector<SDValue, 8> LoadValues;
3764   SmallVector<SDValue, 8> LoadChains;
3765   SmallVector<SDValue, 8> OutChains;
3766   unsigned NumMemOps = MemOps.size();
3767   for (unsigned i = 0; i < NumMemOps; i++) {
3768     EVT VT = MemOps[i];
3769     unsigned VTSize = VT.getSizeInBits() / 8;
3770     SDValue Value, Store;
3771
3772     Value = DAG.getLoad(VT, dl, Chain,
3773                         getMemBasePlusOffset(Src, SrcOff, dl, DAG),
3774                         SrcPtrInfo.getWithOffset(SrcOff), isVol,
3775                         false, false, SrcAlign);
3776     LoadValues.push_back(Value);
3777     LoadChains.push_back(Value.getValue(1));
3778     SrcOff += VTSize;
3779   }
3780   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3781                       &LoadChains[0], LoadChains.size());
3782   OutChains.clear();
3783   for (unsigned i = 0; i < NumMemOps; i++) {
3784     EVT VT = MemOps[i];
3785     unsigned VTSize = VT.getSizeInBits() / 8;
3786     SDValue Value, Store;
3787
3788     Store = DAG.getStore(Chain, dl, LoadValues[i],
3789                          getMemBasePlusOffset(Dst, DstOff, dl, DAG),
3790                          DstPtrInfo.getWithOffset(DstOff), isVol, false, Align);
3791     OutChains.push_back(Store);
3792     DstOff += VTSize;
3793   }
3794
3795   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3796                      &OutChains[0], OutChains.size());
3797 }
3798
3799 static SDValue getMemsetStores(SelectionDAG &DAG, SDLoc dl,
3800                                SDValue Chain, SDValue Dst,
3801                                SDValue Src, uint64_t Size,
3802                                unsigned Align, bool isVol,
3803                                MachinePointerInfo DstPtrInfo) {
3804   // Turn a memset of undef to nop.
3805   if (Src.getOpcode() == ISD::UNDEF)
3806     return Chain;
3807
3808   // Expand memset to a series of load/store ops if the size operand
3809   // falls below a certain threshold.
3810   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3811   std::vector<EVT> MemOps;
3812   bool DstAlignCanChange = false;
3813   MachineFunction &MF = DAG.getMachineFunction();
3814   MachineFrameInfo *MFI = MF.getFrameInfo();
3815   bool OptSize = MF.getFunction()->getAttributes().
3816     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
3817   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
3818   if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
3819     DstAlignCanChange = true;
3820   bool IsZeroVal =
3821     isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
3822   if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize),
3823                                 Size, (DstAlignCanChange ? 0 : Align), 0,
3824                                 true, IsZeroVal, false, true, DAG, TLI))
3825     return SDValue();
3826
3827   if (DstAlignCanChange) {
3828     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
3829     unsigned NewAlign = (unsigned) TLI.getDataLayout()->getABITypeAlignment(Ty);
3830     if (NewAlign > Align) {
3831       // Give the stack frame object a larger alignment if needed.
3832       if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
3833         MFI->setObjectAlignment(FI->getIndex(), NewAlign);
3834       Align = NewAlign;
3835     }
3836   }
3837
3838   SmallVector<SDValue, 8> OutChains;
3839   uint64_t DstOff = 0;
3840   unsigned NumMemOps = MemOps.size();
3841
3842   // Find the largest store and generate the bit pattern for it.
3843   EVT LargestVT = MemOps[0];
3844   for (unsigned i = 1; i < NumMemOps; i++)
3845     if (MemOps[i].bitsGT(LargestVT))
3846       LargestVT = MemOps[i];
3847   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
3848
3849   for (unsigned i = 0; i < NumMemOps; i++) {
3850     EVT VT = MemOps[i];
3851     unsigned VTSize = VT.getSizeInBits() / 8;
3852     if (VTSize > Size) {
3853       // Issuing an unaligned load / store pair  that overlaps with the previous
3854       // pair. Adjust the offset accordingly.
3855       assert(i == NumMemOps-1 && i != 0);
3856       DstOff -= VTSize - Size;
3857     }
3858
3859     // If this store is smaller than the largest store see whether we can get
3860     // the smaller value for free with a truncate.
3861     SDValue Value = MemSetValue;
3862     if (VT.bitsLT(LargestVT)) {
3863       if (!LargestVT.isVector() && !VT.isVector() &&
3864           TLI.isTruncateFree(LargestVT, VT))
3865         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
3866       else
3867         Value = getMemsetValue(Src, VT, DAG, dl);
3868     }
3869     assert(Value.getValueType() == VT && "Value with wrong type.");
3870     SDValue Store = DAG.getStore(Chain, dl, Value,
3871                                  getMemBasePlusOffset(Dst, DstOff, dl, DAG),
3872                                  DstPtrInfo.getWithOffset(DstOff),
3873                                  isVol, false, Align);
3874     OutChains.push_back(Store);
3875     DstOff += VT.getSizeInBits() / 8;
3876     Size -= VTSize;
3877   }
3878
3879   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3880                      &OutChains[0], OutChains.size());
3881 }
3882
3883 SDValue SelectionDAG::getMemcpy(SDValue Chain, SDLoc dl, SDValue Dst,
3884                                 SDValue Src, SDValue Size,
3885                                 unsigned Align, bool isVol, bool AlwaysInline,
3886                                 MachinePointerInfo DstPtrInfo,
3887                                 MachinePointerInfo SrcPtrInfo) {
3888   assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
3889
3890   // Check to see if we should lower the memcpy to loads and stores first.
3891   // For cases within the target-specified limits, this is the best choice.
3892   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3893   if (ConstantSize) {
3894     // Memcpy with size zero? Just return the original chain.
3895     if (ConstantSize->isNullValue())
3896       return Chain;
3897
3898     SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3899                                              ConstantSize->getZExtValue(),Align,
3900                                 isVol, false, DstPtrInfo, SrcPtrInfo);
3901     if (Result.getNode())
3902       return Result;
3903   }
3904
3905   // Then check to see if we should lower the memcpy with target-specific
3906   // code. If the target chooses to do this, this is the next best.
3907   SDValue Result =
3908     TSI.EmitTargetCodeForMemcpy(*this, dl, Chain, Dst, Src, Size, Align,
3909                                 isVol, AlwaysInline,
3910                                 DstPtrInfo, SrcPtrInfo);
3911   if (Result.getNode())
3912     return Result;
3913
3914   // If we really need inline code and the target declined to provide it,
3915   // use a (potentially long) sequence of loads and stores.
3916   if (AlwaysInline) {
3917     assert(ConstantSize && "AlwaysInline requires a constant size!");
3918     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3919                                    ConstantSize->getZExtValue(), Align, isVol,
3920                                    true, DstPtrInfo, SrcPtrInfo);
3921   }
3922
3923   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
3924   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
3925   // respect volatile, so they may do things like read or write memory
3926   // beyond the given memory regions. But fixing this isn't easy, and most
3927   // people don't care.
3928
3929   const TargetLowering *TLI = TM.getTargetLowering();
3930
3931   // Emit a library call.
3932   TargetLowering::ArgListTy Args;
3933   TargetLowering::ArgListEntry Entry;
3934   Entry.Ty = TLI->getDataLayout()->getIntPtrType(*getContext());
3935   Entry.Node = Dst; Args.push_back(Entry);
3936   Entry.Node = Src; Args.push_back(Entry);
3937   Entry.Node = Size; Args.push_back(Entry);
3938   // FIXME: pass in SDLoc
3939   TargetLowering::
3940   CallLoweringInfo CLI(Chain, Type::getVoidTy(*getContext()),
3941                     false, false, false, false, 0,
3942                     TLI->getLibcallCallingConv(RTLIB::MEMCPY),
3943                     /*isTailCall=*/false,
3944                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/false,
3945                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
3946                                       TLI->getPointerTy()),
3947                     Args, *this, dl);
3948   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
3949
3950   return CallResult.second;
3951 }
3952
3953 SDValue SelectionDAG::getMemmove(SDValue Chain, SDLoc dl, SDValue Dst,
3954                                  SDValue Src, SDValue Size,
3955                                  unsigned Align, bool isVol,
3956                                  MachinePointerInfo DstPtrInfo,
3957                                  MachinePointerInfo SrcPtrInfo) {
3958   assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
3959
3960   // Check to see if we should lower the memmove to loads and stores first.
3961   // For cases within the target-specified limits, this is the best choice.
3962   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3963   if (ConstantSize) {
3964     // Memmove with size zero? Just return the original chain.
3965     if (ConstantSize->isNullValue())
3966       return Chain;
3967
3968     SDValue Result =
3969       getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
3970                                ConstantSize->getZExtValue(), Align, isVol,
3971                                false, DstPtrInfo, SrcPtrInfo);
3972     if (Result.getNode())
3973       return Result;
3974   }
3975
3976   // Then check to see if we should lower the memmove with target-specific
3977   // code. If the target chooses to do this, this is the next best.
3978   SDValue Result =
3979     TSI.EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, Align, isVol,
3980                                  DstPtrInfo, SrcPtrInfo);
3981   if (Result.getNode())
3982     return Result;
3983
3984   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
3985   // not be safe.  See memcpy above for more details.
3986
3987   const TargetLowering *TLI = TM.getTargetLowering();
3988
3989   // Emit a library call.
3990   TargetLowering::ArgListTy Args;
3991   TargetLowering::ArgListEntry Entry;
3992   Entry.Ty = TLI->getDataLayout()->getIntPtrType(*getContext());
3993   Entry.Node = Dst; Args.push_back(Entry);
3994   Entry.Node = Src; Args.push_back(Entry);
3995   Entry.Node = Size; Args.push_back(Entry);
3996   // FIXME:  pass in SDLoc
3997   TargetLowering::
3998   CallLoweringInfo CLI(Chain, Type::getVoidTy(*getContext()),
3999                     false, false, false, false, 0,
4000                     TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
4001                     /*isTailCall=*/false,
4002                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/false,
4003                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
4004                                       TLI->getPointerTy()),
4005                     Args, *this, dl);
4006   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
4007
4008   return CallResult.second;
4009 }
4010
4011 SDValue SelectionDAG::getMemset(SDValue Chain, SDLoc dl, SDValue Dst,
4012                                 SDValue Src, SDValue Size,
4013                                 unsigned Align, bool isVol,
4014                                 MachinePointerInfo DstPtrInfo) {
4015   assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
4016
4017   // Check to see if we should lower the memset to stores first.
4018   // For cases within the target-specified limits, this is the best choice.
4019   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4020   if (ConstantSize) {
4021     // Memset with size zero? Just return the original chain.
4022     if (ConstantSize->isNullValue())
4023       return Chain;
4024
4025     SDValue Result =
4026       getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
4027                       Align, isVol, DstPtrInfo);
4028
4029     if (Result.getNode())
4030       return Result;
4031   }
4032
4033   // Then check to see if we should lower the memset with target-specific
4034   // code. If the target chooses to do this, this is the next best.
4035   SDValue Result =
4036     TSI.EmitTargetCodeForMemset(*this, dl, Chain, Dst, Src, Size, Align, isVol,
4037                                 DstPtrInfo);
4038   if (Result.getNode())
4039     return Result;
4040
4041   // Emit a library call.
4042   const TargetLowering *TLI = TM.getTargetLowering();
4043   Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(*getContext());
4044   TargetLowering::ArgListTy Args;
4045   TargetLowering::ArgListEntry Entry;
4046   Entry.Node = Dst; Entry.Ty = IntPtrTy;
4047   Args.push_back(Entry);
4048   // Extend or truncate the argument to be an i32 value for the call.
4049   if (Src.getValueType().bitsGT(MVT::i32))
4050     Src = getNode(ISD::TRUNCATE, dl, MVT::i32, Src);
4051   else
4052     Src = getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Src);
4053   Entry.Node = Src;
4054   Entry.Ty = Type::getInt32Ty(*getContext());
4055   Entry.isSExt = true;
4056   Args.push_back(Entry);
4057   Entry.Node = Size;
4058   Entry.Ty = IntPtrTy;
4059   Entry.isSExt = false;
4060   Args.push_back(Entry);
4061   // FIXME: pass in SDLoc
4062   TargetLowering::
4063   CallLoweringInfo CLI(Chain, Type::getVoidTy(*getContext()),
4064                     false, false, false, false, 0,
4065                     TLI->getLibcallCallingConv(RTLIB::MEMSET),
4066                     /*isTailCall=*/false,
4067                     /*doesNotReturn*/false, /*isReturnValueUsed=*/false,
4068                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
4069                                       TLI->getPointerTy()),
4070                     Args, *this, dl);
4071   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
4072
4073   return CallResult.second;
4074 }
4075
4076 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4077                                 SDValue Chain, SDValue Ptr, SDValue Cmp,
4078                                 SDValue Swp, MachinePointerInfo PtrInfo,
4079                                 unsigned Alignment,
4080                                 AtomicOrdering Ordering,
4081                                 SynchronizationScope SynchScope) {
4082   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
4083     Alignment = getEVTAlignment(MemVT);
4084
4085   MachineFunction &MF = getMachineFunction();
4086
4087   // All atomics are load and store, except for ATMOIC_LOAD and ATOMIC_STORE.
4088   // For now, atomics are considered to be volatile always.
4089   // FIXME: Volatile isn't really correct; we should keep track of atomic
4090   // orderings in the memoperand.
4091   unsigned Flags = MachineMemOperand::MOVolatile;
4092   if (Opcode != ISD::ATOMIC_STORE)
4093     Flags |= MachineMemOperand::MOLoad;
4094   if (Opcode != ISD::ATOMIC_LOAD)
4095     Flags |= MachineMemOperand::MOStore;
4096
4097   MachineMemOperand *MMO =
4098     MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment);
4099
4100   return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Cmp, Swp, MMO,
4101                    Ordering, SynchScope);
4102 }
4103
4104 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4105                                 SDValue Chain,
4106                                 SDValue Ptr, SDValue Cmp,
4107                                 SDValue Swp, MachineMemOperand *MMO,
4108                                 AtomicOrdering Ordering,
4109                                 SynchronizationScope SynchScope) {
4110   assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
4111   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
4112
4113   EVT VT = Cmp.getValueType();
4114
4115   SDVTList VTs = getVTList(VT, MVT::Other);
4116   FoldingSetNodeID ID;
4117   ID.AddInteger(MemVT.getRawBits());
4118   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
4119   AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
4120   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4121   void* IP = 0;
4122   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4123     cast<AtomicSDNode>(E)->refineAlignment(MMO);
4124     return SDValue(E, 0);
4125   }
4126   SDNode *N = new (NodeAllocator) AtomicSDNode(Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, MemVT, Chain,
4127                                                Ptr, Cmp, Swp, MMO, Ordering,
4128                                                SynchScope);
4129   CSEMap.InsertNode(N, IP);
4130   AllNodes.push_back(N);
4131   return SDValue(N, 0);
4132 }
4133
4134 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4135                                 SDValue Chain,
4136                                 SDValue Ptr, SDValue Val,
4137                                 const Value* PtrVal,
4138                                 unsigned Alignment,
4139                                 AtomicOrdering Ordering,
4140                                 SynchronizationScope SynchScope) {
4141   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
4142     Alignment = getEVTAlignment(MemVT);
4143
4144   MachineFunction &MF = getMachineFunction();
4145   // An atomic store does not load. An atomic load does not store.
4146   // (An atomicrmw obviously both loads and stores.)
4147   // For now, atomics are considered to be volatile always, and they are
4148   // chained as such.
4149   // FIXME: Volatile isn't really correct; we should keep track of atomic
4150   // orderings in the memoperand.
4151   unsigned Flags = MachineMemOperand::MOVolatile;
4152   if (Opcode != ISD::ATOMIC_STORE)
4153     Flags |= MachineMemOperand::MOLoad;
4154   if (Opcode != ISD::ATOMIC_LOAD)
4155     Flags |= MachineMemOperand::MOStore;
4156
4157   MachineMemOperand *MMO =
4158     MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags,
4159                             MemVT.getStoreSize(), Alignment);
4160
4161   return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO,
4162                    Ordering, SynchScope);
4163 }
4164
4165 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4166                                 SDValue Chain,
4167                                 SDValue Ptr, SDValue Val,
4168                                 MachineMemOperand *MMO,
4169                                 AtomicOrdering Ordering,
4170                                 SynchronizationScope SynchScope) {
4171   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
4172           Opcode == ISD::ATOMIC_LOAD_SUB ||
4173           Opcode == ISD::ATOMIC_LOAD_AND ||
4174           Opcode == ISD::ATOMIC_LOAD_OR ||
4175           Opcode == ISD::ATOMIC_LOAD_XOR ||
4176           Opcode == ISD::ATOMIC_LOAD_NAND ||
4177           Opcode == ISD::ATOMIC_LOAD_MIN ||
4178           Opcode == ISD::ATOMIC_LOAD_MAX ||
4179           Opcode == ISD::ATOMIC_LOAD_UMIN ||
4180           Opcode == ISD::ATOMIC_LOAD_UMAX ||
4181           Opcode == ISD::ATOMIC_SWAP ||
4182           Opcode == ISD::ATOMIC_STORE) &&
4183          "Invalid Atomic Op");
4184
4185   EVT VT = Val.getValueType();
4186
4187   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
4188                                                getVTList(VT, MVT::Other);
4189   FoldingSetNodeID ID;
4190   ID.AddInteger(MemVT.getRawBits());
4191   SDValue Ops[] = {Chain, Ptr, Val};
4192   AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
4193   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4194   void* IP = 0;
4195   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4196     cast<AtomicSDNode>(E)->refineAlignment(MMO);
4197     return SDValue(E, 0);
4198   }
4199   SDNode *N = new (NodeAllocator) AtomicSDNode(Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, MemVT, Chain,
4200                                                Ptr, Val, MMO,
4201                                                Ordering, SynchScope);
4202   CSEMap.InsertNode(N, IP);
4203   AllNodes.push_back(N);
4204   return SDValue(N, 0);
4205 }
4206
4207 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4208                                 EVT VT, SDValue Chain,
4209                                 SDValue Ptr,
4210                                 const Value* PtrVal,
4211                                 unsigned Alignment,
4212                                 AtomicOrdering Ordering,
4213                                 SynchronizationScope SynchScope) {
4214   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
4215     Alignment = getEVTAlignment(MemVT);
4216
4217   MachineFunction &MF = getMachineFunction();
4218   // An atomic store does not load. An atomic load does not store.
4219   // (An atomicrmw obviously both loads and stores.)
4220   // For now, atomics are considered to be volatile always, and they are
4221   // chained as such.
4222   // FIXME: Volatile isn't really correct; we should keep track of atomic
4223   // orderings in the memoperand.
4224   unsigned Flags = MachineMemOperand::MOVolatile;
4225   if (Opcode != ISD::ATOMIC_STORE)
4226     Flags |= MachineMemOperand::MOLoad;
4227   if (Opcode != ISD::ATOMIC_LOAD)
4228     Flags |= MachineMemOperand::MOStore;
4229
4230   MachineMemOperand *MMO =
4231     MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags,
4232                             MemVT.getStoreSize(), Alignment);
4233
4234   return getAtomic(Opcode, dl, MemVT, VT, Chain, Ptr, MMO,
4235                    Ordering, SynchScope);
4236 }
4237
4238 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4239                                 EVT VT, SDValue Chain,
4240                                 SDValue Ptr,
4241                                 MachineMemOperand *MMO,
4242                                 AtomicOrdering Ordering,
4243                                 SynchronizationScope SynchScope) {
4244   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
4245
4246   SDVTList VTs = getVTList(VT, MVT::Other);
4247   FoldingSetNodeID ID;
4248   ID.AddInteger(MemVT.getRawBits());
4249   SDValue Ops[] = {Chain, Ptr};
4250   AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
4251   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4252   void* IP = 0;
4253   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4254     cast<AtomicSDNode>(E)->refineAlignment(MMO);
4255     return SDValue(E, 0);
4256   }
4257   SDNode *N = new (NodeAllocator) AtomicSDNode(Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, MemVT, Chain,
4258                                                Ptr, MMO, Ordering, SynchScope);
4259   CSEMap.InsertNode(N, IP);
4260   AllNodes.push_back(N);
4261   return SDValue(N, 0);
4262 }
4263
4264 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
4265 SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps,
4266                                      SDLoc dl) {
4267   if (NumOps == 1)
4268     return Ops[0];
4269
4270   SmallVector<EVT, 4> VTs;
4271   VTs.reserve(NumOps);
4272   for (unsigned i = 0; i < NumOps; ++i)
4273     VTs.push_back(Ops[i].getValueType());
4274   return getNode(ISD::MERGE_VALUES, dl, getVTList(&VTs[0], NumOps),
4275                  Ops, NumOps);
4276 }
4277
4278 SDValue
4279 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, SDLoc dl,
4280                                   const EVT *VTs, unsigned NumVTs,
4281                                   const SDValue *Ops, unsigned NumOps,
4282                                   EVT MemVT, MachinePointerInfo PtrInfo,
4283                                   unsigned Align, bool Vol,
4284                                   bool ReadMem, bool WriteMem) {
4285   return getMemIntrinsicNode(Opcode, dl, makeVTList(VTs, NumVTs), Ops, NumOps,
4286                              MemVT, PtrInfo, Align, Vol,
4287                              ReadMem, WriteMem);
4288 }
4289
4290 SDValue
4291 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, SDLoc dl, SDVTList VTList,
4292                                   const SDValue *Ops, unsigned NumOps,
4293                                   EVT MemVT, MachinePointerInfo PtrInfo,
4294                                   unsigned Align, bool Vol,
4295                                   bool ReadMem, bool WriteMem) {
4296   if (Align == 0)  // Ensure that codegen never sees alignment 0
4297     Align = getEVTAlignment(MemVT);
4298
4299   MachineFunction &MF = getMachineFunction();
4300   unsigned Flags = 0;
4301   if (WriteMem)
4302     Flags |= MachineMemOperand::MOStore;
4303   if (ReadMem)
4304     Flags |= MachineMemOperand::MOLoad;
4305   if (Vol)
4306     Flags |= MachineMemOperand::MOVolatile;
4307   MachineMemOperand *MMO =
4308     MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Align);
4309
4310   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
4311 }
4312
4313 SDValue
4314 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, SDLoc dl, SDVTList VTList,
4315                                   const SDValue *Ops, unsigned NumOps,
4316                                   EVT MemVT, MachineMemOperand *MMO) {
4317   assert((Opcode == ISD::INTRINSIC_VOID ||
4318           Opcode == ISD::INTRINSIC_W_CHAIN ||
4319           Opcode == ISD::PREFETCH ||
4320           Opcode == ISD::LIFETIME_START ||
4321           Opcode == ISD::LIFETIME_END ||
4322           (Opcode <= INT_MAX &&
4323            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
4324          "Opcode is not a memory-accessing opcode!");
4325
4326   // Memoize the node unless it returns a flag.
4327   MemIntrinsicSDNode *N;
4328   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
4329     FoldingSetNodeID ID;
4330     AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4331     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4332     void *IP = 0;
4333     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4334       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
4335       return SDValue(E, 0);
4336     }
4337
4338     N = new (NodeAllocator) MemIntrinsicSDNode(Opcode, dl.getIROrder(), dl.getDebugLoc(), VTList, Ops, NumOps,
4339                                                MemVT, MMO);
4340     CSEMap.InsertNode(N, IP);
4341   } else {
4342     N = new (NodeAllocator) MemIntrinsicSDNode(Opcode, dl.getIROrder(), dl.getDebugLoc(), VTList, Ops, NumOps,
4343                                                MemVT, MMO);
4344   }
4345   AllNodes.push_back(N);
4346   return SDValue(N, 0);
4347 }
4348
4349 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
4350 /// MachinePointerInfo record from it.  This is particularly useful because the
4351 /// code generator has many cases where it doesn't bother passing in a
4352 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
4353 static MachinePointerInfo InferPointerInfo(SDValue Ptr, int64_t Offset = 0) {
4354   // If this is FI+Offset, we can model it.
4355   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
4356     return MachinePointerInfo::getFixedStack(FI->getIndex(), Offset);
4357
4358   // If this is (FI+Offset1)+Offset2, we can model it.
4359   if (Ptr.getOpcode() != ISD::ADD ||
4360       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
4361       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
4362     return MachinePointerInfo();
4363
4364   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4365   return MachinePointerInfo::getFixedStack(FI, Offset+
4366                        cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
4367 }
4368
4369 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
4370 /// MachinePointerInfo record from it.  This is particularly useful because the
4371 /// code generator has many cases where it doesn't bother passing in a
4372 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
4373 static MachinePointerInfo InferPointerInfo(SDValue Ptr, SDValue OffsetOp) {
4374   // If the 'Offset' value isn't a constant, we can't handle this.
4375   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
4376     return InferPointerInfo(Ptr, OffsetNode->getSExtValue());
4377   if (OffsetOp.getOpcode() == ISD::UNDEF)
4378     return InferPointerInfo(Ptr);
4379   return MachinePointerInfo();
4380 }
4381
4382
4383 SDValue
4384 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
4385                       EVT VT, SDLoc dl, SDValue Chain,
4386                       SDValue Ptr, SDValue Offset,
4387                       MachinePointerInfo PtrInfo, EVT MemVT,
4388                       bool isVolatile, bool isNonTemporal, bool isInvariant,
4389                       unsigned Alignment, const MDNode *TBAAInfo,
4390                       const MDNode *Ranges) {
4391   assert(Chain.getValueType() == MVT::Other &&
4392         "Invalid chain type");
4393   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
4394     Alignment = getEVTAlignment(VT);
4395
4396   unsigned Flags = MachineMemOperand::MOLoad;
4397   if (isVolatile)
4398     Flags |= MachineMemOperand::MOVolatile;
4399   if (isNonTemporal)
4400     Flags |= MachineMemOperand::MONonTemporal;
4401   if (isInvariant)
4402     Flags |= MachineMemOperand::MOInvariant;
4403
4404   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
4405   // clients.
4406   if (PtrInfo.V == 0)
4407     PtrInfo = InferPointerInfo(Ptr, Offset);
4408
4409   MachineFunction &MF = getMachineFunction();
4410   MachineMemOperand *MMO =
4411     MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment,
4412                             TBAAInfo, Ranges);
4413   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
4414 }
4415
4416 SDValue
4417 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
4418                       EVT VT, SDLoc dl, SDValue Chain,
4419                       SDValue Ptr, SDValue Offset, EVT MemVT,
4420                       MachineMemOperand *MMO) {
4421   if (VT == MemVT) {
4422     ExtType = ISD::NON_EXTLOAD;
4423   } else if (ExtType == ISD::NON_EXTLOAD) {
4424     assert(VT == MemVT && "Non-extending load from different memory type!");
4425   } else {
4426     // Extending load.
4427     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
4428            "Should only be an extending load, not truncating!");
4429     assert(VT.isInteger() == MemVT.isInteger() &&
4430            "Cannot convert from FP to Int or Int -> FP!");
4431     assert(VT.isVector() == MemVT.isVector() &&
4432            "Cannot use trunc store to convert to or from a vector!");
4433     assert((!VT.isVector() ||
4434             VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
4435            "Cannot use trunc store to change the number of vector elements!");
4436   }
4437
4438   bool Indexed = AM != ISD::UNINDEXED;
4439   assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
4440          "Unindexed load with an offset!");
4441
4442   SDVTList VTs = Indexed ?
4443     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
4444   SDValue Ops[] = { Chain, Ptr, Offset };
4445   FoldingSetNodeID ID;
4446   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
4447   ID.AddInteger(MemVT.getRawBits());
4448   ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, MMO->isVolatile(),
4449                                      MMO->isNonTemporal(),
4450                                      MMO->isInvariant()));
4451   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4452   void *IP = 0;
4453   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4454     cast<LoadSDNode>(E)->refineAlignment(MMO);
4455     return SDValue(E, 0);
4456   }
4457   SDNode *N = new (NodeAllocator) LoadSDNode(Ops, dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ExtType,
4458                                              MemVT, MMO);
4459   CSEMap.InsertNode(N, IP);
4460   AllNodes.push_back(N);
4461   return SDValue(N, 0);
4462 }
4463
4464 SDValue SelectionDAG::getLoad(EVT VT, SDLoc dl,
4465                               SDValue Chain, SDValue Ptr,
4466                               MachinePointerInfo PtrInfo,
4467                               bool isVolatile, bool isNonTemporal,
4468                               bool isInvariant, unsigned Alignment,
4469                               const MDNode *TBAAInfo,
4470                               const MDNode *Ranges) {
4471   SDValue Undef = getUNDEF(Ptr.getValueType());
4472   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
4473                  PtrInfo, VT, isVolatile, isNonTemporal, isInvariant, Alignment,
4474                  TBAAInfo, Ranges);
4475 }
4476
4477 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, SDLoc dl, EVT VT,
4478                                  SDValue Chain, SDValue Ptr,
4479                                  MachinePointerInfo PtrInfo, EVT MemVT,
4480                                  bool isVolatile, bool isNonTemporal,
4481                                  unsigned Alignment, const MDNode *TBAAInfo) {
4482   SDValue Undef = getUNDEF(Ptr.getValueType());
4483   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
4484                  PtrInfo, MemVT, isVolatile, isNonTemporal, false, Alignment,
4485                  TBAAInfo);
4486 }
4487
4488
4489 SDValue
4490 SelectionDAG::getIndexedLoad(SDValue OrigLoad, SDLoc dl, SDValue Base,
4491                              SDValue Offset, ISD::MemIndexedMode AM) {
4492   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
4493   assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
4494          "Load is already a indexed load!");
4495   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
4496                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
4497                  LD->getMemoryVT(), LD->isVolatile(), LD->isNonTemporal(),
4498                  false, LD->getAlignment());
4499 }
4500
4501 SDValue SelectionDAG::getStore(SDValue Chain, SDLoc dl, SDValue Val,
4502                                SDValue Ptr, MachinePointerInfo PtrInfo,
4503                                bool isVolatile, bool isNonTemporal,
4504                                unsigned Alignment, const MDNode *TBAAInfo) {
4505   assert(Chain.getValueType() == MVT::Other &&
4506         "Invalid chain type");
4507   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
4508     Alignment = getEVTAlignment(Val.getValueType());
4509
4510   unsigned Flags = MachineMemOperand::MOStore;
4511   if (isVolatile)
4512     Flags |= MachineMemOperand::MOVolatile;
4513   if (isNonTemporal)
4514     Flags |= MachineMemOperand::MONonTemporal;
4515
4516   if (PtrInfo.V == 0)
4517     PtrInfo = InferPointerInfo(Ptr);
4518
4519   MachineFunction &MF = getMachineFunction();
4520   MachineMemOperand *MMO =
4521     MF.getMachineMemOperand(PtrInfo, Flags,
4522                             Val.getValueType().getStoreSize(), Alignment,
4523                             TBAAInfo);
4524
4525   return getStore(Chain, dl, Val, Ptr, MMO);
4526 }
4527
4528 SDValue SelectionDAG::getStore(SDValue Chain, SDLoc dl, SDValue Val,
4529                                SDValue Ptr, MachineMemOperand *MMO) {
4530   assert(Chain.getValueType() == MVT::Other &&
4531         "Invalid chain type");
4532   EVT VT = Val.getValueType();
4533   SDVTList VTs = getVTList(MVT::Other);
4534   SDValue Undef = getUNDEF(Ptr.getValueType());
4535   SDValue Ops[] = { Chain, Val, Ptr, Undef };
4536   FoldingSetNodeID ID;
4537   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
4538   ID.AddInteger(VT.getRawBits());
4539   ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile(),
4540                                      MMO->isNonTemporal(), MMO->isInvariant()));
4541   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4542   void *IP = 0;
4543   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4544     cast<StoreSDNode>(E)->refineAlignment(MMO);
4545     return SDValue(E, 0);
4546   }
4547   SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl.getIROrder(), dl.getDebugLoc(), VTs, ISD::UNINDEXED,
4548                                               false, VT, MMO);
4549   CSEMap.InsertNode(N, IP);
4550   AllNodes.push_back(N);
4551   return SDValue(N, 0);
4552 }
4553
4554 SDValue SelectionDAG::getTruncStore(SDValue Chain, SDLoc dl, SDValue Val,
4555                                     SDValue Ptr, MachinePointerInfo PtrInfo,
4556                                     EVT SVT,bool isVolatile, bool isNonTemporal,
4557                                     unsigned Alignment,
4558                                     const MDNode *TBAAInfo) {
4559   assert(Chain.getValueType() == MVT::Other &&
4560         "Invalid chain type");
4561   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
4562     Alignment = getEVTAlignment(SVT);
4563
4564   unsigned Flags = MachineMemOperand::MOStore;
4565   if (isVolatile)
4566     Flags |= MachineMemOperand::MOVolatile;
4567   if (isNonTemporal)
4568     Flags |= MachineMemOperand::MONonTemporal;
4569
4570   if (PtrInfo.V == 0)
4571     PtrInfo = InferPointerInfo(Ptr);
4572
4573   MachineFunction &MF = getMachineFunction();
4574   MachineMemOperand *MMO =
4575     MF.getMachineMemOperand(PtrInfo, Flags, SVT.getStoreSize(), Alignment,
4576                             TBAAInfo);
4577
4578   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
4579 }
4580
4581 SDValue SelectionDAG::getTruncStore(SDValue Chain, SDLoc dl, SDValue Val,
4582                                     SDValue Ptr, EVT SVT,
4583                                     MachineMemOperand *MMO) {
4584   EVT VT = Val.getValueType();
4585
4586   assert(Chain.getValueType() == MVT::Other &&
4587         "Invalid chain type");
4588   if (VT == SVT)
4589     return getStore(Chain, dl, Val, Ptr, MMO);
4590
4591   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
4592          "Should only be a truncating store, not extending!");
4593   assert(VT.isInteger() == SVT.isInteger() &&
4594          "Can't do FP-INT conversion!");
4595   assert(VT.isVector() == SVT.isVector() &&
4596          "Cannot use trunc store to convert to or from a vector!");
4597   assert((!VT.isVector() ||
4598           VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
4599          "Cannot use trunc store to change the number of vector elements!");
4600
4601   SDVTList VTs = getVTList(MVT::Other);
4602   SDValue Undef = getUNDEF(Ptr.getValueType());
4603   SDValue Ops[] = { Chain, Val, Ptr, Undef };
4604   FoldingSetNodeID ID;
4605   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
4606   ID.AddInteger(SVT.getRawBits());
4607   ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED, MMO->isVolatile(),
4608                                      MMO->isNonTemporal(), MMO->isInvariant()));
4609   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4610   void *IP = 0;
4611   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4612     cast<StoreSDNode>(E)->refineAlignment(MMO);
4613     return SDValue(E, 0);
4614   }
4615   SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl.getIROrder(), dl.getDebugLoc(), VTs, ISD::UNINDEXED,
4616                                               true, SVT, MMO);
4617   CSEMap.InsertNode(N, IP);
4618   AllNodes.push_back(N);
4619   return SDValue(N, 0);
4620 }
4621
4622 SDValue
4623 SelectionDAG::getIndexedStore(SDValue OrigStore, SDLoc dl, SDValue Base,
4624                               SDValue Offset, ISD::MemIndexedMode AM) {
4625   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
4626   assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
4627          "Store is already a indexed store!");
4628   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
4629   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
4630   FoldingSetNodeID ID;
4631   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
4632   ID.AddInteger(ST->getMemoryVT().getRawBits());
4633   ID.AddInteger(ST->getRawSubclassData());
4634   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
4635   void *IP = 0;
4636   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4637     return SDValue(E, 0);
4638
4639   SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
4640                                               ST->isTruncatingStore(),
4641                                               ST->getMemoryVT(),
4642                                               ST->getMemOperand());
4643   CSEMap.InsertNode(N, IP);
4644   AllNodes.push_back(N);
4645   return SDValue(N, 0);
4646 }
4647
4648 SDValue SelectionDAG::getVAArg(EVT VT, SDLoc dl,
4649                                SDValue Chain, SDValue Ptr,
4650                                SDValue SV,
4651                                unsigned Align) {
4652   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, MVT::i32) };
4653   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops, 4);
4654 }
4655
4656 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT,
4657                               const SDUse *Ops, unsigned NumOps) {
4658   switch (NumOps) {
4659   case 0: return getNode(Opcode, DL, VT);
4660   case 1: return getNode(Opcode, DL, VT, Ops[0]);
4661   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
4662   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
4663   default: break;
4664   }
4665
4666   // Copy from an SDUse array into an SDValue array for use with
4667   // the regular getNode logic.
4668   SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
4669   return getNode(Opcode, DL, VT, &NewOps[0], NumOps);
4670 }
4671
4672 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT,
4673                               const SDValue *Ops, unsigned NumOps) {
4674   switch (NumOps) {
4675   case 0: return getNode(Opcode, DL, VT);
4676   case 1: return getNode(Opcode, DL, VT, Ops[0]);
4677   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
4678   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
4679   default: break;
4680   }
4681
4682   switch (Opcode) {
4683   default: break;
4684   case ISD::SELECT_CC: {
4685     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
4686     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
4687            "LHS and RHS of condition must have same type!");
4688     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
4689            "True and False arms of SelectCC must have same type!");
4690     assert(Ops[2].getValueType() == VT &&
4691            "select_cc node must be of same type as true and false value!");
4692     break;
4693   }
4694   case ISD::BR_CC: {
4695     assert(NumOps == 5 && "BR_CC takes 5 operands!");
4696     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
4697            "LHS/RHS of comparison should match types!");
4698     break;
4699   }
4700   }
4701
4702   // Memoize nodes.
4703   SDNode *N;
4704   SDVTList VTs = getVTList(VT);
4705
4706   if (VT != MVT::Glue) {
4707     FoldingSetNodeID ID;
4708     AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
4709     void *IP = 0;
4710
4711     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4712       return SDValue(E, 0);
4713
4714     N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, Ops, NumOps);
4715     CSEMap.InsertNode(N, IP);
4716   } else {
4717     N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, Ops, NumOps);
4718   }
4719
4720   AllNodes.push_back(N);
4721 #ifndef NDEBUG
4722   VerifySDNode(N);
4723 #endif
4724   return SDValue(N, 0);
4725 }
4726
4727 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL,
4728                               ArrayRef<EVT> ResultTys,
4729                               const SDValue *Ops, unsigned NumOps) {
4730   return getNode(Opcode, DL, getVTList(&ResultTys[0], ResultTys.size()),
4731                  Ops, NumOps);
4732 }
4733
4734 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL,
4735                               const EVT *VTs, unsigned NumVTs,
4736                               const SDValue *Ops, unsigned NumOps) {
4737   if (NumVTs == 1)
4738     return getNode(Opcode, DL, VTs[0], Ops, NumOps);
4739   return getNode(Opcode, DL, makeVTList(VTs, NumVTs), Ops, NumOps);
4740 }
4741
4742 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
4743                               const SDValue *Ops, unsigned NumOps) {
4744   if (VTList.NumVTs == 1)
4745     return getNode(Opcode, DL, VTList.VTs[0], Ops, NumOps);
4746
4747 #if 0
4748   switch (Opcode) {
4749   // FIXME: figure out how to safely handle things like
4750   // int foo(int x) { return 1 << (x & 255); }
4751   // int bar() { return foo(256); }
4752   case ISD::SRA_PARTS:
4753   case ISD::SRL_PARTS:
4754   case ISD::SHL_PARTS:
4755     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4756         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
4757       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4758     else if (N3.getOpcode() == ISD::AND)
4759       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
4760         // If the and is only masking out bits that cannot effect the shift,
4761         // eliminate the and.
4762         unsigned NumBits = VT.getScalarType().getSizeInBits()*2;
4763         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
4764           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4765       }
4766     break;
4767   }
4768 #endif
4769
4770   // Memoize the node unless it returns a flag.
4771   SDNode *N;
4772   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
4773     FoldingSetNodeID ID;
4774     AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4775     void *IP = 0;
4776     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4777       return SDValue(E, 0);
4778
4779     if (NumOps == 1) {
4780       N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList, Ops[0]);
4781     } else if (NumOps == 2) {
4782       N = new (NodeAllocator) BinarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList, Ops[0], Ops[1]);
4783     } else if (NumOps == 3) {
4784       N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList, Ops[0], Ops[1],
4785                                             Ops[2]);
4786     } else {
4787       N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList, Ops, NumOps);
4788     }
4789     CSEMap.InsertNode(N, IP);
4790   } else {
4791     if (NumOps == 1) {
4792       N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList, Ops[0]);
4793     } else if (NumOps == 2) {
4794       N = new (NodeAllocator) BinarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList, Ops[0], Ops[1]);
4795     } else if (NumOps == 3) {
4796       N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList, Ops[0], Ops[1],
4797                                             Ops[2]);
4798     } else {
4799       N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList, Ops, NumOps);
4800     }
4801   }
4802   AllNodes.push_back(N);
4803 #ifndef NDEBUG
4804   VerifySDNode(N);
4805 #endif
4806   return SDValue(N, 0);
4807 }
4808
4809 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList) {
4810   return getNode(Opcode, DL, VTList, 0, 0);
4811 }
4812
4813 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
4814                               SDValue N1) {
4815   SDValue Ops[] = { N1 };
4816   return getNode(Opcode, DL, VTList, Ops, 1);
4817 }
4818
4819 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
4820                               SDValue N1, SDValue N2) {
4821   SDValue Ops[] = { N1, N2 };
4822   return getNode(Opcode, DL, VTList, Ops, 2);
4823 }
4824
4825 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
4826                               SDValue N1, SDValue N2, SDValue N3) {
4827   SDValue Ops[] = { N1, N2, N3 };
4828   return getNode(Opcode, DL, VTList, Ops, 3);
4829 }
4830
4831 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
4832                               SDValue N1, SDValue N2, SDValue N3,
4833                               SDValue N4) {
4834   SDValue Ops[] = { N1, N2, N3, N4 };
4835   return getNode(Opcode, DL, VTList, Ops, 4);
4836 }
4837
4838 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
4839                               SDValue N1, SDValue N2, SDValue N3,
4840                               SDValue N4, SDValue N5) {
4841   SDValue Ops[] = { N1, N2, N3, N4, N5 };
4842   return getNode(Opcode, DL, VTList, Ops, 5);
4843 }
4844
4845 SDVTList SelectionDAG::getVTList(EVT VT) {
4846   return makeVTList(SDNode::getValueTypeList(VT), 1);
4847 }
4848
4849 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
4850   for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4851        E = VTList.rend(); I != E; ++I)
4852     if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
4853       return *I;
4854
4855   EVT *Array = Allocator.Allocate<EVT>(2);
4856   Array[0] = VT1;
4857   Array[1] = VT2;
4858   SDVTList Result = makeVTList(Array, 2);
4859   VTList.push_back(Result);
4860   return Result;
4861 }
4862
4863 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
4864   for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4865        E = VTList.rend(); I != E; ++I)
4866     if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4867                           I->VTs[2] == VT3)
4868       return *I;
4869
4870   EVT *Array = Allocator.Allocate<EVT>(3);
4871   Array[0] = VT1;
4872   Array[1] = VT2;
4873   Array[2] = VT3;
4874   SDVTList Result = makeVTList(Array, 3);
4875   VTList.push_back(Result);
4876   return Result;
4877 }
4878
4879 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
4880   for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4881        E = VTList.rend(); I != E; ++I)
4882     if (I->NumVTs == 4 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4883                           I->VTs[2] == VT3 && I->VTs[3] == VT4)
4884       return *I;
4885
4886   EVT *Array = Allocator.Allocate<EVT>(4);
4887   Array[0] = VT1;
4888   Array[1] = VT2;
4889   Array[2] = VT3;
4890   Array[3] = VT4;
4891   SDVTList Result = makeVTList(Array, 4);
4892   VTList.push_back(Result);
4893   return Result;
4894 }
4895
4896 SDVTList SelectionDAG::getVTList(const EVT *VTs, unsigned NumVTs) {
4897   switch (NumVTs) {
4898     case 0: llvm_unreachable("Cannot have nodes without results!");
4899     case 1: return getVTList(VTs[0]);
4900     case 2: return getVTList(VTs[0], VTs[1]);
4901     case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
4902     case 4: return getVTList(VTs[0], VTs[1], VTs[2], VTs[3]);
4903     default: break;
4904   }
4905
4906   for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4907        E = VTList.rend(); I != E; ++I) {
4908     if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
4909       continue;
4910
4911     if (std::equal(&VTs[2], &VTs[NumVTs], &I->VTs[2]))
4912       return *I;
4913   }
4914
4915   EVT *Array = Allocator.Allocate<EVT>(NumVTs);
4916   std::copy(VTs, VTs+NumVTs, Array);
4917   SDVTList Result = makeVTList(Array, NumVTs);
4918   VTList.push_back(Result);
4919   return Result;
4920 }
4921
4922
4923 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
4924 /// specified operands.  If the resultant node already exists in the DAG,
4925 /// this does not modify the specified node, instead it returns the node that
4926 /// already exists.  If the resultant node does not exist in the DAG, the
4927 /// input node is returned.  As a degenerate case, if you specify the same
4928 /// input operands as the node already has, the input node is returned.
4929 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
4930   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
4931
4932   // Check to see if there is no change.
4933   if (Op == N->getOperand(0)) return N;
4934
4935   // See if the modified node already exists.
4936   void *InsertPos = 0;
4937   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
4938     return Existing;
4939
4940   // Nope it doesn't.  Remove the node from its current place in the maps.
4941   if (InsertPos)
4942     if (!RemoveNodeFromCSEMaps(N))
4943       InsertPos = 0;
4944
4945   // Now we update the operands.
4946   N->OperandList[0].set(Op);
4947
4948   // If this gets put into a CSE map, add it.
4949   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4950   return N;
4951 }
4952
4953 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
4954   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
4955
4956   // Check to see if there is no change.
4957   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
4958     return N;   // No operands changed, just return the input node.
4959
4960   // See if the modified node already exists.
4961   void *InsertPos = 0;
4962   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
4963     return Existing;
4964
4965   // Nope it doesn't.  Remove the node from its current place in the maps.
4966   if (InsertPos)
4967     if (!RemoveNodeFromCSEMaps(N))
4968       InsertPos = 0;
4969
4970   // Now we update the operands.
4971   if (N->OperandList[0] != Op1)
4972     N->OperandList[0].set(Op1);
4973   if (N->OperandList[1] != Op2)
4974     N->OperandList[1].set(Op2);
4975
4976   // If this gets put into a CSE map, add it.
4977   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4978   return N;
4979 }
4980
4981 SDNode *SelectionDAG::
4982 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
4983   SDValue Ops[] = { Op1, Op2, Op3 };
4984   return UpdateNodeOperands(N, Ops, 3);
4985 }
4986
4987 SDNode *SelectionDAG::
4988 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
4989                    SDValue Op3, SDValue Op4) {
4990   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
4991   return UpdateNodeOperands(N, Ops, 4);
4992 }
4993
4994 SDNode *SelectionDAG::
4995 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
4996                    SDValue Op3, SDValue Op4, SDValue Op5) {
4997   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
4998   return UpdateNodeOperands(N, Ops, 5);
4999 }
5000
5001 SDNode *SelectionDAG::
5002 UpdateNodeOperands(SDNode *N, const SDValue *Ops, unsigned NumOps) {
5003   assert(N->getNumOperands() == NumOps &&
5004          "Update with wrong number of operands");
5005
5006   // Check to see if there is no change.
5007   bool AnyChange = false;
5008   for (unsigned i = 0; i != NumOps; ++i) {
5009     if (Ops[i] != N->getOperand(i)) {
5010       AnyChange = true;
5011       break;
5012     }
5013   }
5014
5015   // No operands changed, just return the input node.
5016   if (!AnyChange) return N;
5017
5018   // See if the modified node already exists.
5019   void *InsertPos = 0;
5020   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
5021     return Existing;
5022
5023   // Nope it doesn't.  Remove the node from its current place in the maps.
5024   if (InsertPos)
5025     if (!RemoveNodeFromCSEMaps(N))
5026       InsertPos = 0;
5027
5028   // Now we update the operands.
5029   for (unsigned i = 0; i != NumOps; ++i)
5030     if (N->OperandList[i] != Ops[i])
5031       N->OperandList[i].set(Ops[i]);
5032
5033   // If this gets put into a CSE map, add it.
5034   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
5035   return N;
5036 }
5037
5038 /// DropOperands - Release the operands and set this node to have
5039 /// zero operands.
5040 void SDNode::DropOperands() {
5041   // Unlike the code in MorphNodeTo that does this, we don't need to
5042   // watch for dead nodes here.
5043   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
5044     SDUse &Use = *I++;
5045     Use.set(SDValue());
5046   }
5047 }
5048
5049 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
5050 /// machine opcode.
5051 ///
5052 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5053                                    EVT VT) {
5054   SDVTList VTs = getVTList(VT);
5055   return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
5056 }
5057
5058 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5059                                    EVT VT, SDValue Op1) {
5060   SDVTList VTs = getVTList(VT);
5061   SDValue Ops[] = { Op1 };
5062   return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
5063 }
5064
5065 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5066                                    EVT VT, SDValue Op1,
5067                                    SDValue Op2) {
5068   SDVTList VTs = getVTList(VT);
5069   SDValue Ops[] = { Op1, Op2 };
5070   return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
5071 }
5072
5073 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5074                                    EVT VT, SDValue Op1,
5075                                    SDValue Op2, SDValue Op3) {
5076   SDVTList VTs = getVTList(VT);
5077   SDValue Ops[] = { Op1, Op2, Op3 };
5078   return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
5079 }
5080
5081 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5082                                    EVT VT, const SDValue *Ops,
5083                                    unsigned NumOps) {
5084   SDVTList VTs = getVTList(VT);
5085   return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
5086 }
5087
5088 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5089                                    EVT VT1, EVT VT2, const SDValue *Ops,
5090                                    unsigned NumOps) {
5091   SDVTList VTs = getVTList(VT1, VT2);
5092   return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
5093 }
5094
5095 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5096                                    EVT VT1, EVT VT2) {
5097   SDVTList VTs = getVTList(VT1, VT2);
5098   return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
5099 }
5100
5101 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5102                                    EVT VT1, EVT VT2, EVT VT3,
5103                                    const SDValue *Ops, unsigned NumOps) {
5104   SDVTList VTs = getVTList(VT1, VT2, VT3);
5105   return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
5106 }
5107
5108 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5109                                    EVT VT1, EVT VT2, EVT VT3, EVT VT4,
5110                                    const SDValue *Ops, unsigned NumOps) {
5111   SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
5112   return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
5113 }
5114
5115 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5116                                    EVT VT1, EVT VT2,
5117                                    SDValue Op1) {
5118   SDVTList VTs = getVTList(VT1, VT2);
5119   SDValue Ops[] = { Op1 };
5120   return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
5121 }
5122
5123 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5124                                    EVT VT1, EVT VT2,
5125                                    SDValue Op1, SDValue Op2) {
5126   SDVTList VTs = getVTList(VT1, VT2);
5127   SDValue Ops[] = { Op1, Op2 };
5128   return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
5129 }
5130
5131 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5132                                    EVT VT1, EVT VT2,
5133                                    SDValue Op1, SDValue Op2,
5134                                    SDValue Op3) {
5135   SDVTList VTs = getVTList(VT1, VT2);
5136   SDValue Ops[] = { Op1, Op2, Op3 };
5137   return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
5138 }
5139
5140 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5141                                    EVT VT1, EVT VT2, EVT VT3,
5142                                    SDValue Op1, SDValue Op2,
5143                                    SDValue Op3) {
5144   SDVTList VTs = getVTList(VT1, VT2, VT3);
5145   SDValue Ops[] = { Op1, Op2, Op3 };
5146   return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
5147 }
5148
5149 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5150                                    SDVTList VTs, const SDValue *Ops,
5151                                    unsigned NumOps) {
5152   N = MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
5153   // Reset the NodeID to -1.
5154   N->setNodeId(-1);
5155   return N;
5156 }
5157
5158 /// UpdadeSDLocOnMergedSDNode - If the opt level is -O0 then it throws away
5159 /// the line number information on the merged node since it is not possible to
5160 /// preserve the information that operation is associated with multiple lines.
5161 /// This will make the debugger working better at -O0, were there is a higher
5162 /// probability having other instructions associated with that line.
5163 ///
5164 /// For IROrder, we keep the smaller of the two
5165 SDNode *SelectionDAG::UpdadeSDLocOnMergedSDNode(SDNode *N, SDLoc OLoc) {
5166   DebugLoc NLoc = N->getDebugLoc();
5167   if (!(NLoc.isUnknown()) && (OptLevel == CodeGenOpt::None) &&
5168     (OLoc.getDebugLoc() != NLoc)) {
5169     N->setDebugLoc(DebugLoc());
5170   }
5171   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
5172   N->setIROrder(Order);
5173   return N;
5174 }
5175
5176 /// MorphNodeTo - This *mutates* the specified node to have the specified
5177 /// return type, opcode, and operands.
5178 ///
5179 /// Note that MorphNodeTo returns the resultant node.  If there is already a
5180 /// node of the specified opcode and operands, it returns that node instead of
5181 /// the current one.  Note that the SDLoc need not be the same.
5182 ///
5183 /// Using MorphNodeTo is faster than creating a new node and swapping it in
5184 /// with ReplaceAllUsesWith both because it often avoids allocating a new
5185 /// node, and because it doesn't require CSE recalculation for any of
5186 /// the node's users.
5187 ///
5188 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
5189                                   SDVTList VTs, const SDValue *Ops,
5190                                   unsigned NumOps) {
5191   // If an identical node already exists, use it.
5192   void *IP = 0;
5193   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
5194     FoldingSetNodeID ID;
5195     AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
5196     if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
5197       return UpdadeSDLocOnMergedSDNode(ON, SDLoc(N));
5198   }
5199
5200   if (!RemoveNodeFromCSEMaps(N))
5201     IP = 0;
5202
5203   // Start the morphing.
5204   N->NodeType = Opc;
5205   N->ValueList = VTs.VTs;
5206   N->NumValues = VTs.NumVTs;
5207
5208   // Clear the operands list, updating used nodes to remove this from their
5209   // use list.  Keep track of any operands that become dead as a result.
5210   SmallPtrSet<SDNode*, 16> DeadNodeSet;
5211   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
5212     SDUse &Use = *I++;
5213     SDNode *Used = Use.getNode();
5214     Use.set(SDValue());
5215     if (Used->use_empty())
5216       DeadNodeSet.insert(Used);
5217   }
5218
5219   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) {
5220     // Initialize the memory references information.
5221     MN->setMemRefs(0, 0);
5222     // If NumOps is larger than the # of operands we can have in a
5223     // MachineSDNode, reallocate the operand list.
5224     if (NumOps > MN->NumOperands || !MN->OperandsNeedDelete) {
5225       if (MN->OperandsNeedDelete)
5226         delete[] MN->OperandList;
5227       if (NumOps > array_lengthof(MN->LocalOperands))
5228         // We're creating a final node that will live unmorphed for the
5229         // remainder of the current SelectionDAG iteration, so we can allocate
5230         // the operands directly out of a pool with no recycling metadata.
5231         MN->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
5232                          Ops, NumOps);
5233       else
5234         MN->InitOperands(MN->LocalOperands, Ops, NumOps);
5235       MN->OperandsNeedDelete = false;
5236     } else
5237       MN->InitOperands(MN->OperandList, Ops, NumOps);
5238   } else {
5239     // If NumOps is larger than the # of operands we currently have, reallocate
5240     // the operand list.
5241     if (NumOps > N->NumOperands) {
5242       if (N->OperandsNeedDelete)
5243         delete[] N->OperandList;
5244       N->InitOperands(new SDUse[NumOps], Ops, NumOps);
5245       N->OperandsNeedDelete = true;
5246     } else
5247       N->InitOperands(N->OperandList, Ops, NumOps);
5248   }
5249
5250   // Delete any nodes that are still dead after adding the uses for the
5251   // new operands.
5252   if (!DeadNodeSet.empty()) {
5253     SmallVector<SDNode *, 16> DeadNodes;
5254     for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
5255          E = DeadNodeSet.end(); I != E; ++I)
5256       if ((*I)->use_empty())
5257         DeadNodes.push_back(*I);
5258     RemoveDeadNodes(DeadNodes);
5259   }
5260
5261   if (IP)
5262     CSEMap.InsertNode(N, IP);   // Memoize the new node.
5263   return N;
5264 }
5265
5266
5267 /// getMachineNode - These are used for target selectors to create a new node
5268 /// with specified return type(s), MachineInstr opcode, and operands.
5269 ///
5270 /// Note that getMachineNode returns the resultant node.  If there is already a
5271 /// node of the specified opcode and operands, it returns that node instead of
5272 /// the current one.
5273 MachineSDNode *
5274 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT) {
5275   SDVTList VTs = getVTList(VT);
5276   return getMachineNode(Opcode, dl, VTs, None);
5277 }
5278
5279 MachineSDNode *
5280 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT, SDValue Op1) {
5281   SDVTList VTs = getVTList(VT);
5282   SDValue Ops[] = { Op1 };
5283   return getMachineNode(Opcode, dl, VTs, Ops);
5284 }
5285
5286 MachineSDNode *
5287 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT,
5288                              SDValue Op1, SDValue Op2) {
5289   SDVTList VTs = getVTList(VT);
5290   SDValue Ops[] = { Op1, Op2 };
5291   return getMachineNode(Opcode, dl, VTs, Ops);
5292 }
5293
5294 MachineSDNode *
5295 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT,
5296                              SDValue Op1, SDValue Op2, SDValue Op3) {
5297   SDVTList VTs = getVTList(VT);
5298   SDValue Ops[] = { Op1, Op2, Op3 };
5299   return getMachineNode(Opcode, dl, VTs, Ops);
5300 }
5301
5302 MachineSDNode *
5303 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT,
5304                              ArrayRef<SDValue> Ops) {
5305   SDVTList VTs = getVTList(VT);
5306   return getMachineNode(Opcode, dl, VTs, Ops);
5307 }
5308
5309 MachineSDNode *
5310 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT1, EVT VT2) {
5311   SDVTList VTs = getVTList(VT1, VT2);
5312   return getMachineNode(Opcode, dl, VTs, None);
5313 }
5314
5315 MachineSDNode *
5316 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5317                              EVT VT1, EVT VT2, SDValue Op1) {
5318   SDVTList VTs = getVTList(VT1, VT2);
5319   SDValue Ops[] = { Op1 };
5320   return getMachineNode(Opcode, dl, VTs, Ops);
5321 }
5322
5323 MachineSDNode *
5324 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5325                              EVT VT1, EVT VT2, SDValue Op1, SDValue Op2) {
5326   SDVTList VTs = getVTList(VT1, VT2);
5327   SDValue Ops[] = { Op1, Op2 };
5328   return getMachineNode(Opcode, dl, VTs, Ops);
5329 }
5330
5331 MachineSDNode *
5332 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5333                              EVT VT1, EVT VT2, SDValue Op1,
5334                              SDValue Op2, SDValue Op3) {
5335   SDVTList VTs = getVTList(VT1, VT2);
5336   SDValue Ops[] = { Op1, Op2, Op3 };
5337   return getMachineNode(Opcode, dl, VTs, Ops);
5338 }
5339
5340 MachineSDNode *
5341 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5342                              EVT VT1, EVT VT2,
5343                              ArrayRef<SDValue> Ops) {
5344   SDVTList VTs = getVTList(VT1, VT2);
5345   return getMachineNode(Opcode, dl, VTs, Ops);
5346 }
5347
5348 MachineSDNode *
5349 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5350                              EVT VT1, EVT VT2, EVT VT3,
5351                              SDValue Op1, SDValue Op2) {
5352   SDVTList VTs = getVTList(VT1, VT2, VT3);
5353   SDValue Ops[] = { Op1, Op2 };
5354   return getMachineNode(Opcode, dl, VTs, Ops);
5355 }
5356
5357 MachineSDNode *
5358 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5359                              EVT VT1, EVT VT2, EVT VT3,
5360                              SDValue Op1, SDValue Op2, SDValue Op3) {
5361   SDVTList VTs = getVTList(VT1, VT2, VT3);
5362   SDValue Ops[] = { Op1, Op2, Op3 };
5363   return getMachineNode(Opcode, dl, VTs, Ops);
5364 }
5365
5366 MachineSDNode *
5367 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5368                              EVT VT1, EVT VT2, EVT VT3,
5369                              ArrayRef<SDValue> Ops) {
5370   SDVTList VTs = getVTList(VT1, VT2, VT3);
5371   return getMachineNode(Opcode, dl, VTs, Ops);
5372 }
5373
5374 MachineSDNode *
5375 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT1,
5376                              EVT VT2, EVT VT3, EVT VT4,
5377                              ArrayRef<SDValue> Ops) {
5378   SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
5379   return getMachineNode(Opcode, dl, VTs, Ops);
5380 }
5381
5382 MachineSDNode *
5383 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5384                              ArrayRef<EVT> ResultTys,
5385                              ArrayRef<SDValue> Ops) {
5386   SDVTList VTs = getVTList(&ResultTys[0], ResultTys.size());
5387   return getMachineNode(Opcode, dl, VTs, Ops);
5388 }
5389
5390 MachineSDNode *
5391 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc DL, SDVTList VTs,
5392                              ArrayRef<SDValue> OpsArray) {
5393   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
5394   MachineSDNode *N;
5395   void *IP = 0;
5396   const SDValue *Ops = OpsArray.data();
5397   unsigned NumOps = OpsArray.size();
5398
5399   if (DoCSE) {
5400     FoldingSetNodeID ID;
5401     AddNodeIDNode(ID, ~Opcode, VTs, Ops, NumOps);
5402     IP = 0;
5403     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
5404       return cast<MachineSDNode>(UpdadeSDLocOnMergedSDNode(E, DL));
5405     }
5406   }
5407
5408   // Allocate a new MachineSDNode.
5409   N = new (NodeAllocator) MachineSDNode(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5410
5411   // Initialize the operands list.
5412   if (NumOps > array_lengthof(N->LocalOperands))
5413     // We're creating a final node that will live unmorphed for the
5414     // remainder of the current SelectionDAG iteration, so we can allocate
5415     // the operands directly out of a pool with no recycling metadata.
5416     N->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
5417                     Ops, NumOps);
5418   else
5419     N->InitOperands(N->LocalOperands, Ops, NumOps);
5420   N->OperandsNeedDelete = false;
5421
5422   if (DoCSE)
5423     CSEMap.InsertNode(N, IP);
5424
5425   AllNodes.push_back(N);
5426 #ifndef NDEBUG
5427   VerifyMachineNode(N);
5428 #endif
5429   return N;
5430 }
5431
5432 /// getTargetExtractSubreg - A convenience function for creating
5433 /// TargetOpcode::EXTRACT_SUBREG nodes.
5434 SDValue
5435 SelectionDAG::getTargetExtractSubreg(int SRIdx, SDLoc DL, EVT VT,
5436                                      SDValue Operand) {
5437   SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
5438   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
5439                                   VT, Operand, SRIdxVal);
5440   return SDValue(Subreg, 0);
5441 }
5442
5443 /// getTargetInsertSubreg - A convenience function for creating
5444 /// TargetOpcode::INSERT_SUBREG nodes.
5445 SDValue
5446 SelectionDAG::getTargetInsertSubreg(int SRIdx, SDLoc DL, EVT VT,
5447                                     SDValue Operand, SDValue Subreg) {
5448   SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
5449   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
5450                                   VT, Operand, Subreg, SRIdxVal);
5451   return SDValue(Result, 0);
5452 }
5453
5454 /// getNodeIfExists - Get the specified node if it's already available, or
5455 /// else return NULL.
5456 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
5457                                       const SDValue *Ops, unsigned NumOps) {
5458   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
5459     FoldingSetNodeID ID;
5460     AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
5461     void *IP = 0;
5462     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
5463       return E;
5464   }
5465   return NULL;
5466 }
5467
5468 /// getDbgValue - Creates a SDDbgValue node.
5469 ///
5470 SDDbgValue *
5471 SelectionDAG::getDbgValue(MDNode *MDPtr, SDNode *N, unsigned R, uint64_t Off,
5472                           DebugLoc DL, unsigned O) {
5473   return new (Allocator) SDDbgValue(MDPtr, N, R, Off, DL, O);
5474 }
5475
5476 SDDbgValue *
5477 SelectionDAG::getDbgValue(MDNode *MDPtr, const Value *C, uint64_t Off,
5478                           DebugLoc DL, unsigned O) {
5479   return new (Allocator) SDDbgValue(MDPtr, C, Off, DL, O);
5480 }
5481
5482 SDDbgValue *
5483 SelectionDAG::getDbgValue(MDNode *MDPtr, unsigned FI, uint64_t Off,
5484                           DebugLoc DL, unsigned O) {
5485   return new (Allocator) SDDbgValue(MDPtr, FI, Off, DL, O);
5486 }
5487
5488 namespace {
5489
5490 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
5491 /// pointed to by a use iterator is deleted, increment the use iterator
5492 /// so that it doesn't dangle.
5493 ///
5494 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
5495   SDNode::use_iterator &UI;
5496   SDNode::use_iterator &UE;
5497
5498   virtual void NodeDeleted(SDNode *N, SDNode *E) {
5499     // Increment the iterator as needed.
5500     while (UI != UE && N == *UI)
5501       ++UI;
5502   }
5503
5504 public:
5505   RAUWUpdateListener(SelectionDAG &d,
5506                      SDNode::use_iterator &ui,
5507                      SDNode::use_iterator &ue)
5508     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
5509 };
5510
5511 }
5512
5513 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5514 /// This can cause recursive merging of nodes in the DAG.
5515 ///
5516 /// This version assumes From has a single result value.
5517 ///
5518 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
5519   SDNode *From = FromN.getNode();
5520   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
5521          "Cannot replace with this method!");
5522   assert(From != To.getNode() && "Cannot replace uses of with self");
5523
5524   // Iterate over all the existing uses of From. New uses will be added
5525   // to the beginning of the use list, which we avoid visiting.
5526   // This specifically avoids visiting uses of From that arise while the
5527   // replacement is happening, because any such uses would be the result
5528   // of CSE: If an existing node looks like From after one of its operands
5529   // is replaced by To, we don't want to replace of all its users with To
5530   // too. See PR3018 for more info.
5531   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5532   RAUWUpdateListener Listener(*this, UI, UE);
5533   while (UI != UE) {
5534     SDNode *User = *UI;
5535
5536     // This node is about to morph, remove its old self from the CSE maps.
5537     RemoveNodeFromCSEMaps(User);
5538
5539     // A user can appear in a use list multiple times, and when this
5540     // happens the uses are usually next to each other in the list.
5541     // To help reduce the number of CSE recomputations, process all
5542     // the uses of this user that we can find this way.
5543     do {
5544       SDUse &Use = UI.getUse();
5545       ++UI;
5546       Use.set(To);
5547     } while (UI != UE && *UI == User);
5548
5549     // Now that we have modified User, add it back to the CSE maps.  If it
5550     // already exists there, recursively merge the results together.
5551     AddModifiedNodeToCSEMaps(User);
5552   }
5553
5554   // If we just RAUW'd the root, take note.
5555   if (FromN == getRoot())
5556     setRoot(To);
5557 }
5558
5559 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5560 /// This can cause recursive merging of nodes in the DAG.
5561 ///
5562 /// This version assumes that for each value of From, there is a
5563 /// corresponding value in To in the same position with the same type.
5564 ///
5565 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
5566 #ifndef NDEBUG
5567   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
5568     assert((!From->hasAnyUseOfValue(i) ||
5569             From->getValueType(i) == To->getValueType(i)) &&
5570            "Cannot use this version of ReplaceAllUsesWith!");
5571 #endif
5572
5573   // Handle the trivial case.
5574   if (From == To)
5575     return;
5576
5577   // Iterate over just the existing users of From. See the comments in
5578   // the ReplaceAllUsesWith above.
5579   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5580   RAUWUpdateListener Listener(*this, UI, UE);
5581   while (UI != UE) {
5582     SDNode *User = *UI;
5583
5584     // This node is about to morph, remove its old self from the CSE maps.
5585     RemoveNodeFromCSEMaps(User);
5586
5587     // A user can appear in a use list multiple times, and when this
5588     // happens the uses are usually next to each other in the list.
5589     // To help reduce the number of CSE recomputations, process all
5590     // the uses of this user that we can find this way.
5591     do {
5592       SDUse &Use = UI.getUse();
5593       ++UI;
5594       Use.setNode(To);
5595     } while (UI != UE && *UI == User);
5596
5597     // Now that we have modified User, add it back to the CSE maps.  If it
5598     // already exists there, recursively merge the results together.
5599     AddModifiedNodeToCSEMaps(User);
5600   }
5601
5602   // If we just RAUW'd the root, take note.
5603   if (From == getRoot().getNode())
5604     setRoot(SDValue(To, getRoot().getResNo()));
5605 }
5606
5607 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5608 /// This can cause recursive merging of nodes in the DAG.
5609 ///
5610 /// This version can replace From with any result values.  To must match the
5611 /// number and types of values returned by From.
5612 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
5613   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
5614     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
5615
5616   // Iterate over just the existing users of From. See the comments in
5617   // the ReplaceAllUsesWith above.
5618   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5619   RAUWUpdateListener Listener(*this, UI, UE);
5620   while (UI != UE) {
5621     SDNode *User = *UI;
5622
5623     // This node is about to morph, remove its old self from the CSE maps.
5624     RemoveNodeFromCSEMaps(User);
5625
5626     // A user can appear in a use list multiple times, and when this
5627     // happens the uses are usually next to each other in the list.
5628     // To help reduce the number of CSE recomputations, process all
5629     // the uses of this user that we can find this way.
5630     do {
5631       SDUse &Use = UI.getUse();
5632       const SDValue &ToOp = To[Use.getResNo()];
5633       ++UI;
5634       Use.set(ToOp);
5635     } while (UI != UE && *UI == User);
5636
5637     // Now that we have modified User, add it back to the CSE maps.  If it
5638     // already exists there, recursively merge the results together.
5639     AddModifiedNodeToCSEMaps(User);
5640   }
5641
5642   // If we just RAUW'd the root, take note.
5643   if (From == getRoot().getNode())
5644     setRoot(SDValue(To[getRoot().getResNo()]));
5645 }
5646
5647 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
5648 /// uses of other values produced by From.getNode() alone.  The Deleted
5649 /// vector is handled the same way as for ReplaceAllUsesWith.
5650 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
5651   // Handle the really simple, really trivial case efficiently.
5652   if (From == To) return;
5653
5654   // Handle the simple, trivial, case efficiently.
5655   if (From.getNode()->getNumValues() == 1) {
5656     ReplaceAllUsesWith(From, To);
5657     return;
5658   }
5659
5660   // Iterate over just the existing users of From. See the comments in
5661   // the ReplaceAllUsesWith above.
5662   SDNode::use_iterator UI = From.getNode()->use_begin(),
5663                        UE = From.getNode()->use_end();
5664   RAUWUpdateListener Listener(*this, UI, UE);
5665   while (UI != UE) {
5666     SDNode *User = *UI;
5667     bool UserRemovedFromCSEMaps = false;
5668
5669     // A user can appear in a use list multiple times, and when this
5670     // happens the uses are usually next to each other in the list.
5671     // To help reduce the number of CSE recomputations, process all
5672     // the uses of this user that we can find this way.
5673     do {
5674       SDUse &Use = UI.getUse();
5675
5676       // Skip uses of different values from the same node.
5677       if (Use.getResNo() != From.getResNo()) {
5678         ++UI;
5679         continue;
5680       }
5681
5682       // If this node hasn't been modified yet, it's still in the CSE maps,
5683       // so remove its old self from the CSE maps.
5684       if (!UserRemovedFromCSEMaps) {
5685         RemoveNodeFromCSEMaps(User);
5686         UserRemovedFromCSEMaps = true;
5687       }
5688
5689       ++UI;
5690       Use.set(To);
5691     } while (UI != UE && *UI == User);
5692
5693     // We are iterating over all uses of the From node, so if a use
5694     // doesn't use the specific value, no changes are made.
5695     if (!UserRemovedFromCSEMaps)
5696       continue;
5697
5698     // Now that we have modified User, add it back to the CSE maps.  If it
5699     // already exists there, recursively merge the results together.
5700     AddModifiedNodeToCSEMaps(User);
5701   }
5702
5703   // If we just RAUW'd the root, take note.
5704   if (From == getRoot())
5705     setRoot(To);
5706 }
5707
5708 namespace {
5709   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
5710   /// to record information about a use.
5711   struct UseMemo {
5712     SDNode *User;
5713     unsigned Index;
5714     SDUse *Use;
5715   };
5716
5717   /// operator< - Sort Memos by User.
5718   bool operator<(const UseMemo &L, const UseMemo &R) {
5719     return (intptr_t)L.User < (intptr_t)R.User;
5720   }
5721 }
5722
5723 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
5724 /// uses of other values produced by From.getNode() alone.  The same value
5725 /// may appear in both the From and To list.  The Deleted vector is
5726 /// handled the same way as for ReplaceAllUsesWith.
5727 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
5728                                               const SDValue *To,
5729                                               unsigned Num){
5730   // Handle the simple, trivial case efficiently.
5731   if (Num == 1)
5732     return ReplaceAllUsesOfValueWith(*From, *To);
5733
5734   // Read up all the uses and make records of them. This helps
5735   // processing new uses that are introduced during the
5736   // replacement process.
5737   SmallVector<UseMemo, 4> Uses;
5738   for (unsigned i = 0; i != Num; ++i) {
5739     unsigned FromResNo = From[i].getResNo();
5740     SDNode *FromNode = From[i].getNode();
5741     for (SDNode::use_iterator UI = FromNode->use_begin(),
5742          E = FromNode->use_end(); UI != E; ++UI) {
5743       SDUse &Use = UI.getUse();
5744       if (Use.getResNo() == FromResNo) {
5745         UseMemo Memo = { *UI, i, &Use };
5746         Uses.push_back(Memo);
5747       }
5748     }
5749   }
5750
5751   // Sort the uses, so that all the uses from a given User are together.
5752   std::sort(Uses.begin(), Uses.end());
5753
5754   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
5755        UseIndex != UseIndexEnd; ) {
5756     // We know that this user uses some value of From.  If it is the right
5757     // value, update it.
5758     SDNode *User = Uses[UseIndex].User;
5759
5760     // This node is about to morph, remove its old self from the CSE maps.
5761     RemoveNodeFromCSEMaps(User);
5762
5763     // The Uses array is sorted, so all the uses for a given User
5764     // are next to each other in the list.
5765     // To help reduce the number of CSE recomputations, process all
5766     // the uses of this user that we can find this way.
5767     do {
5768       unsigned i = Uses[UseIndex].Index;
5769       SDUse &Use = *Uses[UseIndex].Use;
5770       ++UseIndex;
5771
5772       Use.set(To[i]);
5773     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
5774
5775     // Now that we have modified User, add it back to the CSE maps.  If it
5776     // already exists there, recursively merge the results together.
5777     AddModifiedNodeToCSEMaps(User);
5778   }
5779 }
5780
5781 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
5782 /// based on their topological order. It returns the maximum id and a vector
5783 /// of the SDNodes* in assigned order by reference.
5784 unsigned SelectionDAG::AssignTopologicalOrder() {
5785
5786   unsigned DAGSize = 0;
5787
5788   // SortedPos tracks the progress of the algorithm. Nodes before it are
5789   // sorted, nodes after it are unsorted. When the algorithm completes
5790   // it is at the end of the list.
5791   allnodes_iterator SortedPos = allnodes_begin();
5792
5793   // Visit all the nodes. Move nodes with no operands to the front of
5794   // the list immediately. Annotate nodes that do have operands with their
5795   // operand count. Before we do this, the Node Id fields of the nodes
5796   // may contain arbitrary values. After, the Node Id fields for nodes
5797   // before SortedPos will contain the topological sort index, and the
5798   // Node Id fields for nodes At SortedPos and after will contain the
5799   // count of outstanding operands.
5800   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
5801     SDNode *N = I++;
5802     checkForCycles(N);
5803     unsigned Degree = N->getNumOperands();
5804     if (Degree == 0) {
5805       // A node with no uses, add it to the result array immediately.
5806       N->setNodeId(DAGSize++);
5807       allnodes_iterator Q = N;
5808       if (Q != SortedPos)
5809         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
5810       assert(SortedPos != AllNodes.end() && "Overran node list");
5811       ++SortedPos;
5812     } else {
5813       // Temporarily use the Node Id as scratch space for the degree count.
5814       N->setNodeId(Degree);
5815     }
5816   }
5817
5818   // Visit all the nodes. As we iterate, move nodes into sorted order,
5819   // such that by the time the end is reached all nodes will be sorted.
5820   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
5821     SDNode *N = I;
5822     checkForCycles(N);
5823     // N is in sorted position, so all its uses have one less operand
5824     // that needs to be sorted.
5825     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5826          UI != UE; ++UI) {
5827       SDNode *P = *UI;
5828       unsigned Degree = P->getNodeId();
5829       assert(Degree != 0 && "Invalid node degree");
5830       --Degree;
5831       if (Degree == 0) {
5832         // All of P's operands are sorted, so P may sorted now.
5833         P->setNodeId(DAGSize++);
5834         if (P != SortedPos)
5835           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
5836         assert(SortedPos != AllNodes.end() && "Overran node list");
5837         ++SortedPos;
5838       } else {
5839         // Update P's outstanding operand count.
5840         P->setNodeId(Degree);
5841       }
5842     }
5843     if (I == SortedPos) {
5844 #ifndef NDEBUG
5845       SDNode *S = ++I;
5846       dbgs() << "Overran sorted position:\n";
5847       S->dumprFull();
5848 #endif
5849       llvm_unreachable(0);
5850     }
5851   }
5852
5853   assert(SortedPos == AllNodes.end() &&
5854          "Topological sort incomplete!");
5855   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
5856          "First node in topological sort is not the entry token!");
5857   assert(AllNodes.front().getNodeId() == 0 &&
5858          "First node in topological sort has non-zero id!");
5859   assert(AllNodes.front().getNumOperands() == 0 &&
5860          "First node in topological sort has operands!");
5861   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
5862          "Last node in topologic sort has unexpected id!");
5863   assert(AllNodes.back().use_empty() &&
5864          "Last node in topologic sort has users!");
5865   assert(DAGSize == allnodes_size() && "Node count mismatch!");
5866   return DAGSize;
5867 }
5868
5869 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
5870 /// value is produced by SD.
5871 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
5872   DbgInfo->add(DB, SD, isParameter);
5873   if (SD)
5874     SD->setHasDebugValue(true);
5875 }
5876
5877 /// TransferDbgValues - Transfer SDDbgValues.
5878 void SelectionDAG::TransferDbgValues(SDValue From, SDValue To) {
5879   if (From == To || !From.getNode()->getHasDebugValue())
5880     return;
5881   SDNode *FromNode = From.getNode();
5882   SDNode *ToNode = To.getNode();
5883   ArrayRef<SDDbgValue *> DVs = GetDbgValues(FromNode);
5884   SmallVector<SDDbgValue *, 2> ClonedDVs;
5885   for (ArrayRef<SDDbgValue *>::iterator I = DVs.begin(), E = DVs.end();
5886        I != E; ++I) {
5887     SDDbgValue *Dbg = *I;
5888     if (Dbg->getKind() == SDDbgValue::SDNODE) {
5889       SDDbgValue *Clone = getDbgValue(Dbg->getMDPtr(), ToNode, To.getResNo(),
5890                                       Dbg->getOffset(), Dbg->getDebugLoc(),
5891                                       Dbg->getOrder());
5892       ClonedDVs.push_back(Clone);
5893     }
5894   }
5895   for (SmallVectorImpl<SDDbgValue *>::iterator I = ClonedDVs.begin(),
5896          E = ClonedDVs.end(); I != E; ++I)
5897     AddDbgValue(*I, ToNode, false);
5898 }
5899
5900 //===----------------------------------------------------------------------===//
5901 //                              SDNode Class
5902 //===----------------------------------------------------------------------===//
5903
5904 HandleSDNode::~HandleSDNode() {
5905   DropOperands();
5906 }
5907
5908 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
5909                                          DebugLoc DL, const GlobalValue *GA,
5910                                          EVT VT, int64_t o, unsigned char TF)
5911   : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
5912   TheGlobal = GA;
5913 }
5914
5915 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs,
5916                      EVT memvt, MachineMemOperand *mmo)
5917  : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
5918   SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(),
5919                                       MMO->isNonTemporal(), MMO->isInvariant());
5920   assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
5921   assert(isNonTemporal() == MMO->isNonTemporal() &&
5922          "Non-temporal encoding error!");
5923   assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
5924 }
5925
5926 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs,
5927                      const SDValue *Ops, unsigned NumOps, EVT memvt,
5928                      MachineMemOperand *mmo)
5929    : SDNode(Opc, Order, dl, VTs, Ops, NumOps),
5930      MemoryVT(memvt), MMO(mmo) {
5931   SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(),
5932                                       MMO->isNonTemporal(), MMO->isInvariant());
5933   assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
5934   assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
5935 }
5936
5937 /// Profile - Gather unique data for the node.
5938 ///
5939 void SDNode::Profile(FoldingSetNodeID &ID) const {
5940   AddNodeIDNode(ID, this);
5941 }
5942
5943 namespace {
5944   struct EVTArray {
5945     std::vector<EVT> VTs;
5946
5947     EVTArray() {
5948       VTs.reserve(MVT::LAST_VALUETYPE);
5949       for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
5950         VTs.push_back(MVT((MVT::SimpleValueType)i));
5951     }
5952   };
5953 }
5954
5955 static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs;
5956 static ManagedStatic<EVTArray> SimpleVTArray;
5957 static ManagedStatic<sys::SmartMutex<true> > VTMutex;
5958
5959 /// getValueTypeList - Return a pointer to the specified value type.
5960 ///
5961 const EVT *SDNode::getValueTypeList(EVT VT) {
5962   if (VT.isExtended()) {
5963     sys::SmartScopedLock<true> Lock(*VTMutex);
5964     return &(*EVTs->insert(VT).first);
5965   } else {
5966     assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
5967            "Value type out of range!");
5968     return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
5969   }
5970 }
5971
5972 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
5973 /// indicated value.  This method ignores uses of other values defined by this
5974 /// operation.
5975 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
5976   assert(Value < getNumValues() && "Bad value!");
5977
5978   // TODO: Only iterate over uses of a given value of the node
5979   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
5980     if (UI.getUse().getResNo() == Value) {
5981       if (NUses == 0)
5982         return false;
5983       --NUses;
5984     }
5985   }
5986
5987   // Found exactly the right number of uses?
5988   return NUses == 0;
5989 }
5990
5991
5992 /// hasAnyUseOfValue - Return true if there are any use of the indicated
5993 /// value. This method ignores uses of other values defined by this operation.
5994 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
5995   assert(Value < getNumValues() && "Bad value!");
5996
5997   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
5998     if (UI.getUse().getResNo() == Value)
5999       return true;
6000
6001   return false;
6002 }
6003
6004
6005 /// isOnlyUserOf - Return true if this node is the only use of N.
6006 ///
6007 bool SDNode::isOnlyUserOf(SDNode *N) const {
6008   bool Seen = false;
6009   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
6010     SDNode *User = *I;
6011     if (User == this)
6012       Seen = true;
6013     else
6014       return false;
6015   }
6016
6017   return Seen;
6018 }
6019
6020 /// isOperand - Return true if this node is an operand of N.
6021 ///
6022 bool SDValue::isOperandOf(SDNode *N) const {
6023   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
6024     if (*this == N->getOperand(i))
6025       return true;
6026   return false;
6027 }
6028
6029 bool SDNode::isOperandOf(SDNode *N) const {
6030   for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
6031     if (this == N->OperandList[i].getNode())
6032       return true;
6033   return false;
6034 }
6035
6036 /// reachesChainWithoutSideEffects - Return true if this operand (which must
6037 /// be a chain) reaches the specified operand without crossing any
6038 /// side-effecting instructions on any chain path.  In practice, this looks
6039 /// through token factors and non-volatile loads.  In order to remain efficient,
6040 /// this only looks a couple of nodes in, it does not do an exhaustive search.
6041 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
6042                                                unsigned Depth) const {
6043   if (*this == Dest) return true;
6044
6045   // Don't search too deeply, we just want to be able to see through
6046   // TokenFactor's etc.
6047   if (Depth == 0) return false;
6048
6049   // If this is a token factor, all inputs to the TF happen in parallel.  If any
6050   // of the operands of the TF does not reach dest, then we cannot do the xform.
6051   if (getOpcode() == ISD::TokenFactor) {
6052     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
6053       if (!getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
6054         return false;
6055     return true;
6056   }
6057
6058   // Loads don't have side effects, look through them.
6059   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
6060     if (!Ld->isVolatile())
6061       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
6062   }
6063   return false;
6064 }
6065
6066 /// hasPredecessor - Return true if N is a predecessor of this node.
6067 /// N is either an operand of this node, or can be reached by recursively
6068 /// traversing up the operands.
6069 /// NOTE: This is an expensive method. Use it carefully.
6070 bool SDNode::hasPredecessor(const SDNode *N) const {
6071   SmallPtrSet<const SDNode *, 32> Visited;
6072   SmallVector<const SDNode *, 16> Worklist;
6073   return hasPredecessorHelper(N, Visited, Worklist);
6074 }
6075
6076 bool
6077 SDNode::hasPredecessorHelper(const SDNode *N,
6078                              SmallPtrSet<const SDNode *, 32> &Visited,
6079                              SmallVectorImpl<const SDNode *> &Worklist) const {
6080   if (Visited.empty()) {
6081     Worklist.push_back(this);
6082   } else {
6083     // Take a look in the visited set. If we've already encountered this node
6084     // we needn't search further.
6085     if (Visited.count(N))
6086       return true;
6087   }
6088
6089   // Haven't visited N yet. Continue the search.
6090   while (!Worklist.empty()) {
6091     const SDNode *M = Worklist.pop_back_val();
6092     for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
6093       SDNode *Op = M->getOperand(i).getNode();
6094       if (Visited.insert(Op))
6095         Worklist.push_back(Op);
6096       if (Op == N)
6097         return true;
6098     }
6099   }
6100
6101   return false;
6102 }
6103
6104 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
6105   assert(Num < NumOperands && "Invalid child # of SDNode!");
6106   return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
6107 }
6108
6109 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
6110   assert(N->getNumValues() == 1 &&
6111          "Can't unroll a vector with multiple results!");
6112
6113   EVT VT = N->getValueType(0);
6114   unsigned NE = VT.getVectorNumElements();
6115   EVT EltVT = VT.getVectorElementType();
6116   SDLoc dl(N);
6117
6118   SmallVector<SDValue, 8> Scalars;
6119   SmallVector<SDValue, 4> Operands(N->getNumOperands());
6120
6121   // If ResNE is 0, fully unroll the vector op.
6122   if (ResNE == 0)
6123     ResNE = NE;
6124   else if (NE > ResNE)
6125     NE = ResNE;
6126
6127   unsigned i;
6128   for (i= 0; i != NE; ++i) {
6129     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
6130       SDValue Operand = N->getOperand(j);
6131       EVT OperandVT = Operand.getValueType();
6132       if (OperandVT.isVector()) {
6133         // A vector operand; extract a single element.
6134         const TargetLowering *TLI = TM.getTargetLowering();
6135         EVT OperandEltVT = OperandVT.getVectorElementType();
6136         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl,
6137                               OperandEltVT,
6138                               Operand,
6139                               getConstant(i, TLI->getVectorIdxTy()));
6140       } else {
6141         // A scalar operand; just use it as is.
6142         Operands[j] = Operand;
6143       }
6144     }
6145
6146     switch (N->getOpcode()) {
6147     default:
6148       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
6149                                 &Operands[0], Operands.size()));
6150       break;
6151     case ISD::VSELECT:
6152       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT,
6153                                 &Operands[0], Operands.size()));
6154       break;
6155     case ISD::SHL:
6156     case ISD::SRA:
6157     case ISD::SRL:
6158     case ISD::ROTL:
6159     case ISD::ROTR:
6160       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
6161                                 getShiftAmountOperand(Operands[0].getValueType(),
6162                                                       Operands[1])));
6163       break;
6164     case ISD::SIGN_EXTEND_INREG:
6165     case ISD::FP_ROUND_INREG: {
6166       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
6167       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
6168                                 Operands[0],
6169                                 getValueType(ExtVT)));
6170     }
6171     }
6172   }
6173
6174   for (; i < ResNE; ++i)
6175     Scalars.push_back(getUNDEF(EltVT));
6176
6177   return getNode(ISD::BUILD_VECTOR, dl,
6178                  EVT::getVectorVT(*getContext(), EltVT, ResNE),
6179                  &Scalars[0], Scalars.size());
6180 }
6181
6182
6183 /// isConsecutiveLoad - Return true if LD is loading 'Bytes' bytes from a
6184 /// location that is 'Dist' units away from the location that the 'Base' load
6185 /// is loading from.
6186 bool SelectionDAG::isConsecutiveLoad(LoadSDNode *LD, LoadSDNode *Base,
6187                                      unsigned Bytes, int Dist) const {
6188   if (LD->getChain() != Base->getChain())
6189     return false;
6190   EVT VT = LD->getValueType(0);
6191   if (VT.getSizeInBits() / 8 != Bytes)
6192     return false;
6193
6194   SDValue Loc = LD->getOperand(1);
6195   SDValue BaseLoc = Base->getOperand(1);
6196   if (Loc.getOpcode() == ISD::FrameIndex) {
6197     if (BaseLoc.getOpcode() != ISD::FrameIndex)
6198       return false;
6199     const MachineFrameInfo *MFI = getMachineFunction().getFrameInfo();
6200     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
6201     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
6202     int FS  = MFI->getObjectSize(FI);
6203     int BFS = MFI->getObjectSize(BFI);
6204     if (FS != BFS || FS != (int)Bytes) return false;
6205     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
6206   }
6207
6208   // Handle X+C
6209   if (isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
6210       cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
6211     return true;
6212
6213   const GlobalValue *GV1 = NULL;
6214   const GlobalValue *GV2 = NULL;
6215   int64_t Offset1 = 0;
6216   int64_t Offset2 = 0;
6217   const TargetLowering *TLI = TM.getTargetLowering();
6218   bool isGA1 = TLI->isGAPlusOffset(Loc.getNode(), GV1, Offset1);
6219   bool isGA2 = TLI->isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
6220   if (isGA1 && isGA2 && GV1 == GV2)
6221     return Offset1 == (Offset2 + Dist*Bytes);
6222   return false;
6223 }
6224
6225
6226 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
6227 /// it cannot be inferred.
6228 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
6229   // If this is a GlobalAddress + cst, return the alignment.
6230   const GlobalValue *GV;
6231   int64_t GVOffset = 0;
6232   const TargetLowering *TLI = TM.getTargetLowering();
6233   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
6234     unsigned PtrWidth = TLI->getPointerTy().getSizeInBits();
6235     APInt KnownZero(PtrWidth, 0), KnownOne(PtrWidth, 0);
6236     llvm::ComputeMaskedBits(const_cast<GlobalValue*>(GV), KnownZero, KnownOne,
6237                             TLI->getDataLayout());
6238     unsigned AlignBits = KnownZero.countTrailingOnes();
6239     unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0;
6240     if (Align)
6241       return MinAlign(Align, GVOffset);
6242   }
6243
6244   // If this is a direct reference to a stack slot, use information about the
6245   // stack slot's alignment.
6246   int FrameIdx = 1 << 31;
6247   int64_t FrameOffset = 0;
6248   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
6249     FrameIdx = FI->getIndex();
6250   } else if (isBaseWithConstantOffset(Ptr) &&
6251              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
6252     // Handle FI+Cst
6253     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
6254     FrameOffset = Ptr.getConstantOperandVal(1);
6255   }
6256
6257   if (FrameIdx != (1 << 31)) {
6258     const MachineFrameInfo &MFI = *getMachineFunction().getFrameInfo();
6259     unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
6260                                     FrameOffset);
6261     return FIInfoAlign;
6262   }
6263
6264   return 0;
6265 }
6266
6267 // getAddressSpace - Return the address space this GlobalAddress belongs to.
6268 unsigned GlobalAddressSDNode::getAddressSpace() const {
6269   return getGlobal()->getType()->getAddressSpace();
6270 }
6271
6272
6273 Type *ConstantPoolSDNode::getType() const {
6274   if (isMachineConstantPoolEntry())
6275     return Val.MachineCPVal->getType();
6276   return Val.ConstVal->getType();
6277 }
6278
6279 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue,
6280                                         APInt &SplatUndef,
6281                                         unsigned &SplatBitSize,
6282                                         bool &HasAnyUndefs,
6283                                         unsigned MinSplatBits,
6284                                         bool isBigEndian) {
6285   EVT VT = getValueType(0);
6286   assert(VT.isVector() && "Expected a vector type");
6287   unsigned sz = VT.getSizeInBits();
6288   if (MinSplatBits > sz)
6289     return false;
6290
6291   SplatValue = APInt(sz, 0);
6292   SplatUndef = APInt(sz, 0);
6293
6294   // Get the bits.  Bits with undefined values (when the corresponding element
6295   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
6296   // in SplatValue.  If any of the values are not constant, give up and return
6297   // false.
6298   unsigned int nOps = getNumOperands();
6299   assert(nOps > 0 && "isConstantSplat has 0-size build vector");
6300   unsigned EltBitSize = VT.getVectorElementType().getSizeInBits();
6301
6302   for (unsigned j = 0; j < nOps; ++j) {
6303     unsigned i = isBigEndian ? nOps-1-j : j;
6304     SDValue OpVal = getOperand(i);
6305     unsigned BitPos = j * EltBitSize;
6306
6307     if (OpVal.getOpcode() == ISD::UNDEF)
6308       SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos + EltBitSize);
6309     else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal))
6310       SplatValue |= CN->getAPIntValue().zextOrTrunc(EltBitSize).
6311                     zextOrTrunc(sz) << BitPos;
6312     else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal))
6313       SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos;
6314      else
6315       return false;
6316   }
6317
6318   // The build_vector is all constants or undefs.  Find the smallest element
6319   // size that splats the vector.
6320
6321   HasAnyUndefs = (SplatUndef != 0);
6322   while (sz > 8) {
6323
6324     unsigned HalfSize = sz / 2;
6325     APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
6326     APInt LowValue = SplatValue.trunc(HalfSize);
6327     APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
6328     APInt LowUndef = SplatUndef.trunc(HalfSize);
6329
6330     // If the two halves do not match (ignoring undef bits), stop here.
6331     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
6332         MinSplatBits > HalfSize)
6333       break;
6334
6335     SplatValue = HighValue | LowValue;
6336     SplatUndef = HighUndef & LowUndef;
6337
6338     sz = HalfSize;
6339   }
6340
6341   SplatBitSize = sz;
6342   return true;
6343 }
6344
6345 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
6346   // Find the first non-undef value in the shuffle mask.
6347   unsigned i, e;
6348   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
6349     /* search */;
6350
6351   assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
6352
6353   // Make sure all remaining elements are either undef or the same as the first
6354   // non-undef value.
6355   for (int Idx = Mask[i]; i != e; ++i)
6356     if (Mask[i] >= 0 && Mask[i] != Idx)
6357       return false;
6358   return true;
6359 }
6360
6361 #ifdef XDEBUG
6362 static void checkForCyclesHelper(const SDNode *N,
6363                                  SmallPtrSet<const SDNode*, 32> &Visited,
6364                                  SmallPtrSet<const SDNode*, 32> &Checked) {
6365   // If this node has already been checked, don't check it again.
6366   if (Checked.count(N))
6367     return;
6368
6369   // If a node has already been visited on this depth-first walk, reject it as
6370   // a cycle.
6371   if (!Visited.insert(N)) {
6372     dbgs() << "Offending node:\n";
6373     N->dumprFull();
6374     errs() << "Detected cycle in SelectionDAG\n";
6375     abort();
6376   }
6377
6378   for(unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
6379     checkForCyclesHelper(N->getOperand(i).getNode(), Visited, Checked);
6380
6381   Checked.insert(N);
6382   Visited.erase(N);
6383 }
6384 #endif
6385
6386 void llvm::checkForCycles(const llvm::SDNode *N) {
6387 #ifdef XDEBUG
6388   assert(N && "Checking nonexistant SDNode");
6389   SmallPtrSet<const SDNode*, 32> visited;
6390   SmallPtrSet<const SDNode*, 32> checked;
6391   checkForCyclesHelper(N, visited, checked);
6392 #endif
6393 }
6394
6395 void llvm::checkForCycles(const llvm::SelectionDAG *DAG) {
6396   checkForCycles(DAG->getRoot().getNode());
6397 }