Rewrite ISD::FCOPYSIGN lowering to never use i64. Not really ideal, but
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeDAG.cpp
1 //===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the SelectionDAG::Legalize method.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "llvm/CodeGen/MachineFunction.h"
16 #include "llvm/CodeGen/MachineFrameInfo.h"
17 #include "llvm/CodeGen/MachineJumpTableInfo.h"
18 #include "llvm/CodeGen/MachineModuleInfo.h"
19 #include "llvm/CodeGen/DwarfWriter.h"
20 #include "llvm/Analysis/DebugInfo.h"
21 #include "llvm/CodeGen/PseudoSourceValue.h"
22 #include "llvm/Target/TargetFrameInfo.h"
23 #include "llvm/Target/TargetLowering.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetOptions.h"
27 #include "llvm/Target/TargetSubtarget.h"
28 #include "llvm/CallingConv.h"
29 #include "llvm/Constants.h"
30 #include "llvm/DerivedTypes.h"
31 #include "llvm/Function.h"
32 #include "llvm/GlobalVariable.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include <map>
40 using namespace llvm;
41
42 //===----------------------------------------------------------------------===//
43 /// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
44 /// hacks on it until the target machine can handle it.  This involves
45 /// eliminating value sizes the machine cannot handle (promoting small sizes to
46 /// large sizes or splitting up large values into small values) as well as
47 /// eliminating operations the machine cannot handle.
48 ///
49 /// This code also does a small amount of optimization and recognition of idioms
50 /// as part of its processing.  For example, if a target does not support a
51 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
52 /// will attempt merge setcc and brc instructions into brcc's.
53 ///
54 namespace {
55 class VISIBILITY_HIDDEN SelectionDAGLegalize {
56   TargetLowering &TLI;
57   SelectionDAG &DAG;
58   CodeGenOpt::Level OptLevel;
59
60   // Libcall insertion helpers.
61
62   /// LastCALLSEQ_END - This keeps track of the CALLSEQ_END node that has been
63   /// legalized.  We use this to ensure that calls are properly serialized
64   /// against each other, including inserted libcalls.
65   SDValue LastCALLSEQ_END;
66
67   /// IsLegalizingCall - This member is used *only* for purposes of providing
68   /// helpful assertions that a libcall isn't created while another call is
69   /// being legalized (which could lead to non-serialized call sequences).
70   bool IsLegalizingCall;
71
72   /// IsLegalizingCallArguments - This member is used only for the purpose
73   /// of providing assert to check for LegalizeTypes because legalizing an
74   /// operation might introduce call nodes that might need type legalization.
75   bool IsLegalizingCallArgs;
76
77   enum LegalizeAction {
78     Legal,      // The target natively supports this operation.
79     Promote,    // This operation should be executed in a larger type.
80     Expand      // Try to expand this to other ops, otherwise use a libcall.
81   };
82
83   /// ValueTypeActions - This is a bitvector that contains two bits for each
84   /// value type, where the two bits correspond to the LegalizeAction enum.
85   /// This can be queried with "getTypeAction(VT)".
86   TargetLowering::ValueTypeActionImpl ValueTypeActions;
87
88   /// LegalizedNodes - For nodes that are of legal width, and that have more
89   /// than one use, this map indicates what regularized operand to use.  This
90   /// allows us to avoid legalizing the same thing more than once.
91   DenseMap<SDValue, SDValue> LegalizedNodes;
92
93   /// PromotedNodes - For nodes that are below legal width, and that have more
94   /// than one use, this map indicates what promoted value to use.  This allows
95   /// us to avoid promoting the same thing more than once.
96   DenseMap<SDValue, SDValue> PromotedNodes;
97
98   /// ExpandedNodes - For nodes that need to be expanded this map indicates
99   /// which operands are the expanded version of the input.  This allows
100   /// us to avoid expanding the same node more than once.
101   DenseMap<SDValue, std::pair<SDValue, SDValue> > ExpandedNodes;
102
103   /// SplitNodes - For vector nodes that need to be split, this map indicates
104   /// which operands are the split version of the input.  This allows us
105   /// to avoid splitting the same node more than once.
106   std::map<SDValue, std::pair<SDValue, SDValue> > SplitNodes;
107
108   /// ScalarizedNodes - For nodes that need to be converted from vector types to
109   /// scalar types, this contains the mapping of ones we have already
110   /// processed to the result.
111   std::map<SDValue, SDValue> ScalarizedNodes;
112
113   /// WidenNodes - For nodes that need to be widened from one vector type to
114   /// another, this contains the mapping of those that we have already widen.
115   /// This allows us to avoid widening more than once.
116   std::map<SDValue, SDValue> WidenNodes;
117
118   void AddLegalizedOperand(SDValue From, SDValue To) {
119     LegalizedNodes.insert(std::make_pair(From, To));
120     // If someone requests legalization of the new node, return itself.
121     if (From != To)
122       LegalizedNodes.insert(std::make_pair(To, To));
123   }
124   void AddPromotedOperand(SDValue From, SDValue To) {
125     bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
126     assert(isNew && "Got into the map somehow?");
127     isNew = isNew;
128     // If someone requests legalization of the new node, return itself.
129     LegalizedNodes.insert(std::make_pair(To, To));
130   }
131   void AddWidenedOperand(SDValue From, SDValue To) {
132     bool isNew = WidenNodes.insert(std::make_pair(From, To)).second;
133     assert(isNew && "Got into the map somehow?");
134     isNew = isNew;
135     // If someone requests legalization of the new node, return itself.
136     LegalizedNodes.insert(std::make_pair(To, To));
137   }
138
139 public:
140   SelectionDAGLegalize(SelectionDAG &DAG, CodeGenOpt::Level ol);
141
142   /// getTypeAction - Return how we should legalize values of this type, either
143   /// it is already legal or we need to expand it into multiple registers of
144   /// smaller integer type, or we need to promote it to a larger type.
145   LegalizeAction getTypeAction(MVT VT) const {
146     return (LegalizeAction)ValueTypeActions.getTypeAction(VT);
147   }
148
149   /// isTypeLegal - Return true if this type is legal on this target.
150   ///
151   bool isTypeLegal(MVT VT) const {
152     return getTypeAction(VT) == Legal;
153   }
154
155   void LegalizeDAG();
156
157 private:
158   /// HandleOp - Legalize, Promote, or Expand the specified operand as
159   /// appropriate for its type.
160   void HandleOp(SDValue Op);
161
162   /// LegalizeOp - We know that the specified value has a legal type.
163   /// Recursively ensure that the operands have legal types, then return the
164   /// result.
165   SDValue LegalizeOp(SDValue O);
166
167   /// UnrollVectorOp - We know that the given vector has a legal type, however
168   /// the operation it performs is not legal and is an operation that we have
169   /// no way of lowering.  "Unroll" the vector, splitting out the scalars and
170   /// operating on each element individually.
171   SDValue UnrollVectorOp(SDValue O);
172
173   /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
174   /// insertion index for the INSERT_VECTOR_ELT instruction.  In this case, it
175   /// is necessary to spill the vector being inserted into to memory, perform
176   /// the insert there, and then read the result back.
177   SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val,
178                                            SDValue Idx, DebugLoc dl);
179
180   /// PromoteOp - Given an operation that produces a value in an invalid type,
181   /// promote it to compute the value into a larger type.  The produced value
182   /// will have the correct bits for the low portion of the register, but no
183   /// guarantee is made about the top bits: it may be zero, sign-extended, or
184   /// garbage.
185   SDValue PromoteOp(SDValue O);
186
187   /// ExpandOp - Expand the specified SDValue into its two component pieces
188   /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this,
189   /// the LegalizedNodes map is filled in for any results that are not expanded,
190   /// the ExpandedNodes map is filled in for any results that are expanded, and
191   /// the Lo/Hi values are returned.   This applies to integer types and Vector
192   /// types.
193   void ExpandOp(SDValue O, SDValue &Lo, SDValue &Hi);
194
195   /// WidenVectorOp - Widen a vector operation to a wider type given by WidenVT
196   /// (e.g., v3i32 to v4i32).  The produced value will have the correct value
197   /// for the existing elements but no guarantee is made about the new elements
198   /// at the end of the vector: it may be zero, ones, or garbage. This is useful
199   /// when we have an instruction operating on an illegal vector type and we
200   /// want to widen it to do the computation on a legal wider vector type.
201   SDValue WidenVectorOp(SDValue Op, MVT WidenVT);
202
203   /// SplitVectorOp - Given an operand of vector type, break it down into
204   /// two smaller values.
205   void SplitVectorOp(SDValue O, SDValue &Lo, SDValue &Hi);
206
207   /// ScalarizeVectorOp - Given an operand of single-element vector type
208   /// (e.g. v1f32), convert it into the equivalent operation that returns a
209   /// scalar (e.g. f32) value.
210   SDValue ScalarizeVectorOp(SDValue O);
211
212   /// Useful 16 element vector type that is used to pass operands for widening.
213   typedef SmallVector<SDValue, 16> SDValueVector;
214
215   /// LoadWidenVectorOp - Load a vector for a wider type. Returns true if
216   /// the LdChain contains a single load and false if it contains a token
217   /// factor for multiple loads. It takes
218   ///   Result:  location to return the result
219   ///   LdChain: location to return the load chain
220   ///   Op:      load operation to widen
221   ///   NVT:     widen vector result type we want for the load
222   bool LoadWidenVectorOp(SDValue& Result, SDValue& LdChain,
223                          SDValue Op, MVT NVT);
224
225   /// Helper genWidenVectorLoads - Helper function to generate a set of
226   /// loads to load a vector with a resulting wider type. It takes
227   ///   LdChain: list of chains for the load we have generated
228   ///   Chain:   incoming chain for the ld vector
229   ///   BasePtr: base pointer to load from
230   ///   SV:      memory disambiguation source value
231   ///   SVOffset:  memory disambiugation offset
232   ///   Alignment: alignment of the memory
233   ///   isVolatile: volatile load
234   ///   LdWidth:    width of memory that we want to load
235   ///   ResType:    the wider result result type for the resulting loaded vector
236   SDValue genWidenVectorLoads(SDValueVector& LdChain, SDValue Chain,
237                                 SDValue BasePtr, const Value *SV,
238                                 int SVOffset, unsigned Alignment,
239                                 bool isVolatile, unsigned LdWidth,
240                                 MVT ResType, DebugLoc dl);
241
242   /// StoreWidenVectorOp - Stores a widen vector into non widen memory
243   /// location. It takes
244   ///     ST:      store node that we want to replace
245   ///     Chain:   incoming store chain
246   ///     BasePtr: base address of where we want to store into
247   SDValue StoreWidenVectorOp(StoreSDNode *ST, SDValue Chain,
248                                SDValue BasePtr);
249
250   /// Helper genWidenVectorStores - Helper function to generate a set of
251   /// stores to store a widen vector into non widen memory
252   // It takes
253   //   StChain: list of chains for the stores we have generated
254   //   Chain:   incoming chain for the ld vector
255   //   BasePtr: base pointer to load from
256   //   SV:      memory disambiguation source value
257   //   SVOffset:   memory disambiugation offset
258   //   Alignment:  alignment of the memory
259   //   isVolatile: volatile lod
260   //   ValOp:   value to store
261   //   StWidth: width of memory that we want to store
262   void genWidenVectorStores(SDValueVector& StChain, SDValue Chain,
263                             SDValue BasePtr, const Value *SV,
264                             int SVOffset, unsigned Alignment,
265                             bool isVolatile, SDValue ValOp,
266                             unsigned StWidth, DebugLoc dl);
267
268   /// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
269   /// performs the same shuffe in terms of order or result bytes, but on a type
270   /// whose vector element type is narrower than the original shuffle type.
271   /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
272   SDValue ShuffleWithNarrowerEltType(MVT NVT, MVT VT, DebugLoc dl,
273                                      SDValue N1, SDValue N2, 
274                                      SmallVectorImpl<int> &Mask) const;
275
276   bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
277                                     SmallPtrSet<SDNode*, 32> &NodesLeadingTo);
278
279   void LegalizeSetCCOperands(SDValue &LHS, SDValue &RHS, SDValue &CC,
280                              DebugLoc dl);
281   void LegalizeSetCCCondCode(MVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC,
282                              DebugLoc dl);
283   void LegalizeSetCC(MVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC,
284                      DebugLoc dl) {
285     LegalizeSetCCOperands(LHS, RHS, CC, dl);
286     LegalizeSetCCCondCode(VT, LHS, RHS, CC, dl);
287   }
288
289   SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned,
290                           SDValue &Hi);
291   SDValue ExpandIntToFP(bool isSigned, MVT DestTy, SDValue Source, DebugLoc dl);
292
293   SDValue EmitStackConvert(SDValue SrcOp, MVT SlotVT, MVT DestVT, DebugLoc dl);
294   SDValue ExpandBUILD_VECTOR(SDNode *Node);
295   SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
296   SDValue LegalizeINT_TO_FP(SDValue Result, bool isSigned, MVT DestTy,
297                             SDValue Op, DebugLoc dl);
298   SDValue ExpandLegalINT_TO_FP(bool isSigned, SDValue LegalOp, MVT DestVT,
299                                DebugLoc dl);
300   SDValue PromoteLegalINT_TO_FP(SDValue LegalOp, MVT DestVT, bool isSigned,
301                                 DebugLoc dl);
302   SDValue PromoteLegalFP_TO_INT(SDValue LegalOp, MVT DestVT, bool isSigned,
303                                 DebugLoc dl);
304
305   SDValue ExpandBSWAP(SDValue Op, DebugLoc dl);
306   SDValue ExpandBitCount(unsigned Opc, SDValue Op, DebugLoc dl);
307   bool ExpandShift(unsigned Opc, SDValue Op, SDValue Amt,
308                    SDValue &Lo, SDValue &Hi, DebugLoc dl);
309   void ExpandShiftParts(unsigned NodeOp, SDValue Op, SDValue Amt,
310                         SDValue &Lo, SDValue &Hi, DebugLoc dl);
311
312   SDValue ExpandEXTRACT_SUBVECTOR(SDValue Op);
313   SDValue ExpandEXTRACT_VECTOR_ELT(SDValue Op);
314   SDValue ExpandExtractFromVectorThroughStack(SDValue Op);
315 };
316 }
317
318 /// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
319 /// performs the same shuffe in terms of order or result bytes, but on a type
320 /// whose vector element type is narrower than the original shuffle type.
321 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
322 SDValue 
323 SelectionDAGLegalize::ShuffleWithNarrowerEltType(MVT NVT, MVT VT,  DebugLoc dl, 
324                                                  SDValue N1, SDValue N2,
325                                              SmallVectorImpl<int> &Mask) const {
326   MVT EltVT = NVT.getVectorElementType();
327   unsigned NumMaskElts = VT.getVectorNumElements();
328   unsigned NumDestElts = NVT.getVectorNumElements();
329   unsigned NumEltsGrowth = NumDestElts / NumMaskElts;
330
331   assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
332
333   if (NumEltsGrowth == 1)
334     return DAG.getVectorShuffle(NVT, dl, N1, N2, &Mask[0]);
335   
336   SmallVector<int, 8> NewMask;
337   for (unsigned i = 0; i != NumMaskElts; ++i) {
338     int Idx = Mask[i];
339     for (unsigned j = 0; j != NumEltsGrowth; ++j) {
340       if (Idx < 0) 
341         NewMask.push_back(-1);
342       else
343         NewMask.push_back(Idx * NumEltsGrowth + j);
344     }
345   }
346   assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?");
347   assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?");
348   return DAG.getVectorShuffle(NVT, dl, N1, N2, &NewMask[0]);
349 }
350
351 SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag,
352                                            CodeGenOpt::Level ol)
353   : TLI(dag.getTargetLoweringInfo()), DAG(dag), OptLevel(ol),
354     ValueTypeActions(TLI.getValueTypeActions()) {
355   assert(MVT::LAST_VALUETYPE <= 32 &&
356          "Too many value types for ValueTypeActions to hold!");
357 }
358
359 void SelectionDAGLegalize::LegalizeDAG() {
360   LastCALLSEQ_END = DAG.getEntryNode();
361   IsLegalizingCall = false;
362   IsLegalizingCallArgs = false;
363
364   // The legalize process is inherently a bottom-up recursive process (users
365   // legalize their uses before themselves).  Given infinite stack space, we
366   // could just start legalizing on the root and traverse the whole graph.  In
367   // practice however, this causes us to run out of stack space on large basic
368   // blocks.  To avoid this problem, compute an ordering of the nodes where each
369   // node is only legalized after all of its operands are legalized.
370   DAG.AssignTopologicalOrder();
371   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
372        E = prior(DAG.allnodes_end()); I != next(E); ++I)
373     HandleOp(SDValue(I, 0));
374
375   // Finally, it's possible the root changed.  Get the new root.
376   SDValue OldRoot = DAG.getRoot();
377   assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
378   DAG.setRoot(LegalizedNodes[OldRoot]);
379
380   ExpandedNodes.clear();
381   LegalizedNodes.clear();
382   PromotedNodes.clear();
383   SplitNodes.clear();
384   ScalarizedNodes.clear();
385   WidenNodes.clear();
386
387   // Remove dead nodes now.
388   DAG.RemoveDeadNodes();
389 }
390
391
392 /// FindCallEndFromCallStart - Given a chained node that is part of a call
393 /// sequence, find the CALLSEQ_END node that terminates the call sequence.
394 static SDNode *FindCallEndFromCallStart(SDNode *Node) {
395   if (Node->getOpcode() == ISD::CALLSEQ_END)
396     return Node;
397   if (Node->use_empty())
398     return 0;   // No CallSeqEnd
399
400   // The chain is usually at the end.
401   SDValue TheChain(Node, Node->getNumValues()-1);
402   if (TheChain.getValueType() != MVT::Other) {
403     // Sometimes it's at the beginning.
404     TheChain = SDValue(Node, 0);
405     if (TheChain.getValueType() != MVT::Other) {
406       // Otherwise, hunt for it.
407       for (unsigned i = 1, e = Node->getNumValues(); i != e; ++i)
408         if (Node->getValueType(i) == MVT::Other) {
409           TheChain = SDValue(Node, i);
410           break;
411         }
412
413       // Otherwise, we walked into a node without a chain.
414       if (TheChain.getValueType() != MVT::Other)
415         return 0;
416     }
417   }
418
419   for (SDNode::use_iterator UI = Node->use_begin(),
420        E = Node->use_end(); UI != E; ++UI) {
421
422     // Make sure to only follow users of our token chain.
423     SDNode *User = *UI;
424     for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
425       if (User->getOperand(i) == TheChain)
426         if (SDNode *Result = FindCallEndFromCallStart(User))
427           return Result;
428   }
429   return 0;
430 }
431
432 /// FindCallStartFromCallEnd - Given a chained node that is part of a call
433 /// sequence, find the CALLSEQ_START node that initiates the call sequence.
434 static SDNode *FindCallStartFromCallEnd(SDNode *Node) {
435   assert(Node && "Didn't find callseq_start for a call??");
436   if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
437
438   assert(Node->getOperand(0).getValueType() == MVT::Other &&
439          "Node doesn't have a token chain argument!");
440   return FindCallStartFromCallEnd(Node->getOperand(0).getNode());
441 }
442
443 /// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking to
444 /// see if any uses can reach Dest.  If no dest operands can get to dest,
445 /// legalize them, legalize ourself, and return false, otherwise, return true.
446 ///
447 /// Keep track of the nodes we fine that actually do lead to Dest in
448 /// NodesLeadingTo.  This avoids retraversing them exponential number of times.
449 ///
450 bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
451                                      SmallPtrSet<SDNode*, 32> &NodesLeadingTo) {
452   if (N == Dest) return true;  // N certainly leads to Dest :)
453
454   // If we've already processed this node and it does lead to Dest, there is no
455   // need to reprocess it.
456   if (NodesLeadingTo.count(N)) return true;
457
458   // If the first result of this node has been already legalized, then it cannot
459   // reach N.
460   switch (getTypeAction(N->getValueType(0))) {
461   case Legal:
462     if (LegalizedNodes.count(SDValue(N, 0))) return false;
463     break;
464   case Promote:
465     if (PromotedNodes.count(SDValue(N, 0))) return false;
466     break;
467   case Expand:
468     if (ExpandedNodes.count(SDValue(N, 0))) return false;
469     break;
470   }
471
472   // Okay, this node has not already been legalized.  Check and legalize all
473   // operands.  If none lead to Dest, then we can legalize this node.
474   bool OperandsLeadToDest = false;
475   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
476     OperandsLeadToDest |=     // If an operand leads to Dest, so do we.
477       LegalizeAllNodesNotLeadingTo(N->getOperand(i).getNode(), Dest, NodesLeadingTo);
478
479   if (OperandsLeadToDest) {
480     NodesLeadingTo.insert(N);
481     return true;
482   }
483
484   // Okay, this node looks safe, legalize it and return false.
485   HandleOp(SDValue(N, 0));
486   return false;
487 }
488
489 /// HandleOp - Legalize, Promote, Widen, or Expand the specified operand as
490 /// appropriate for its type.
491 void SelectionDAGLegalize::HandleOp(SDValue Op) {
492   // Don't touch TargetConstants
493   if (Op.getOpcode() == ISD::TargetConstant)
494     return;
495   MVT VT = Op.getValueType();
496   // We should never see any illegal result types here.
497   assert(isTypeLegal(VT) && "Illegal type introduced after type legalization?");
498   switch (getTypeAction(VT)) {
499   default: assert(0 && "Bad type action!");
500   case Legal:   (void)LegalizeOp(Op); break;
501   case Promote:
502     if (!VT.isVector()) {
503       (void)PromoteOp(Op);
504       break;
505     }
506     else  {
507       // See if we can widen otherwise use Expand to either scalarize or split
508       MVT WidenVT = TLI.getWidenVectorType(VT);
509       if (WidenVT != MVT::Other) {
510         (void) WidenVectorOp(Op, WidenVT);
511         break;
512       }
513       // else fall thru to expand since we can't widen the vector
514     }
515   case Expand:
516     if (!VT.isVector()) {
517       // If this is an illegal scalar, expand it into its two component
518       // pieces.
519       SDValue X, Y;
520       if (Op.getOpcode() == ISD::TargetConstant)
521         break;  // Allow illegal target nodes.
522       ExpandOp(Op, X, Y);
523     } else if (VT.getVectorNumElements() == 1) {
524       // If this is an illegal single element vector, convert it to a
525       // scalar operation.
526       (void)ScalarizeVectorOp(Op);
527     } else {
528       // This is an illegal multiple element vector.
529       // Split it in half and legalize both parts.
530       SDValue X, Y;
531       SplitVectorOp(Op, X, Y);
532     }
533     break;
534   }
535 }
536
537 /// ExpandConstantFP - Expands the ConstantFP node to an integer constant or
538 /// a load from the constant pool.
539 static SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP,
540                                 SelectionDAG &DAG, const TargetLowering &TLI) {
541   bool Extend = false;
542   DebugLoc dl = CFP->getDebugLoc();
543
544   // If a FP immediate is precise when represented as a float and if the
545   // target can do an extending load from float to double, we put it into
546   // the constant pool as a float, even if it's is statically typed as a
547   // double.  This shrinks FP constants and canonicalizes them for targets where
548   // an FP extending load is the same cost as a normal load (such as on the x87
549   // fp stack or PPC FP unit).
550   MVT VT = CFP->getValueType(0);
551   ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
552   if (!UseCP) {
553     assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion");
554     return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(),
555                            (VT == MVT::f64) ? MVT::i64 : MVT::i32);
556   }
557
558   MVT OrigVT = VT;
559   MVT SVT = VT;
560   while (SVT != MVT::f32) {
561     SVT = (MVT::SimpleValueType)(SVT.getSimpleVT() - 1);
562     if (CFP->isValueValidForType(SVT, CFP->getValueAPF()) &&
563         // Only do this if the target has a native EXTLOAD instruction from
564         // smaller type.
565         TLI.isLoadExtLegal(ISD::EXTLOAD, SVT) &&
566         TLI.ShouldShrinkFPConstant(OrigVT)) {
567       const Type *SType = SVT.getTypeForMVT();
568       LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
569       VT = SVT;
570       Extend = true;
571     }
572   }
573
574   SDValue CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
575   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
576   if (Extend)
577     return DAG.getExtLoad(ISD::EXTLOAD, dl,
578                           OrigVT, DAG.getEntryNode(),
579                           CPIdx, PseudoSourceValue::getConstantPool(),
580                           0, VT, false, Alignment);
581   return DAG.getLoad(OrigVT, dl, DAG.getEntryNode(), CPIdx,
582                      PseudoSourceValue::getConstantPool(), 0, false, Alignment);
583 }
584
585
586 /// ExpandFCOPYSIGNToBitwiseOps - Expands fcopysign to a series of bitwise
587 /// operations.
588 static
589 SDValue ExpandFCOPYSIGNToBitwiseOps(SDNode *Node, MVT NVT,
590                                     SelectionDAG &DAG,
591                                     const TargetLowering &TLI) {
592   DebugLoc dl = Node->getDebugLoc();
593   MVT VT = Node->getValueType(0);
594   MVT SrcVT = Node->getOperand(1).getValueType();
595   assert((SrcVT == MVT::f32 || SrcVT == MVT::f64) &&
596          "fcopysign expansion only supported for f32 and f64");
597   MVT SrcNVT = (SrcVT == MVT::f64) ? MVT::i64 : MVT::i32;
598
599   // First get the sign bit of second operand.
600   SDValue Mask1 = (SrcVT == MVT::f64)
601     ? DAG.getConstantFP(BitsToDouble(1ULL << 63), SrcVT)
602     : DAG.getConstantFP(BitsToFloat(1U << 31), SrcVT);
603   Mask1 = DAG.getNode(ISD::BIT_CONVERT, dl, SrcNVT, Mask1);
604   SDValue SignBit= DAG.getNode(ISD::BIT_CONVERT, dl, SrcNVT,
605                                Node->getOperand(1));
606   SignBit = DAG.getNode(ISD::AND, dl, SrcNVT, SignBit, Mask1);
607   // Shift right or sign-extend it if the two operands have different types.
608   int SizeDiff = SrcNVT.getSizeInBits() - NVT.getSizeInBits();
609   if (SizeDiff > 0) {
610     SignBit = DAG.getNode(ISD::SRL, dl, SrcNVT, SignBit,
611                           DAG.getConstant(SizeDiff, TLI.getShiftAmountTy()));
612     SignBit = DAG.getNode(ISD::TRUNCATE, dl, NVT, SignBit);
613   } else if (SizeDiff < 0) {
614     SignBit = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, SignBit);
615     SignBit = DAG.getNode(ISD::SHL, dl, NVT, SignBit,
616                           DAG.getConstant(-SizeDiff, TLI.getShiftAmountTy()));
617   }
618
619   // Clear the sign bit of first operand.
620   SDValue Mask2 = (VT == MVT::f64)
621     ? DAG.getConstantFP(BitsToDouble(~(1ULL << 63)), VT)
622     : DAG.getConstantFP(BitsToFloat(~(1U << 31)), VT);
623   Mask2 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Mask2);
624   SDValue Result = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Node->getOperand(0));
625   Result = DAG.getNode(ISD::AND, dl, NVT, Result, Mask2);
626
627   // Or the value with the sign bit.
628   Result = DAG.getNode(ISD::OR, dl, NVT, Result, SignBit);
629   return Result;
630 }
631
632 /// ExpandUnalignedStore - Expands an unaligned store to 2 half-size stores.
633 static
634 SDValue ExpandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG,
635                              const TargetLowering &TLI) {
636   SDValue Chain = ST->getChain();
637   SDValue Ptr = ST->getBasePtr();
638   SDValue Val = ST->getValue();
639   MVT VT = Val.getValueType();
640   int Alignment = ST->getAlignment();
641   int SVOffset = ST->getSrcValueOffset();
642   DebugLoc dl = ST->getDebugLoc();
643   if (ST->getMemoryVT().isFloatingPoint() ||
644       ST->getMemoryVT().isVector()) {
645     MVT intVT = MVT::getIntegerVT(VT.getSizeInBits());
646     if (TLI.isTypeLegal(intVT)) {
647       // Expand to a bitconvert of the value to the integer type of the
648       // same size, then a (misaligned) int store.
649       // FIXME: Does not handle truncating floating point stores!
650       SDValue Result = DAG.getNode(ISD::BIT_CONVERT, dl, intVT, Val);
651       return DAG.getStore(Chain, dl, Result, Ptr, ST->getSrcValue(),
652                           SVOffset, ST->isVolatile(), Alignment);
653     } else {
654       // Do a (aligned) store to a stack slot, then copy from the stack slot
655       // to the final destination using (unaligned) integer loads and stores.
656       MVT StoredVT = ST->getMemoryVT();
657       MVT RegVT =
658         TLI.getRegisterType(MVT::getIntegerVT(StoredVT.getSizeInBits()));
659       unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
660       unsigned RegBytes = RegVT.getSizeInBits() / 8;
661       unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
662
663       // Make sure the stack slot is also aligned for the register type.
664       SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
665
666       // Perform the original store, only redirected to the stack slot.
667       SDValue Store = DAG.getTruncStore(Chain, dl,
668                                         Val, StackPtr, NULL, 0, StoredVT);
669       SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
670       SmallVector<SDValue, 8> Stores;
671       unsigned Offset = 0;
672
673       // Do all but one copies using the full register width.
674       for (unsigned i = 1; i < NumRegs; i++) {
675         // Load one integer register's worth from the stack slot.
676         SDValue Load = DAG.getLoad(RegVT, dl, Store, StackPtr, NULL, 0);
677         // Store it to the final location.  Remember the store.
678         Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
679                                       ST->getSrcValue(), SVOffset + Offset,
680                                       ST->isVolatile(),
681                                       MinAlign(ST->getAlignment(), Offset)));
682         // Increment the pointers.
683         Offset += RegBytes;
684         StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
685                                Increment);
686         Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
687       }
688
689       // The last store may be partial.  Do a truncating store.  On big-endian
690       // machines this requires an extending load from the stack slot to ensure
691       // that the bits are in the right place.
692       MVT MemVT = MVT::getIntegerVT(8 * (StoredBytes - Offset));
693
694       // Load from the stack slot.
695       SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
696                                     NULL, 0, MemVT);
697
698       Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
699                                          ST->getSrcValue(), SVOffset + Offset,
700                                          MemVT, ST->isVolatile(),
701                                          MinAlign(ST->getAlignment(), Offset)));
702       // The order of the stores doesn't matter - say it with a TokenFactor.
703       return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
704                          Stores.size());
705     }
706   }
707   assert(ST->getMemoryVT().isInteger() &&
708          !ST->getMemoryVT().isVector() &&
709          "Unaligned store of unknown type.");
710   // Get the half-size VT
711   MVT NewStoredVT =
712     (MVT::SimpleValueType)(ST->getMemoryVT().getSimpleVT() - 1);
713   int NumBits = NewStoredVT.getSizeInBits();
714   int IncrementSize = NumBits / 8;
715
716   // Divide the stored value in two parts.
717   SDValue ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
718   SDValue Lo = Val;
719   SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
720
721   // Store the two parts
722   SDValue Store1, Store2;
723   Store1 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Lo:Hi, Ptr,
724                              ST->getSrcValue(), SVOffset, NewStoredVT,
725                              ST->isVolatile(), Alignment);
726   Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
727                     DAG.getConstant(IncrementSize, TLI.getPointerTy()));
728   Alignment = MinAlign(Alignment, IncrementSize);
729   Store2 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Hi:Lo, Ptr,
730                              ST->getSrcValue(), SVOffset + IncrementSize,
731                              NewStoredVT, ST->isVolatile(), Alignment);
732
733   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
734 }
735
736 /// ExpandUnalignedLoad - Expands an unaligned load to 2 half-size loads.
737 static
738 SDValue ExpandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG,
739                             const TargetLowering &TLI) {
740   int SVOffset = LD->getSrcValueOffset();
741   SDValue Chain = LD->getChain();
742   SDValue Ptr = LD->getBasePtr();
743   MVT VT = LD->getValueType(0);
744   MVT LoadedVT = LD->getMemoryVT();
745   DebugLoc dl = LD->getDebugLoc();
746   if (VT.isFloatingPoint() || VT.isVector()) {
747     MVT intVT = MVT::getIntegerVT(LoadedVT.getSizeInBits());
748     if (TLI.isTypeLegal(intVT)) {
749       // Expand to a (misaligned) integer load of the same size,
750       // then bitconvert to floating point or vector.
751       SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, LD->getSrcValue(),
752                                     SVOffset, LD->isVolatile(),
753                                     LD->getAlignment());
754       SDValue Result = DAG.getNode(ISD::BIT_CONVERT, dl, LoadedVT, newLoad);
755       if (VT.isFloatingPoint() && LoadedVT != VT)
756         Result = DAG.getNode(ISD::FP_EXTEND, dl, VT, Result);
757
758       SDValue Ops[] = { Result, Chain };
759       return DAG.getMergeValues(Ops, 2, dl);
760     } else {
761       // Copy the value to a (aligned) stack slot using (unaligned) integer
762       // loads and stores, then do a (aligned) load from the stack slot.
763       MVT RegVT = TLI.getRegisterType(intVT);
764       unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
765       unsigned RegBytes = RegVT.getSizeInBits() / 8;
766       unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
767
768       // Make sure the stack slot is also aligned for the register type.
769       SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
770
771       SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
772       SmallVector<SDValue, 8> Stores;
773       SDValue StackPtr = StackBase;
774       unsigned Offset = 0;
775
776       // Do all but one copies using the full register width.
777       for (unsigned i = 1; i < NumRegs; i++) {
778         // Load one integer register's worth from the original location.
779         SDValue Load = DAG.getLoad(RegVT, dl, Chain, Ptr, LD->getSrcValue(),
780                                    SVOffset + Offset, LD->isVolatile(),
781                                    MinAlign(LD->getAlignment(), Offset));
782         // Follow the load with a store to the stack slot.  Remember the store.
783         Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
784                                       NULL, 0));
785         // Increment the pointers.
786         Offset += RegBytes;
787         Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
788         StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
789                                Increment);
790       }
791
792       // The last copy may be partial.  Do an extending load.
793       MVT MemVT = MVT::getIntegerVT(8 * (LoadedBytes - Offset));
794       SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
795                                     LD->getSrcValue(), SVOffset + Offset,
796                                     MemVT, LD->isVolatile(),
797                                     MinAlign(LD->getAlignment(), Offset));
798       // Follow the load with a store to the stack slot.  Remember the store.
799       // On big-endian machines this requires a truncating store to ensure
800       // that the bits end up in the right place.
801       Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
802                                          NULL, 0, MemVT));
803
804       // The order of the stores doesn't matter - say it with a TokenFactor.
805       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
806                                Stores.size());
807
808       // Finally, perform the original load only redirected to the stack slot.
809       Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
810                             NULL, 0, LoadedVT);
811
812       // Callers expect a MERGE_VALUES node.
813       SDValue Ops[] = { Load, TF };
814       return DAG.getMergeValues(Ops, 2, dl);
815     }
816   }
817   assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
818          "Unaligned load of unsupported type.");
819
820   // Compute the new VT that is half the size of the old one.  This is an
821   // integer MVT.
822   unsigned NumBits = LoadedVT.getSizeInBits();
823   MVT NewLoadedVT;
824   NewLoadedVT = MVT::getIntegerVT(NumBits/2);
825   NumBits >>= 1;
826
827   unsigned Alignment = LD->getAlignment();
828   unsigned IncrementSize = NumBits / 8;
829   ISD::LoadExtType HiExtType = LD->getExtensionType();
830
831   // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
832   if (HiExtType == ISD::NON_EXTLOAD)
833     HiExtType = ISD::ZEXTLOAD;
834
835   // Load the value in two parts
836   SDValue Lo, Hi;
837   if (TLI.isLittleEndian()) {
838     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getSrcValue(),
839                         SVOffset, NewLoadedVT, LD->isVolatile(), Alignment);
840     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
841                       DAG.getConstant(IncrementSize, TLI.getPointerTy()));
842     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getSrcValue(),
843                         SVOffset + IncrementSize, NewLoadedVT, LD->isVolatile(),
844                         MinAlign(Alignment, IncrementSize));
845   } else {
846     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getSrcValue(),
847                         SVOffset, NewLoadedVT, LD->isVolatile(), Alignment);
848     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
849                       DAG.getConstant(IncrementSize, TLI.getPointerTy()));
850     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getSrcValue(),
851                         SVOffset + IncrementSize, NewLoadedVT, LD->isVolatile(),
852                         MinAlign(Alignment, IncrementSize));
853   }
854
855   // aggregate the two parts
856   SDValue ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
857   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
858   Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
859
860   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
861                              Hi.getValue(1));
862
863   SDValue Ops[] = { Result, TF };
864   return DAG.getMergeValues(Ops, 2, dl);
865 }
866
867 /// UnrollVectorOp - We know that the given vector has a legal type, however
868 /// the operation it performs is not legal and is an operation that we have
869 /// no way of lowering.  "Unroll" the vector, splitting out the scalars and
870 /// operating on each element individually.
871 SDValue SelectionDAGLegalize::UnrollVectorOp(SDValue Op) {
872   MVT VT = Op.getValueType();
873   assert(isTypeLegal(VT) &&
874          "Caller should expand or promote operands that are not legal!");
875   assert(Op.getNode()->getNumValues() == 1 &&
876          "Can't unroll a vector with multiple results!");
877   unsigned NE = VT.getVectorNumElements();
878   MVT EltVT = VT.getVectorElementType();
879   DebugLoc dl = Op.getDebugLoc();
880
881   SmallVector<SDValue, 8> Scalars;
882   SmallVector<SDValue, 4> Operands(Op.getNumOperands());
883   for (unsigned i = 0; i != NE; ++i) {
884     for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
885       SDValue Operand = Op.getOperand(j);
886       MVT OperandVT = Operand.getValueType();
887       if (OperandVT.isVector()) {
888         // A vector operand; extract a single element.
889         MVT OperandEltVT = OperandVT.getVectorElementType();
890         Operands[j] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
891                                   OperandEltVT,
892                                   Operand,
893                                   DAG.getConstant(i, MVT::i32));
894       } else {
895         // A scalar operand; just use it as is.
896         Operands[j] = Operand;
897       }
898     }
899
900     switch (Op.getOpcode()) {
901     default:
902       Scalars.push_back(DAG.getNode(Op.getOpcode(), dl, EltVT,
903                                     &Operands[0], Operands.size()));
904       break;
905     case ISD::SHL:
906     case ISD::SRA:
907     case ISD::SRL:
908     case ISD::ROTL:
909     case ISD::ROTR:
910       Scalars.push_back(DAG.getNode(Op.getOpcode(), dl, EltVT, Operands[0],
911                                     DAG.getShiftAmountOperand(Operands[1])));
912       break;
913     }
914   }
915
916   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Scalars[0], Scalars.size());
917 }
918
919 /// GetFPLibCall - Return the right libcall for the given floating point type.
920 static RTLIB::Libcall GetFPLibCall(MVT VT,
921                                    RTLIB::Libcall Call_F32,
922                                    RTLIB::Libcall Call_F64,
923                                    RTLIB::Libcall Call_F80,
924                                    RTLIB::Libcall Call_PPCF128) {
925   return
926     VT == MVT::f32 ? Call_F32 :
927     VT == MVT::f64 ? Call_F64 :
928     VT == MVT::f80 ? Call_F80 :
929     VT == MVT::ppcf128 ? Call_PPCF128 :
930     RTLIB::UNKNOWN_LIBCALL;
931 }
932
933 /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
934 /// insertion index for the INSERT_VECTOR_ELT instruction.  In this case, it
935 /// is necessary to spill the vector being inserted into to memory, perform
936 /// the insert there, and then read the result back.
937 SDValue SelectionDAGLegalize::
938 PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx,
939                                DebugLoc dl) {
940   SDValue Tmp1 = Vec;
941   SDValue Tmp2 = Val;
942   SDValue Tmp3 = Idx;
943
944   // If the target doesn't support this, we have to spill the input vector
945   // to a temporary stack slot, update the element, then reload it.  This is
946   // badness.  We could also load the value into a vector register (either
947   // with a "move to register" or "extload into register" instruction, then
948   // permute it into place, if the idx is a constant and if the idx is
949   // supported by the target.
950   MVT VT    = Tmp1.getValueType();
951   MVT EltVT = VT.getVectorElementType();
952   MVT IdxVT = Tmp3.getValueType();
953   MVT PtrVT = TLI.getPointerTy();
954   SDValue StackPtr = DAG.CreateStackTemporary(VT);
955
956   int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
957
958   // Store the vector.
959   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Tmp1, StackPtr,
960                             PseudoSourceValue::getFixedStack(SPFI), 0);
961
962   // Truncate or zero extend offset to target pointer type.
963   unsigned CastOpc = IdxVT.bitsGT(PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
964   Tmp3 = DAG.getNode(CastOpc, dl, PtrVT, Tmp3);
965   // Add the offset to the index.
966   unsigned EltSize = EltVT.getSizeInBits()/8;
967   Tmp3 = DAG.getNode(ISD::MUL, dl, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
968   SDValue StackPtr2 = DAG.getNode(ISD::ADD, dl, IdxVT, Tmp3, StackPtr);
969   // Store the scalar value.
970   Ch = DAG.getTruncStore(Ch, dl, Tmp2, StackPtr2,
971                          PseudoSourceValue::getFixedStack(SPFI), 0, EltVT);
972   // Load the updated vector.
973   return DAG.getLoad(VT, dl, Ch, StackPtr,
974                      PseudoSourceValue::getFixedStack(SPFI), 0);
975 }
976
977
978 /// LegalizeOp - We know that the specified value has a legal type, and
979 /// that its operands are legal.  Now ensure that the operation itself
980 /// is legal, recursively ensuring that the operands' operations remain
981 /// legal.
982 SDValue SelectionDAGLegalize::LegalizeOp(SDValue Op) {
983   if (Op.getOpcode() == ISD::TargetConstant) // Allow illegal target nodes.
984     return Op;
985
986   SDNode *Node = Op.getNode();
987   DebugLoc dl = Node->getDebugLoc();
988
989   for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
990     assert(getTypeAction(Node->getValueType(i)) == Legal &&
991            "Unexpected illegal type!");
992
993   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
994     assert((isTypeLegal(Node->getOperand(i).getValueType()) || 
995             Node->getOperand(i).getOpcode() == ISD::TargetConstant) &&
996            "Unexpected illegal type!");
997
998   // Note that LegalizeOp may be reentered even from single-use nodes, which
999   // means that we always must cache transformed nodes.
1000   DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
1001   if (I != LegalizedNodes.end()) return I->second;
1002
1003   SDValue Tmp1, Tmp2, Tmp3, Tmp4;
1004   SDValue Result = Op;
1005   bool isCustom = false;
1006
1007   switch (Node->getOpcode()) {
1008   case ISD::FrameIndex:
1009   case ISD::EntryToken:
1010   case ISD::Register:
1011   case ISD::BasicBlock:
1012   case ISD::TargetFrameIndex:
1013   case ISD::TargetJumpTable:
1014   case ISD::TargetConstant:
1015   case ISD::TargetConstantFP:
1016   case ISD::TargetConstantPool:
1017   case ISD::TargetGlobalAddress:
1018   case ISD::TargetGlobalTLSAddress:
1019   case ISD::TargetExternalSymbol:
1020   case ISD::VALUETYPE:
1021   case ISD::SRCVALUE:
1022   case ISD::MEMOPERAND:
1023   case ISD::CONDCODE:
1024   case ISD::ARG_FLAGS:
1025     // Primitives must all be legal.
1026     assert(TLI.isOperationLegal(Node->getOpcode(), Node->getValueType(0)) &&
1027            "This must be legal!");
1028     break;
1029   default:
1030     if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
1031       // If this is a target node, legalize it by legalizing the operands then
1032       // passing it through.
1033       SmallVector<SDValue, 8> Ops;
1034       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1035         Ops.push_back(LegalizeOp(Node->getOperand(i)));
1036
1037       Result = DAG.UpdateNodeOperands(Result.getValue(0), Ops.data(), Ops.size());
1038
1039       for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
1040         AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
1041       return Result.getValue(Op.getResNo());
1042     }
1043     // Otherwise this is an unhandled builtin node.  splat.
1044 #ifndef NDEBUG
1045     cerr << "NODE: "; Node->dump(&DAG); cerr << "\n";
1046 #endif
1047     assert(0 && "Do not know how to legalize this operator!");
1048     abort();
1049   case ISD::GLOBAL_OFFSET_TABLE:
1050   case ISD::GlobalAddress:
1051   case ISD::GlobalTLSAddress:
1052   case ISD::ExternalSymbol:
1053   case ISD::ConstantPool:
1054   case ISD::JumpTable: // Nothing to do.
1055     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1056     default: assert(0 && "This action is not supported yet!");
1057     case TargetLowering::Custom:
1058       Tmp1 = TLI.LowerOperation(Op, DAG);
1059       if (Tmp1.getNode()) Result = Tmp1;
1060       // FALLTHROUGH if the target doesn't want to lower this op after all.
1061     case TargetLowering::Legal:
1062       break;
1063     }
1064     break;
1065   case ISD::FRAMEADDR:
1066   case ISD::RETURNADDR:
1067     // The only option for these nodes is to custom lower them.  If the target
1068     // does not custom lower them, then return zero.
1069     Tmp1 = TLI.LowerOperation(Op, DAG);
1070     if (Tmp1.getNode())
1071       Result = Tmp1;
1072     else
1073       Result = DAG.getConstant(0, TLI.getPointerTy());
1074     break;
1075   case ISD::FRAME_TO_ARGS_OFFSET: {
1076     MVT VT = Node->getValueType(0);
1077     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1078     default: assert(0 && "This action is not supported yet!");
1079     case TargetLowering::Custom:
1080       Result = TLI.LowerOperation(Op, DAG);
1081       if (Result.getNode()) break;
1082       // Fall Thru
1083     case TargetLowering::Legal:
1084       Result = DAG.getConstant(0, VT);
1085       break;
1086     }
1087     }
1088     break;
1089   case ISD::EXCEPTIONADDR: {
1090     Tmp1 = LegalizeOp(Node->getOperand(0));
1091     MVT VT = Node->getValueType(0);
1092     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1093     default: assert(0 && "This action is not supported yet!");
1094     case TargetLowering::Expand: {
1095         unsigned Reg = TLI.getExceptionAddressRegister();
1096         Result = DAG.getCopyFromReg(Tmp1, dl, Reg, VT);
1097       }
1098       break;
1099     case TargetLowering::Custom:
1100       Result = TLI.LowerOperation(Op, DAG);
1101       if (Result.getNode()) break;
1102       // Fall Thru
1103     case TargetLowering::Legal: {
1104       SDValue Ops[] = { DAG.getConstant(0, VT), Tmp1 };
1105       Result = DAG.getMergeValues(Ops, 2, dl);
1106       break;
1107     }
1108     }
1109     }
1110     if (Result.getNode()->getNumValues() == 1) break;
1111
1112     assert(Result.getNode()->getNumValues() == 2 &&
1113            "Cannot return more than two values!");
1114
1115     // Since we produced two values, make sure to remember that we
1116     // legalized both of them.
1117     Tmp1 = LegalizeOp(Result);
1118     Tmp2 = LegalizeOp(Result.getValue(1));
1119     AddLegalizedOperand(Op.getValue(0), Tmp1);
1120     AddLegalizedOperand(Op.getValue(1), Tmp2);
1121     return Op.getResNo() ? Tmp2 : Tmp1;
1122   case ISD::EHSELECTION: {
1123     Tmp1 = LegalizeOp(Node->getOperand(0));
1124     Tmp2 = LegalizeOp(Node->getOperand(1));
1125     MVT VT = Node->getValueType(0);
1126     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1127     default: assert(0 && "This action is not supported yet!");
1128     case TargetLowering::Expand: {
1129         unsigned Reg = TLI.getExceptionSelectorRegister();
1130         Result = DAG.getCopyFromReg(Tmp2, dl, Reg, VT);
1131       }
1132       break;
1133     case TargetLowering::Custom:
1134       Result = TLI.LowerOperation(Op, DAG);
1135       if (Result.getNode()) break;
1136       // Fall Thru
1137     case TargetLowering::Legal: {
1138       SDValue Ops[] = { DAG.getConstant(0, VT), Tmp2 };
1139       Result = DAG.getMergeValues(Ops, 2, dl);
1140       break;
1141     }
1142     }
1143     }
1144     if (Result.getNode()->getNumValues() == 1) break;
1145
1146     assert(Result.getNode()->getNumValues() == 2 &&
1147            "Cannot return more than two values!");
1148
1149     // Since we produced two values, make sure to remember that we
1150     // legalized both of them.
1151     Tmp1 = LegalizeOp(Result);
1152     Tmp2 = LegalizeOp(Result.getValue(1));
1153     AddLegalizedOperand(Op.getValue(0), Tmp1);
1154     AddLegalizedOperand(Op.getValue(1), Tmp2);
1155     return Op.getResNo() ? Tmp2 : Tmp1;
1156   case ISD::EH_RETURN: {
1157     MVT VT = Node->getValueType(0);
1158     // The only "good" option for this node is to custom lower it.
1159     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1160     default: assert(0 && "This action is not supported at all!");
1161     case TargetLowering::Custom:
1162       Result = TLI.LowerOperation(Op, DAG);
1163       if (Result.getNode()) break;
1164       // Fall Thru
1165     case TargetLowering::Legal:
1166       // Target does not know, how to lower this, lower to noop
1167       Result = LegalizeOp(Node->getOperand(0));
1168       break;
1169     }
1170     }
1171     break;
1172   case ISD::AssertSext:
1173   case ISD::AssertZext:
1174     Tmp1 = LegalizeOp(Node->getOperand(0));
1175     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1176     break;
1177   case ISD::MERGE_VALUES:
1178     // Legalize eliminates MERGE_VALUES nodes.
1179     Result = Node->getOperand(Op.getResNo());
1180     break;
1181   case ISD::CopyFromReg:
1182     Tmp1 = LegalizeOp(Node->getOperand(0));
1183     Result = Op.getValue(0);
1184     if (Node->getNumValues() == 2) {
1185       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1186     } else {
1187       assert(Node->getNumValues() == 3 && "Invalid copyfromreg!");
1188       if (Node->getNumOperands() == 3) {
1189         Tmp2 = LegalizeOp(Node->getOperand(2));
1190         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
1191       } else {
1192         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1193       }
1194       AddLegalizedOperand(Op.getValue(2), Result.getValue(2));
1195     }
1196     // Since CopyFromReg produces two values, make sure to remember that we
1197     // legalized both of them.
1198     AddLegalizedOperand(Op.getValue(0), Result);
1199     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1200     return Result.getValue(Op.getResNo());
1201   case ISD::UNDEF: {
1202     MVT VT = Op.getValueType();
1203     switch (TLI.getOperationAction(ISD::UNDEF, VT)) {
1204     default: assert(0 && "This action is not supported yet!");
1205     case TargetLowering::Expand:
1206       if (VT.isInteger())
1207         Result = DAG.getConstant(0, VT);
1208       else if (VT.isFloatingPoint())
1209         Result = DAG.getConstantFP(APFloat(APInt(VT.getSizeInBits(), 0)),
1210                                    VT);
1211       else
1212         assert(0 && "Unknown value type!");
1213       break;
1214     case TargetLowering::Legal:
1215       break;
1216     }
1217     break;
1218   }
1219
1220   case ISD::INTRINSIC_W_CHAIN:
1221   case ISD::INTRINSIC_WO_CHAIN:
1222   case ISD::INTRINSIC_VOID: {
1223     SmallVector<SDValue, 8> Ops;
1224     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1225       Ops.push_back(LegalizeOp(Node->getOperand(i)));
1226     Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1227
1228     // Allow the target to custom lower its intrinsics if it wants to.
1229     if (TLI.getOperationAction(Node->getOpcode(), MVT::Other) ==
1230         TargetLowering::Custom) {
1231       Tmp3 = TLI.LowerOperation(Result, DAG);
1232       if (Tmp3.getNode()) Result = Tmp3;
1233     }
1234
1235     if (Result.getNode()->getNumValues() == 1) break;
1236
1237     // Must have return value and chain result.
1238     assert(Result.getNode()->getNumValues() == 2 &&
1239            "Cannot return more than two values!");
1240
1241     // Since loads produce two values, make sure to remember that we
1242     // legalized both of them.
1243     AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1244     AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1245     return Result.getValue(Op.getResNo());
1246   }
1247
1248   case ISD::DBG_STOPPOINT:
1249     assert(Node->getNumOperands() == 1 && "Invalid DBG_STOPPOINT node!");
1250     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the input chain.
1251
1252     switch (TLI.getOperationAction(ISD::DBG_STOPPOINT, MVT::Other)) {
1253     case TargetLowering::Promote:
1254     default: assert(0 && "This action is not supported yet!");
1255     case TargetLowering::Expand: {
1256       DwarfWriter *DW = DAG.getDwarfWriter();
1257       bool useDEBUG_LOC = TLI.isOperationLegalOrCustom(ISD::DEBUG_LOC,
1258                                                        MVT::Other);
1259       bool useLABEL = TLI.isOperationLegalOrCustom(ISD::DBG_LABEL, MVT::Other);
1260
1261       const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(Node);
1262       GlobalVariable *CU_GV = cast<GlobalVariable>(DSP->getCompileUnit());
1263       if (DW && (useDEBUG_LOC || useLABEL) && !CU_GV->isDeclaration()) {
1264         DICompileUnit CU(cast<GlobalVariable>(DSP->getCompileUnit()));
1265
1266         unsigned Line = DSP->getLine();
1267         unsigned Col = DSP->getColumn();
1268
1269         if (OptLevel == CodeGenOpt::None) {
1270           // A bit self-referential to have DebugLoc on Debug_Loc nodes, but it
1271           // won't hurt anything.
1272           if (useDEBUG_LOC) {
1273             SDValue Ops[] = { Tmp1, DAG.getConstant(Line, MVT::i32),
1274                               DAG.getConstant(Col, MVT::i32),
1275                               DAG.getSrcValue(CU.getGV()) };
1276             Result = DAG.getNode(ISD::DEBUG_LOC, dl, MVT::Other, Ops, 4);
1277           } else {
1278             unsigned ID = DW->RecordSourceLine(Line, Col, CU);
1279             Result = DAG.getLabel(ISD::DBG_LABEL, dl, Tmp1, ID);
1280           }
1281         } else {
1282           Result = Tmp1;  // chain
1283         }
1284       } else {
1285         Result = Tmp1;  // chain
1286       }
1287       break;
1288     }
1289    case TargetLowering::Custom:
1290       Result = TLI.LowerOperation(Op, DAG);
1291       if (Result.getNode())
1292         break;
1293     case TargetLowering::Legal: {
1294       LegalizeAction Action = getTypeAction(Node->getOperand(1).getValueType());
1295       if (Action == Legal && Tmp1 == Node->getOperand(0))
1296         break;
1297
1298       SmallVector<SDValue, 8> Ops;
1299       Ops.push_back(Tmp1);
1300       if (Action == Legal) {
1301         Ops.push_back(Node->getOperand(1));  // line # must be legal.
1302         Ops.push_back(Node->getOperand(2));  // col # must be legal.
1303       } else {
1304         // Otherwise promote them.
1305         Ops.push_back(PromoteOp(Node->getOperand(1)));
1306         Ops.push_back(PromoteOp(Node->getOperand(2)));
1307       }
1308       Ops.push_back(Node->getOperand(3));  // filename must be legal.
1309       Ops.push_back(Node->getOperand(4));  // working dir # must be legal.
1310       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1311       break;
1312     }
1313     }
1314     break;
1315
1316   case ISD::DECLARE:
1317     assert(Node->getNumOperands() == 3 && "Invalid DECLARE node!");
1318     switch (TLI.getOperationAction(ISD::DECLARE, MVT::Other)) {
1319     default: assert(0 && "This action is not supported yet!");
1320     case TargetLowering::Legal:
1321       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1322       Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the address.
1323       Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the variable.
1324       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1325       break;
1326     case TargetLowering::Expand:
1327       Result = LegalizeOp(Node->getOperand(0));
1328       break;
1329     }
1330     break;
1331
1332   case ISD::DEBUG_LOC:
1333     assert(Node->getNumOperands() == 4 && "Invalid DEBUG_LOC node!");
1334     switch (TLI.getOperationAction(ISD::DEBUG_LOC, MVT::Other)) {
1335     default: assert(0 && "This action is not supported yet!");
1336     case TargetLowering::Legal: {
1337       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1338       if (Tmp1 == Node->getOperand(0))
1339         break;
1340       Tmp2 = Node->getOperand(1);
1341       Tmp3 = Node->getOperand(2);
1342       Tmp4 = Node->getOperand(3);
1343       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4);
1344       break;
1345     }
1346     }
1347     break;
1348
1349   case ISD::DBG_LABEL:
1350   case ISD::EH_LABEL:
1351     assert(Node->getNumOperands() == 1 && "Invalid LABEL node!");
1352     switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
1353     default: assert(0 && "This action is not supported yet!");
1354     case TargetLowering::Legal:
1355       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1356       Result = DAG.UpdateNodeOperands(Result, Tmp1);
1357       break;
1358     case TargetLowering::Expand:
1359       Result = LegalizeOp(Node->getOperand(0));
1360       break;
1361     }
1362     break;
1363
1364   case ISD::PREFETCH:
1365     assert(Node->getNumOperands() == 4 && "Invalid Prefetch node!");
1366     switch (TLI.getOperationAction(ISD::PREFETCH, MVT::Other)) {
1367     default: assert(0 && "This action is not supported yet!");
1368     case TargetLowering::Legal:
1369       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1370       Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the address.
1371       Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the rw specifier.
1372       Tmp4 = LegalizeOp(Node->getOperand(3));  // Legalize locality specifier.
1373       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4);
1374       break;
1375     case TargetLowering::Expand:
1376       // It's a noop.
1377       Result = LegalizeOp(Node->getOperand(0));
1378       break;
1379     }
1380     break;
1381
1382   case ISD::MEMBARRIER: {
1383     assert(Node->getNumOperands() == 6 && "Invalid MemBarrier node!");
1384     switch (TLI.getOperationAction(ISD::MEMBARRIER, MVT::Other)) {
1385     default: assert(0 && "This action is not supported yet!");
1386     case TargetLowering::Legal: {
1387       SDValue Ops[6];
1388       Ops[0] = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1389       for (int x = 1; x < 6; ++x) {
1390         Ops[x] = Node->getOperand(x);
1391       }
1392       Result = DAG.UpdateNodeOperands(Result, &Ops[0], 6);
1393       break;
1394     }
1395     case TargetLowering::Expand:
1396       //There is no libgcc call for this op
1397       Result = Node->getOperand(0);  // Noop
1398     break;
1399     }
1400     break;
1401   }
1402
1403   case ISD::ATOMIC_CMP_SWAP: {
1404     unsigned int num_operands = 4;
1405     assert(Node->getNumOperands() == num_operands && "Invalid Atomic node!");
1406     SDValue Ops[4];
1407     for (unsigned int x = 0; x < num_operands; ++x)
1408       Ops[x] = LegalizeOp(Node->getOperand(x));
1409     Result = DAG.UpdateNodeOperands(Result, &Ops[0], num_operands);
1410
1411     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1412       default: assert(0 && "This action is not supported yet!");
1413       case TargetLowering::Custom:
1414         Result = TLI.LowerOperation(Result, DAG);
1415         break;
1416       case TargetLowering::Legal:
1417         break;
1418     }
1419     AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1420     AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1421     return Result.getValue(Op.getResNo());
1422   }
1423   case ISD::ATOMIC_LOAD_ADD:
1424   case ISD::ATOMIC_LOAD_SUB:
1425   case ISD::ATOMIC_LOAD_AND:
1426   case ISD::ATOMIC_LOAD_OR:
1427   case ISD::ATOMIC_LOAD_XOR:
1428   case ISD::ATOMIC_LOAD_NAND:
1429   case ISD::ATOMIC_LOAD_MIN:
1430   case ISD::ATOMIC_LOAD_MAX:
1431   case ISD::ATOMIC_LOAD_UMIN:
1432   case ISD::ATOMIC_LOAD_UMAX:
1433   case ISD::ATOMIC_SWAP: {
1434     unsigned int num_operands = 3;
1435     assert(Node->getNumOperands() == num_operands && "Invalid Atomic node!");
1436     SDValue Ops[3];
1437     for (unsigned int x = 0; x < num_operands; ++x)
1438       Ops[x] = LegalizeOp(Node->getOperand(x));
1439     Result = DAG.UpdateNodeOperands(Result, &Ops[0], num_operands);
1440
1441     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1442     default: assert(0 && "This action is not supported yet!");
1443     case TargetLowering::Custom:
1444       Result = TLI.LowerOperation(Result, DAG);
1445       break;
1446     case TargetLowering::Legal:
1447       break;
1448     }
1449     AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1450     AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1451     return Result.getValue(Op.getResNo());
1452   }
1453   case ISD::Constant: {
1454     ConstantSDNode *CN = cast<ConstantSDNode>(Node);
1455     unsigned opAction =
1456       TLI.getOperationAction(ISD::Constant, CN->getValueType(0));
1457
1458     // We know we don't need to expand constants here, constants only have one
1459     // value and we check that it is fine above.
1460
1461     if (opAction == TargetLowering::Custom) {
1462       Tmp1 = TLI.LowerOperation(Result, DAG);
1463       if (Tmp1.getNode())
1464         Result = Tmp1;
1465     }
1466     break;
1467   }
1468   case ISD::ConstantFP: {
1469     // Spill FP immediates to the constant pool if the target cannot directly
1470     // codegen them.  Targets often have some immediate values that can be
1471     // efficiently generated into an FP register without a load.  We explicitly
1472     // leave these constants as ConstantFP nodes for the target to deal with.
1473     ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
1474
1475     switch (TLI.getOperationAction(ISD::ConstantFP, CFP->getValueType(0))) {
1476     default: assert(0 && "This action is not supported yet!");
1477     case TargetLowering::Legal:
1478       break;
1479     case TargetLowering::Custom:
1480       Tmp3 = TLI.LowerOperation(Result, DAG);
1481       if (Tmp3.getNode()) {
1482         Result = Tmp3;
1483         break;
1484       }
1485       // FALLTHROUGH
1486     case TargetLowering::Expand: {
1487       // Check to see if this FP immediate is already legal.
1488       bool isLegal = false;
1489       for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
1490              E = TLI.legal_fpimm_end(); I != E; ++I) {
1491         if (CFP->isExactlyValue(*I)) {
1492           isLegal = true;
1493           break;
1494         }
1495       }
1496       // If this is a legal constant, turn it into a TargetConstantFP node.
1497       if (isLegal)
1498         break;
1499       Result = ExpandConstantFP(CFP, true, DAG, TLI);
1500     }
1501     }
1502     break;
1503   }
1504   case ISD::TokenFactor:
1505     if (Node->getNumOperands() == 2) {
1506       Tmp1 = LegalizeOp(Node->getOperand(0));
1507       Tmp2 = LegalizeOp(Node->getOperand(1));
1508       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1509     } else if (Node->getNumOperands() == 3) {
1510       Tmp1 = LegalizeOp(Node->getOperand(0));
1511       Tmp2 = LegalizeOp(Node->getOperand(1));
1512       Tmp3 = LegalizeOp(Node->getOperand(2));
1513       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1514     } else {
1515       SmallVector<SDValue, 8> Ops;
1516       // Legalize the operands.
1517       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1518         Ops.push_back(LegalizeOp(Node->getOperand(i)));
1519       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1520     }
1521     break;
1522
1523   case ISD::FORMAL_ARGUMENTS:
1524   case ISD::CALL:
1525     // The only option for this is to custom lower it.
1526     Tmp3 = TLI.LowerOperation(Result.getValue(0), DAG);
1527     assert(Tmp3.getNode() && "Target didn't custom lower this node!");
1528     // A call within a calling sequence must be legalized to something
1529     // other than the normal CALLSEQ_END.  Violating this gets Legalize
1530     // into an infinite loop.
1531     assert ((!IsLegalizingCall ||
1532              Node->getOpcode() != ISD::CALL ||
1533              Tmp3.getNode()->getOpcode() != ISD::CALLSEQ_END) &&
1534             "Nested CALLSEQ_START..CALLSEQ_END not supported.");
1535
1536     // The number of incoming and outgoing values should match; unless the final
1537     // outgoing value is a flag.
1538     assert((Tmp3.getNode()->getNumValues() == Result.getNode()->getNumValues() ||
1539             (Tmp3.getNode()->getNumValues() == Result.getNode()->getNumValues() + 1 &&
1540              Tmp3.getNode()->getValueType(Tmp3.getNode()->getNumValues() - 1) ==
1541                MVT::Flag)) &&
1542            "Lowering call/formal_arguments produced unexpected # results!");
1543
1544     // Since CALL/FORMAL_ARGUMENTS nodes produce multiple values, make sure to
1545     // remember that we legalized all of them, so it doesn't get relegalized.
1546     for (unsigned i = 0, e = Tmp3.getNode()->getNumValues(); i != e; ++i) {
1547       if (Tmp3.getNode()->getValueType(i) == MVT::Flag)
1548         continue;
1549       Tmp1 = LegalizeOp(Tmp3.getValue(i));
1550       if (Op.getResNo() == i)
1551         Tmp2 = Tmp1;
1552       AddLegalizedOperand(SDValue(Node, i), Tmp1);
1553     }
1554     return Tmp2;
1555   case ISD::BUILD_VECTOR:
1556     switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
1557     default: assert(0 && "This action is not supported yet!");
1558     case TargetLowering::Custom:
1559       Tmp3 = TLI.LowerOperation(Result, DAG);
1560       if (Tmp3.getNode()) {
1561         Result = Tmp3;
1562         break;
1563       }
1564       // FALLTHROUGH
1565     case TargetLowering::Expand:
1566       Result = ExpandBUILD_VECTOR(Result.getNode());
1567       break;
1568     }
1569     break;
1570   case ISD::INSERT_VECTOR_ELT:
1571     Tmp1 = LegalizeOp(Node->getOperand(0));  // InVec
1572     Tmp3 = LegalizeOp(Node->getOperand(2));  // InEltNo
1573
1574     // The type of the value to insert may not be legal, even though the vector
1575     // type is legal.  Legalize/Promote accordingly.  We do not handle Expand
1576     // here.
1577     Tmp2 = LegalizeOp(Node->getOperand(1));
1578     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1579
1580     switch (TLI.getOperationAction(ISD::INSERT_VECTOR_ELT,
1581                                    Node->getValueType(0))) {
1582     default: assert(0 && "This action is not supported yet!");
1583     case TargetLowering::Legal:
1584       break;
1585     case TargetLowering::Custom:
1586       Tmp4 = TLI.LowerOperation(Result, DAG);
1587       if (Tmp4.getNode()) {
1588         Result = Tmp4;
1589         break;
1590       }
1591       // FALLTHROUGH
1592     case TargetLowering::Promote:
1593       // Fall thru for vector case
1594     case TargetLowering::Expand: {
1595       // If the insert index is a constant, codegen this as a scalar_to_vector,
1596       // then a shuffle that inserts it into the right position in the vector.
1597       if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Tmp3)) {
1598         // SCALAR_TO_VECTOR requires that the type of the value being inserted
1599         // match the element type of the vector being created, except for
1600         // integers in which case the inserted value can be over width.
1601         MVT EltVT = Op.getValueType().getVectorElementType();
1602         if (Tmp2.getValueType() == EltVT ||
1603             (EltVT.isInteger() && Tmp2.getValueType().bitsGE(EltVT))) {
1604           SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
1605                                       Tmp1.getValueType(), Tmp2);
1606
1607           unsigned NumElts = Tmp1.getValueType().getVectorNumElements();
1608           // We generate a shuffle of InVec and ScVec, so the shuffle mask
1609           // should be 0,1,2,3,4,5... with the appropriate element replaced with
1610           // elt 0 of the RHS.
1611           SmallVector<int, 8> ShufOps;
1612           for (unsigned i = 0; i != NumElts; ++i)
1613             ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts);
1614           
1615           Result = DAG.getVectorShuffle(Tmp1.getValueType(), dl, Tmp1, ScVec,
1616                                         &ShufOps[0]);
1617           Result = LegalizeOp(Result);
1618           break;
1619         }
1620       }
1621       Result = PerformInsertVectorEltInMemory(Tmp1, Tmp2, Tmp3, dl);
1622       break;
1623     }
1624     }
1625     break;
1626   case ISD::SCALAR_TO_VECTOR:
1627     Tmp1 = LegalizeOp(Node->getOperand(0));  // InVal
1628     Result = DAG.UpdateNodeOperands(Result, Tmp1);
1629     switch (TLI.getOperationAction(ISD::SCALAR_TO_VECTOR,
1630                                    Node->getValueType(0))) {
1631     default: assert(0 && "This action is not supported yet!");
1632     case TargetLowering::Legal:
1633       break;
1634     case TargetLowering::Custom:
1635       Tmp3 = TLI.LowerOperation(Result, DAG);
1636       if (Tmp3.getNode()) {
1637         Result = Tmp3;
1638         break;
1639       }
1640       // FALLTHROUGH
1641     case TargetLowering::Expand:
1642       Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
1643       break;
1644     }
1645     break;
1646   case ISD::VECTOR_SHUFFLE: {
1647     Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the input vectors,
1648     Tmp2 = LegalizeOp(Node->getOperand(1));   // but not the shuffle mask.
1649     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1650     MVT VT = Result.getValueType();
1651
1652     // Copy the Mask to a local SmallVector for use with isShuffleMaskLegal.
1653     SmallVector<int, 8> Mask;
1654     cast<ShuffleVectorSDNode>(Result)->getMask(Mask);
1655
1656     // Allow targets to custom lower the SHUFFLEs they support.
1657     switch (TLI.getOperationAction(ISD::VECTOR_SHUFFLE, VT)) {
1658     default: assert(0 && "Unknown operation action!");
1659     case TargetLowering::Legal:
1660       assert(TLI.isShuffleMaskLegal(Mask, VT) &&
1661              "vector shuffle should not be created if not legal!");
1662       break;
1663     case TargetLowering::Custom:
1664       Tmp3 = TLI.LowerOperation(Result, DAG);
1665       if (Tmp3.getNode()) {
1666         Result = Tmp3;
1667         break;
1668       }
1669       // FALLTHROUGH
1670     case TargetLowering::Expand: {
1671       MVT EltVT = VT.getVectorElementType();
1672       unsigned NumElems = VT.getVectorNumElements();
1673       SmallVector<SDValue, 8> Ops;
1674       for (unsigned i = 0; i != NumElems; ++i) {
1675         if (Mask[i] < 0) {
1676           Ops.push_back(DAG.getUNDEF(EltVT));
1677           continue;
1678         }
1679         unsigned Idx = Mask[i];
1680         if (Idx < NumElems)
1681           Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Tmp1,
1682                                     DAG.getIntPtrConstant(Idx)));
1683         else
1684           Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Tmp2,
1685                                     DAG.getIntPtrConstant(Idx - NumElems)));
1686       }
1687       Result = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], Ops.size());
1688       break;
1689     }
1690     case TargetLowering::Promote: {
1691       // Change base type to a different vector type.
1692       MVT OVT = Node->getValueType(0);
1693       MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
1694
1695       // Cast the two input vectors.
1696       Tmp1 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Tmp1);
1697       Tmp2 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Tmp2);
1698
1699       // Convert the shuffle mask to the right # elements.
1700       Result = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
1701       Result = DAG.getNode(ISD::BIT_CONVERT, dl, OVT, Result);
1702       break;
1703     }
1704     }
1705     break;
1706   }
1707   case ISD::EXTRACT_VECTOR_ELT:
1708     Tmp1 = Node->getOperand(0);
1709     Tmp2 = LegalizeOp(Node->getOperand(1));
1710     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1711     Result = ExpandEXTRACT_VECTOR_ELT(Result);
1712     break;
1713
1714   case ISD::EXTRACT_SUBVECTOR:
1715     Tmp1 = LegalizeOp(Node->getOperand(0));
1716     Tmp2 = LegalizeOp(Node->getOperand(1));
1717     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1718
1719     switch (TLI.getOperationAction(ISD::EXTRACT_SUBVECTOR,
1720                                    Node->getValueType(0))) {
1721     default: assert(0 && "Unknown operation action!");
1722     case TargetLowering::Legal:
1723       break;
1724     case TargetLowering::Custom:
1725       Tmp3 = TLI.LowerOperation(Result, DAG);
1726       if (Tmp3.getNode()) {
1727         Result = Tmp3;
1728         break;
1729       }
1730       // FALLTHROUGH
1731     case TargetLowering::Expand: {
1732       Result = ExpandExtractFromVectorThroughStack(Result);
1733       break;
1734     }
1735     }
1736     break;
1737
1738   case ISD::CONCAT_VECTORS: {
1739     // Legalize the operands.
1740     SmallVector<SDValue, 8> Ops;
1741     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1742       Ops.push_back(LegalizeOp(Node->getOperand(i)));
1743     Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1744
1745     switch (TLI.getOperationAction(ISD::CONCAT_VECTORS,
1746                                    Node->getValueType(0))) {
1747     default: assert(0 && "Unknown operation action!");
1748     case TargetLowering::Legal:
1749       break;
1750     case TargetLowering::Custom:
1751       Tmp3 = TLI.LowerOperation(Result, DAG);
1752       if (Tmp3.getNode()) {
1753         Result = Tmp3;
1754         break;
1755       }
1756       // FALLTHROUGH
1757     case TargetLowering::Expand: {
1758       // Use extract/insert/build vector for now. We might try to be
1759       // more clever later.
1760       MVT PtrVT = TLI.getPointerTy();
1761       SmallVector<SDValue, 8> Ops;
1762       unsigned NumOperands = Node->getNumOperands();
1763       for (unsigned i=0; i < NumOperands; ++i) {
1764         SDValue SubOp = Node->getOperand(i);
1765         MVT VVT = SubOp.getNode()->getValueType(0);
1766         MVT EltVT = VVT.getVectorElementType();
1767         unsigned NumSubElem = VVT.getVectorNumElements();
1768         for (unsigned j=0; j < NumSubElem; ++j) {
1769           Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, SubOp,
1770                                     DAG.getConstant(j, PtrVT)));
1771         }
1772       }
1773       return LegalizeOp(DAG.getNode(ISD::BUILD_VECTOR, dl,
1774                                     Node->getValueType(0),
1775                                     &Ops[0], Ops.size()));
1776     }
1777     }
1778     break;
1779   }
1780
1781   case ISD::CALLSEQ_START: {
1782     SDNode *CallEnd = FindCallEndFromCallStart(Node);
1783
1784     // Recursively Legalize all of the inputs of the call end that do not lead
1785     // to this call start.  This ensures that any libcalls that need be inserted
1786     // are inserted *before* the CALLSEQ_START.
1787     IsLegalizingCallArgs = true;
1788     {SmallPtrSet<SDNode*, 32> NodesLeadingTo;
1789     for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
1790       LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).getNode(), Node,
1791                                    NodesLeadingTo);
1792     }
1793     IsLegalizingCallArgs = false;
1794
1795     // Now that we legalized all of the inputs (which may have inserted
1796     // libcalls) create the new CALLSEQ_START node.
1797     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1798
1799     // Merge in the last call, to ensure that this call start after the last
1800     // call ended.
1801     if (LastCALLSEQ_END.getOpcode() != ISD::EntryToken) {
1802       Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1803                          Tmp1, LastCALLSEQ_END);
1804       Tmp1 = LegalizeOp(Tmp1);
1805     }
1806
1807     // Do not try to legalize the target-specific arguments (#1+).
1808     if (Tmp1 != Node->getOperand(0)) {
1809       SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1810       Ops[0] = Tmp1;
1811       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1812     }
1813
1814     // Remember that the CALLSEQ_START is legalized.
1815     AddLegalizedOperand(Op.getValue(0), Result);
1816     if (Node->getNumValues() == 2)    // If this has a flag result, remember it.
1817       AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1818
1819     // Now that the callseq_start and all of the non-call nodes above this call
1820     // sequence have been legalized, legalize the call itself.  During this
1821     // process, no libcalls can/will be inserted, guaranteeing that no calls
1822     // can overlap.
1823     assert(!IsLegalizingCall && "Inconsistent sequentialization of calls!");
1824     // Note that we are selecting this call!
1825     LastCALLSEQ_END = SDValue(CallEnd, 0);
1826     IsLegalizingCall = true;
1827
1828     // Legalize the call, starting from the CALLSEQ_END.
1829     LegalizeOp(LastCALLSEQ_END);
1830     assert(!IsLegalizingCall && "CALLSEQ_END should have cleared this!");
1831     return Result;
1832   }
1833   case ISD::CALLSEQ_END:
1834     // If the CALLSEQ_START node hasn't been legalized first, legalize it.  This
1835     // will cause this node to be legalized as well as handling libcalls right.
1836     if (LastCALLSEQ_END.getNode() != Node) {
1837       LegalizeOp(SDValue(FindCallStartFromCallEnd(Node), 0));
1838       DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
1839       assert(I != LegalizedNodes.end() &&
1840              "Legalizing the call start should have legalized this node!");
1841       return I->second;
1842     }
1843
1844     // Otherwise, the call start has been legalized and everything is going
1845     // according to plan.  Just legalize ourselves normally here.
1846     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1847     // Do not try to legalize the target-specific arguments (#1+), except for
1848     // an optional flag input.
1849     if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Flag){
1850       if (Tmp1 != Node->getOperand(0)) {
1851         SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1852         Ops[0] = Tmp1;
1853         Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1854       }
1855     } else {
1856       Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
1857       if (Tmp1 != Node->getOperand(0) ||
1858           Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
1859         SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1860         Ops[0] = Tmp1;
1861         Ops.back() = Tmp2;
1862         Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1863       }
1864     }
1865     assert(IsLegalizingCall && "Call sequence imbalance between start/end?");
1866     // This finishes up call legalization.
1867     IsLegalizingCall = false;
1868
1869     // If the CALLSEQ_END node has a flag, remember that we legalized it.
1870     AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1871     if (Node->getNumValues() == 2)
1872       AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1873     return Result.getValue(Op.getResNo());
1874   case ISD::DYNAMIC_STACKALLOC: {
1875     MVT VT = Node->getValueType(0);
1876     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1877     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
1878     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
1879     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1880
1881     Tmp1 = Result.getValue(0);
1882     Tmp2 = Result.getValue(1);
1883     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1884     default: assert(0 && "This action is not supported yet!");
1885     case TargetLowering::Expand: {
1886       unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1887       assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1888              " not tell us which reg is the stack pointer!");
1889       SDValue Chain = Tmp1.getOperand(0);
1890
1891       // Chain the dynamic stack allocation so that it doesn't modify the stack
1892       // pointer when other instructions are using the stack.
1893       Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
1894
1895       SDValue Size  = Tmp2.getOperand(1);
1896       SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
1897       Chain = SP.getValue(1);
1898       unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
1899       unsigned StackAlign =
1900         TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1901       if (Align > StackAlign)
1902         SP = DAG.getNode(ISD::AND, dl, VT, SP,
1903                          DAG.getConstant(-(uint64_t)Align, VT));
1904       Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size);       // Value
1905       Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);     // Output chain
1906
1907       Tmp2 = DAG.getCALLSEQ_END(Chain,  DAG.getIntPtrConstant(0, true),
1908                                 DAG.getIntPtrConstant(0, true), SDValue());
1909
1910       Tmp1 = LegalizeOp(Tmp1);
1911       Tmp2 = LegalizeOp(Tmp2);
1912       break;
1913     }
1914     case TargetLowering::Custom:
1915       Tmp3 = TLI.LowerOperation(Tmp1, DAG);
1916       if (Tmp3.getNode()) {
1917         Tmp1 = LegalizeOp(Tmp3);
1918         Tmp2 = LegalizeOp(Tmp3.getValue(1));
1919       }
1920       break;
1921     case TargetLowering::Legal:
1922       break;
1923     }
1924     // Since this op produce two values, make sure to remember that we
1925     // legalized both of them.
1926     AddLegalizedOperand(SDValue(Node, 0), Tmp1);
1927     AddLegalizedOperand(SDValue(Node, 1), Tmp2);
1928     return Op.getResNo() ? Tmp2 : Tmp1;
1929   }
1930   case ISD::INLINEASM: {
1931     SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1932     bool Changed = false;
1933     // Legalize all of the operands of the inline asm, in case they are nodes
1934     // that need to be expanded or something.  Note we skip the asm string and
1935     // all of the TargetConstant flags.
1936     SDValue Op = LegalizeOp(Ops[0]);
1937     Changed = Op != Ops[0];
1938     Ops[0] = Op;
1939
1940     bool HasInFlag = Ops.back().getValueType() == MVT::Flag;
1941     for (unsigned i = 2, e = Ops.size()-HasInFlag; i < e; ) {
1942       unsigned NumVals = InlineAsm::
1943         getNumOperandRegisters(cast<ConstantSDNode>(Ops[i])->getZExtValue());
1944       for (++i; NumVals; ++i, --NumVals) {
1945         SDValue Op = LegalizeOp(Ops[i]);
1946         if (Op != Ops[i]) {
1947           Changed = true;
1948           Ops[i] = Op;
1949         }
1950       }
1951     }
1952
1953     if (HasInFlag) {
1954       Op = LegalizeOp(Ops.back());
1955       Changed |= Op != Ops.back();
1956       Ops.back() = Op;
1957     }
1958
1959     if (Changed)
1960       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1961
1962     // INLINE asm returns a chain and flag, make sure to add both to the map.
1963     AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1964     AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1965     return Result.getValue(Op.getResNo());
1966   }
1967   case ISD::BR:
1968     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1969     // Ensure that libcalls are emitted before a branch.
1970     Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Tmp1, LastCALLSEQ_END);
1971     Tmp1 = LegalizeOp(Tmp1);
1972     LastCALLSEQ_END = DAG.getEntryNode();
1973
1974     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1975     break;
1976   case ISD::BRIND:
1977     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1978     // Ensure that libcalls are emitted before a branch.
1979     Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Tmp1, LastCALLSEQ_END);
1980     Tmp1 = LegalizeOp(Tmp1);
1981     LastCALLSEQ_END = DAG.getEntryNode();
1982
1983     Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
1984     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1985     break;
1986   case ISD::BR_JT:
1987     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1988     // Ensure that libcalls are emitted before a branch.
1989     Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Tmp1, LastCALLSEQ_END);
1990     Tmp1 = LegalizeOp(Tmp1);
1991     LastCALLSEQ_END = DAG.getEntryNode();
1992
1993     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the jumptable node.
1994     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1995
1996     switch (TLI.getOperationAction(ISD::BR_JT, MVT::Other)) {
1997     default: assert(0 && "This action is not supported yet!");
1998     case TargetLowering::Legal: break;
1999     case TargetLowering::Custom:
2000       Tmp1 = TLI.LowerOperation(Result, DAG);
2001       if (Tmp1.getNode()) Result = Tmp1;
2002       break;
2003     case TargetLowering::Expand: {
2004       SDValue Chain = Result.getOperand(0);
2005       SDValue Table = Result.getOperand(1);
2006       SDValue Index = Result.getOperand(2);
2007
2008       MVT PTy = TLI.getPointerTy();
2009       MachineFunction &MF = DAG.getMachineFunction();
2010       unsigned EntrySize = MF.getJumpTableInfo()->getEntrySize();
2011       Index= DAG.getNode(ISD::MUL, dl, PTy,
2012                          Index, DAG.getConstant(EntrySize, PTy));
2013       SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
2014
2015       MVT MemVT = MVT::getIntegerVT(EntrySize * 8);
2016       SDValue LD = DAG.getExtLoad(ISD::SEXTLOAD, dl, PTy, Chain, Addr,
2017                                   PseudoSourceValue::getJumpTable(), 0, MemVT);
2018       Addr = LD;
2019       if (TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2020         // For PIC, the sequence is:
2021         // BRIND(load(Jumptable + index) + RelocBase)
2022         // RelocBase can be JumpTable, GOT or some sort of global base.
2023         Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr,
2024                            TLI.getPICJumpTableRelocBase(Table, DAG));
2025       }
2026       Result = DAG.getNode(ISD::BRIND, dl, MVT::Other, LD.getValue(1), Addr);
2027     }
2028     }
2029     break;
2030   case ISD::BRCOND:
2031     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2032     // Ensure that libcalls are emitted before a return.
2033     Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Tmp1, LastCALLSEQ_END);
2034     Tmp1 = LegalizeOp(Tmp1);
2035     LastCALLSEQ_END = DAG.getEntryNode();
2036
2037     Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
2038
2039     // Basic block destination (Op#2) is always legal.
2040     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2041
2042     switch (TLI.getOperationAction(ISD::BRCOND, MVT::Other)) {
2043     default: assert(0 && "This action is not supported yet!");
2044     case TargetLowering::Legal: break;
2045     case TargetLowering::Custom:
2046       Tmp1 = TLI.LowerOperation(Result, DAG);
2047       if (Tmp1.getNode()) Result = Tmp1;
2048       break;
2049     case TargetLowering::Expand:
2050       // Expand brcond's setcc into its constituent parts and create a BR_CC
2051       // Node.
2052       if (Tmp2.getOpcode() == ISD::SETCC) {
2053         Result = DAG.getNode(ISD::BR_CC, dl, MVT::Other,
2054                              Tmp1, Tmp2.getOperand(2),
2055                              Tmp2.getOperand(0), Tmp2.getOperand(1),
2056                              Node->getOperand(2));
2057       } else {
2058         Result = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
2059                              DAG.getCondCode(ISD::SETNE), Tmp2,
2060                              DAG.getConstant(0, Tmp2.getValueType()),
2061                              Node->getOperand(2));
2062       }
2063       break;
2064     }
2065     break;
2066   case ISD::BR_CC:
2067     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2068     // Ensure that libcalls are emitted before a branch.
2069     Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Tmp1, LastCALLSEQ_END);
2070     Tmp1 = LegalizeOp(Tmp1);
2071     Tmp2 = Node->getOperand(2);              // LHS
2072     Tmp3 = Node->getOperand(3);              // RHS
2073     Tmp4 = Node->getOperand(1);              // CC
2074
2075     LegalizeSetCC(TLI.getSetCCResultType(Tmp2.getValueType()),
2076                   Tmp2, Tmp3, Tmp4, dl);
2077     LastCALLSEQ_END = DAG.getEntryNode();
2078
2079     // If we didn't get both a LHS and RHS back from LegalizeSetCC,
2080     // the LHS is a legal SETCC itself.  In this case, we need to compare
2081     // the result against zero to select between true and false values.
2082     if (Tmp3.getNode() == 0) {
2083       Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
2084       Tmp4 = DAG.getCondCode(ISD::SETNE);
2085     }
2086
2087     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp4, Tmp2, Tmp3,
2088                                     Node->getOperand(4));
2089
2090     switch (TLI.getOperationAction(ISD::BR_CC, Tmp3.getValueType())) {
2091     default: assert(0 && "Unexpected action for BR_CC!");
2092     case TargetLowering::Legal: break;
2093     case TargetLowering::Custom:
2094       Tmp4 = TLI.LowerOperation(Result, DAG);
2095       if (Tmp4.getNode()) Result = Tmp4;
2096       break;
2097     }
2098     break;
2099   case ISD::LOAD: {
2100     LoadSDNode *LD = cast<LoadSDNode>(Node);
2101     Tmp1 = LegalizeOp(LD->getChain());   // Legalize the chain.
2102     Tmp2 = LegalizeOp(LD->getBasePtr()); // Legalize the base pointer.
2103
2104     ISD::LoadExtType ExtType = LD->getExtensionType();
2105     if (ExtType == ISD::NON_EXTLOAD) {
2106       MVT VT = Node->getValueType(0);
2107       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
2108       Tmp3 = Result.getValue(0);
2109       Tmp4 = Result.getValue(1);
2110
2111       switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
2112       default: assert(0 && "This action is not supported yet!");
2113       case TargetLowering::Legal:
2114         // If this is an unaligned load and the target doesn't support it,
2115         // expand it.
2116         if (!TLI.allowsUnalignedMemoryAccesses()) {
2117           unsigned ABIAlignment = TLI.getTargetData()->
2118             getABITypeAlignment(LD->getMemoryVT().getTypeForMVT());
2119           if (LD->getAlignment() < ABIAlignment){
2120             Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()), DAG,
2121                                          TLI);
2122             Tmp3 = Result.getOperand(0);
2123             Tmp4 = Result.getOperand(1);
2124             Tmp3 = LegalizeOp(Tmp3);
2125             Tmp4 = LegalizeOp(Tmp4);
2126           }
2127         }
2128         break;
2129       case TargetLowering::Custom:
2130         Tmp1 = TLI.LowerOperation(Tmp3, DAG);
2131         if (Tmp1.getNode()) {
2132           Tmp3 = LegalizeOp(Tmp1);
2133           Tmp4 = LegalizeOp(Tmp1.getValue(1));
2134         }
2135         break;
2136       case TargetLowering::Promote: {
2137         // Only promote a load of vector type to another.
2138         assert(VT.isVector() && "Cannot promote this load!");
2139         // Change base type to a different vector type.
2140         MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
2141
2142         Tmp1 = DAG.getLoad(NVT, dl, Tmp1, Tmp2, LD->getSrcValue(),
2143                            LD->getSrcValueOffset(),
2144                            LD->isVolatile(), LD->getAlignment());
2145         Tmp3 = LegalizeOp(DAG.getNode(ISD::BIT_CONVERT, dl, VT, Tmp1));
2146         Tmp4 = LegalizeOp(Tmp1.getValue(1));
2147         break;
2148       }
2149       }
2150       // Since loads produce two values, make sure to remember that we
2151       // legalized both of them.
2152       AddLegalizedOperand(SDValue(Node, 0), Tmp3);
2153       AddLegalizedOperand(SDValue(Node, 1), Tmp4);
2154       return Op.getResNo() ? Tmp4 : Tmp3;
2155     } else {
2156       MVT SrcVT = LD->getMemoryVT();
2157       unsigned SrcWidth = SrcVT.getSizeInBits();
2158       int SVOffset = LD->getSrcValueOffset();
2159       unsigned Alignment = LD->getAlignment();
2160       bool isVolatile = LD->isVolatile();
2161
2162       if (SrcWidth != SrcVT.getStoreSizeInBits() &&
2163           // Some targets pretend to have an i1 loading operation, and actually
2164           // load an i8.  This trick is correct for ZEXTLOAD because the top 7
2165           // bits are guaranteed to be zero; it helps the optimizers understand
2166           // that these bits are zero.  It is also useful for EXTLOAD, since it
2167           // tells the optimizers that those bits are undefined.  It would be
2168           // nice to have an effective generic way of getting these benefits...
2169           // Until such a way is found, don't insist on promoting i1 here.
2170           (SrcVT != MVT::i1 ||
2171            TLI.getLoadExtAction(ExtType, MVT::i1) == TargetLowering::Promote)) {
2172         // Promote to a byte-sized load if not loading an integral number of
2173         // bytes.  For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
2174         unsigned NewWidth = SrcVT.getStoreSizeInBits();
2175         MVT NVT = MVT::getIntegerVT(NewWidth);
2176         SDValue Ch;
2177
2178         // The extra bits are guaranteed to be zero, since we stored them that
2179         // way.  A zext load from NVT thus automatically gives zext from SrcVT.
2180
2181         ISD::LoadExtType NewExtType =
2182           ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
2183
2184         Result = DAG.getExtLoad(NewExtType, dl, Node->getValueType(0),
2185                                 Tmp1, Tmp2, LD->getSrcValue(), SVOffset,
2186                                 NVT, isVolatile, Alignment);
2187
2188         Ch = Result.getValue(1); // The chain.
2189
2190         if (ExtType == ISD::SEXTLOAD)
2191           // Having the top bits zero doesn't help when sign extending.
2192           Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
2193                                Result.getValueType(),
2194                                Result, DAG.getValueType(SrcVT));
2195         else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
2196           // All the top bits are guaranteed to be zero - inform the optimizers.
2197           Result = DAG.getNode(ISD::AssertZext, dl,
2198                                Result.getValueType(), Result,
2199                                DAG.getValueType(SrcVT));
2200
2201         Tmp1 = LegalizeOp(Result);
2202         Tmp2 = LegalizeOp(Ch);
2203       } else if (SrcWidth & (SrcWidth - 1)) {
2204         // If not loading a power-of-2 number of bits, expand as two loads.
2205         assert(SrcVT.isExtended() && !SrcVT.isVector() &&
2206                "Unsupported extload!");
2207         unsigned RoundWidth = 1 << Log2_32(SrcWidth);
2208         assert(RoundWidth < SrcWidth);
2209         unsigned ExtraWidth = SrcWidth - RoundWidth;
2210         assert(ExtraWidth < RoundWidth);
2211         assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
2212                "Load size not an integral number of bytes!");
2213         MVT RoundVT = MVT::getIntegerVT(RoundWidth);
2214         MVT ExtraVT = MVT::getIntegerVT(ExtraWidth);
2215         SDValue Lo, Hi, Ch;
2216         unsigned IncrementSize;
2217
2218         if (TLI.isLittleEndian()) {
2219           // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
2220           // Load the bottom RoundWidth bits.
2221           Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl,
2222                               Node->getValueType(0), Tmp1, Tmp2,
2223                               LD->getSrcValue(), SVOffset, RoundVT, isVolatile,
2224                               Alignment);
2225
2226           // Load the remaining ExtraWidth bits.
2227           IncrementSize = RoundWidth / 8;
2228           Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
2229                              DAG.getIntPtrConstant(IncrementSize));
2230           Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Tmp1, Tmp2,
2231                               LD->getSrcValue(), SVOffset + IncrementSize,
2232                               ExtraVT, isVolatile,
2233                               MinAlign(Alignment, IncrementSize));
2234
2235           // Build a factor node to remember that this load is independent of the
2236           // other one.
2237           Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
2238                            Hi.getValue(1));
2239
2240           // Move the top bits to the right place.
2241           Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
2242                            DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
2243
2244           // Join the hi and lo parts.
2245           Result = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
2246         } else {
2247           // Big endian - avoid unaligned loads.
2248           // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
2249           // Load the top RoundWidth bits.
2250           Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Tmp1, Tmp2,
2251                               LD->getSrcValue(), SVOffset, RoundVT, isVolatile,
2252                               Alignment);
2253
2254           // Load the remaining ExtraWidth bits.
2255           IncrementSize = RoundWidth / 8;
2256           Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
2257                              DAG.getIntPtrConstant(IncrementSize));
2258           Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl,
2259                               Node->getValueType(0), Tmp1, Tmp2,
2260                               LD->getSrcValue(), SVOffset + IncrementSize,
2261                               ExtraVT, isVolatile,
2262                               MinAlign(Alignment, IncrementSize));
2263
2264           // Build a factor node to remember that this load is independent of the
2265           // other one.
2266           Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
2267                            Hi.getValue(1));
2268
2269           // Move the top bits to the right place.
2270           Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
2271                            DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
2272
2273           // Join the hi and lo parts.
2274           Result = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
2275         }
2276
2277         Tmp1 = LegalizeOp(Result);
2278         Tmp2 = LegalizeOp(Ch);
2279       } else {
2280         switch (TLI.getLoadExtAction(ExtType, SrcVT)) {
2281         default: assert(0 && "This action is not supported yet!");
2282         case TargetLowering::Custom:
2283           isCustom = true;
2284           // FALLTHROUGH
2285         case TargetLowering::Legal:
2286           Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
2287           Tmp1 = Result.getValue(0);
2288           Tmp2 = Result.getValue(1);
2289
2290           if (isCustom) {
2291             Tmp3 = TLI.LowerOperation(Result, DAG);
2292             if (Tmp3.getNode()) {
2293               Tmp1 = LegalizeOp(Tmp3);
2294               Tmp2 = LegalizeOp(Tmp3.getValue(1));
2295             }
2296           } else {
2297             // If this is an unaligned load and the target doesn't support it,
2298             // expand it.
2299             if (!TLI.allowsUnalignedMemoryAccesses()) {
2300               unsigned ABIAlignment = TLI.getTargetData()->
2301                 getABITypeAlignment(LD->getMemoryVT().getTypeForMVT());
2302               if (LD->getAlignment() < ABIAlignment){
2303                 Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()), DAG,
2304                                              TLI);
2305                 Tmp1 = Result.getOperand(0);
2306                 Tmp2 = Result.getOperand(1);
2307                 Tmp1 = LegalizeOp(Tmp1);
2308                 Tmp2 = LegalizeOp(Tmp2);
2309               }
2310             }
2311           }
2312           break;
2313         case TargetLowering::Expand:
2314           // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
2315           if (SrcVT == MVT::f32 && Node->getValueType(0) == MVT::f64) {
2316             SDValue Load = DAG.getLoad(SrcVT, dl, Tmp1, Tmp2, LD->getSrcValue(),
2317                                          LD->getSrcValueOffset(),
2318                                          LD->isVolatile(), LD->getAlignment());
2319             Result = DAG.getNode(ISD::FP_EXTEND, dl,
2320                                  Node->getValueType(0), Load);
2321             Tmp1 = LegalizeOp(Result);  // Relegalize new nodes.
2322             Tmp2 = LegalizeOp(Load.getValue(1));
2323             break;
2324           }
2325           assert(ExtType != ISD::EXTLOAD &&"EXTLOAD should always be supported!");
2326           // Turn the unsupported load into an EXTLOAD followed by an explicit
2327           // zero/sign extend inreg.
2328           Result = DAG.getExtLoad(ISD::EXTLOAD, dl, Node->getValueType(0),
2329                                   Tmp1, Tmp2, LD->getSrcValue(),
2330                                   LD->getSrcValueOffset(), SrcVT,
2331                                   LD->isVolatile(), LD->getAlignment());
2332           SDValue ValRes;
2333           if (ExtType == ISD::SEXTLOAD)
2334             ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
2335                                  Result.getValueType(),
2336                                  Result, DAG.getValueType(SrcVT));
2337           else
2338             ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT);
2339           Tmp1 = LegalizeOp(ValRes);  // Relegalize new nodes.
2340           Tmp2 = LegalizeOp(Result.getValue(1));  // Relegalize new nodes.
2341           break;
2342         }
2343       }
2344
2345       // Since loads produce two values, make sure to remember that we legalized
2346       // both of them.
2347       AddLegalizedOperand(SDValue(Node, 0), Tmp1);
2348       AddLegalizedOperand(SDValue(Node, 1), Tmp2);
2349       return Op.getResNo() ? Tmp2 : Tmp1;
2350     }
2351   }
2352   case ISD::EXTRACT_ELEMENT: {
2353     MVT OpTy = Node->getOperand(0).getValueType();
2354     if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
2355       // 1 -> Hi
2356       Result = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0),
2357                            DAG.getConstant(OpTy.getSizeInBits()/2,
2358                                            TLI.getShiftAmountTy()));
2359       Result = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Result);
2360     } else {
2361       // 0 -> Lo
2362       Result = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
2363                            Node->getOperand(0));
2364     }
2365     break;
2366   }
2367
2368   case ISD::CopyToReg:
2369     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2370
2371     // Legalize the incoming value (must be a legal type).
2372     Tmp2 = LegalizeOp(Node->getOperand(2));
2373     if (Node->getNumValues() == 1) {
2374       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2);
2375     } else {
2376       assert(Node->getNumValues() == 2 && "Unknown CopyToReg");
2377       if (Node->getNumOperands() == 4) {
2378         Tmp3 = LegalizeOp(Node->getOperand(3));
2379         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2,
2380                                         Tmp3);
2381       } else {
2382         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
2383       }
2384
2385       // Since this produces two values, make sure to remember that we legalized
2386       // both of them.
2387       AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
2388       AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
2389       return Result;
2390     }
2391     break;
2392
2393   case ISD::RET:
2394     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2395
2396     // Ensure that libcalls are emitted before a return.
2397     Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Tmp1, LastCALLSEQ_END);
2398     Tmp1 = LegalizeOp(Tmp1);
2399     LastCALLSEQ_END = DAG.getEntryNode();
2400
2401     switch (Node->getNumOperands()) {
2402     case 3:  // ret val
2403       Tmp2 = Node->getOperand(1);
2404       Tmp3 = Node->getOperand(2);  // Signness
2405       Result = DAG.UpdateNodeOperands(Result, Tmp1, LegalizeOp(Tmp2), Tmp3);
2406       break;
2407     case 1:  // ret void
2408       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2409       break;
2410     default: { // ret <values>
2411       SmallVector<SDValue, 8> NewValues;
2412       NewValues.push_back(Tmp1);
2413       for (unsigned i = 1, e = Node->getNumOperands(); i < e; i += 2) {
2414         NewValues.push_back(LegalizeOp(Node->getOperand(i)));
2415         NewValues.push_back(Node->getOperand(i+1));
2416       }
2417       Result = DAG.UpdateNodeOperands(Result, &NewValues[0],NewValues.size());
2418       break;
2419     }
2420     }
2421
2422     switch (TLI.getOperationAction(Result.getOpcode(), MVT::Other)) {
2423     default: assert(0 && "This action is not supported yet!");
2424     case TargetLowering::Legal: break;
2425     case TargetLowering::Custom:
2426       Tmp1 = TLI.LowerOperation(Result, DAG);
2427       if (Tmp1.getNode()) Result = Tmp1;
2428       break;
2429     }
2430     break;
2431   case ISD::STORE: {
2432     StoreSDNode *ST = cast<StoreSDNode>(Node);
2433     Tmp1 = LegalizeOp(ST->getChain());    // Legalize the chain.
2434     Tmp2 = LegalizeOp(ST->getBasePtr());  // Legalize the pointer.
2435     int SVOffset = ST->getSrcValueOffset();
2436     unsigned Alignment = ST->getAlignment();
2437     bool isVolatile = ST->isVolatile();
2438
2439     if (!ST->isTruncatingStore()) {
2440       // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
2441       // FIXME: We shouldn't do this for TargetConstantFP's.
2442       // FIXME: move this to the DAG Combiner!  Note that we can't regress due
2443       // to phase ordering between legalized code and the dag combiner.  This
2444       // probably means that we need to integrate dag combiner and legalizer
2445       // together.
2446       // We generally can't do this one for long doubles.
2447       if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
2448         if (CFP->getValueType(0) == MVT::f32 &&
2449             getTypeAction(MVT::i32) == Legal) {
2450           Tmp3 = DAG.getConstant(CFP->getValueAPF().
2451                                           bitcastToAPInt().zextOrTrunc(32),
2452                                   MVT::i32);
2453           Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
2454                                 SVOffset, isVolatile, Alignment);
2455           break;
2456         } else if (CFP->getValueType(0) == MVT::f64) {
2457           // If this target supports 64-bit registers, do a single 64-bit store.
2458           if (getTypeAction(MVT::i64) == Legal) {
2459             Tmp3 = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
2460                                      zextOrTrunc(64), MVT::i64);
2461             Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
2462                                   SVOffset, isVolatile, Alignment);
2463             break;
2464           } else if (getTypeAction(MVT::i32) == Legal && !ST->isVolatile()) {
2465             // Otherwise, if the target supports 32-bit registers, use 2 32-bit
2466             // stores.  If the target supports neither 32- nor 64-bits, this
2467             // xform is certainly not worth it.
2468             const APInt &IntVal =CFP->getValueAPF().bitcastToAPInt();
2469             SDValue Lo = DAG.getConstant(APInt(IntVal).trunc(32), MVT::i32);
2470             SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), MVT::i32);
2471             if (TLI.isBigEndian()) std::swap(Lo, Hi);
2472
2473             Lo = DAG.getStore(Tmp1, dl, Lo, Tmp2, ST->getSrcValue(),
2474                               SVOffset, isVolatile, Alignment);
2475             Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
2476                                DAG.getIntPtrConstant(4));
2477             Hi = DAG.getStore(Tmp1, dl, Hi, Tmp2, ST->getSrcValue(), SVOffset+4,
2478                               isVolatile, MinAlign(Alignment, 4U));
2479
2480             Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
2481             break;
2482           }
2483         }
2484       }
2485
2486       {
2487         Tmp3 = LegalizeOp(ST->getValue());
2488         Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
2489                                         ST->getOffset());
2490
2491         MVT VT = Tmp3.getValueType();
2492         switch (TLI.getOperationAction(ISD::STORE, VT)) {
2493         default: assert(0 && "This action is not supported yet!");
2494         case TargetLowering::Legal:
2495           // If this is an unaligned store and the target doesn't support it,
2496           // expand it.
2497           if (!TLI.allowsUnalignedMemoryAccesses()) {
2498             unsigned ABIAlignment = TLI.getTargetData()->
2499               getABITypeAlignment(ST->getMemoryVT().getTypeForMVT());
2500             if (ST->getAlignment() < ABIAlignment)
2501               Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()), DAG,
2502                                             TLI);
2503           }
2504           break;
2505         case TargetLowering::Custom:
2506           Tmp1 = TLI.LowerOperation(Result, DAG);
2507           if (Tmp1.getNode()) Result = Tmp1;
2508           break;
2509         case TargetLowering::Promote:
2510           assert(VT.isVector() && "Unknown legal promote case!");
2511           Tmp3 = DAG.getNode(ISD::BIT_CONVERT, dl,
2512                              TLI.getTypeToPromoteTo(ISD::STORE, VT), Tmp3);
2513           Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2,
2514                                 ST->getSrcValue(), SVOffset, isVolatile,
2515                                 Alignment);
2516           break;
2517         }
2518         break;
2519       }
2520     } else {
2521       Tmp3 = LegalizeOp(ST->getValue());
2522
2523       MVT StVT = ST->getMemoryVT();
2524       unsigned StWidth = StVT.getSizeInBits();
2525
2526       if (StWidth != StVT.getStoreSizeInBits()) {
2527         // Promote to a byte-sized store with upper bits zero if not
2528         // storing an integral number of bytes.  For example, promote
2529         // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
2530         MVT NVT = MVT::getIntegerVT(StVT.getStoreSizeInBits());
2531         Tmp3 = DAG.getZeroExtendInReg(Tmp3, dl, StVT);
2532         Result = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
2533                                    SVOffset, NVT, isVolatile, Alignment);
2534       } else if (StWidth & (StWidth - 1)) {
2535         // If not storing a power-of-2 number of bits, expand as two stores.
2536         assert(StVT.isExtended() && !StVT.isVector() &&
2537                "Unsupported truncstore!");
2538         unsigned RoundWidth = 1 << Log2_32(StWidth);
2539         assert(RoundWidth < StWidth);
2540         unsigned ExtraWidth = StWidth - RoundWidth;
2541         assert(ExtraWidth < RoundWidth);
2542         assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
2543                "Store size not an integral number of bytes!");
2544         MVT RoundVT = MVT::getIntegerVT(RoundWidth);
2545         MVT ExtraVT = MVT::getIntegerVT(ExtraWidth);
2546         SDValue Lo, Hi;
2547         unsigned IncrementSize;
2548
2549         if (TLI.isLittleEndian()) {
2550           // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
2551           // Store the bottom RoundWidth bits.
2552           Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
2553                                  SVOffset, RoundVT,
2554                                  isVolatile, Alignment);
2555
2556           // Store the remaining ExtraWidth bits.
2557           IncrementSize = RoundWidth / 8;
2558           Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
2559                              DAG.getIntPtrConstant(IncrementSize));
2560           Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
2561                            DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
2562           Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2, ST->getSrcValue(),
2563                                  SVOffset + IncrementSize, ExtraVT, isVolatile,
2564                                  MinAlign(Alignment, IncrementSize));
2565         } else {
2566           // Big endian - avoid unaligned stores.
2567           // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
2568           // Store the top RoundWidth bits.
2569           Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
2570                            DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
2571           Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2, ST->getSrcValue(),
2572                                  SVOffset, RoundVT, isVolatile, Alignment);
2573
2574           // Store the remaining ExtraWidth bits.
2575           IncrementSize = RoundWidth / 8;
2576           Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
2577                              DAG.getIntPtrConstant(IncrementSize));
2578           Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
2579                                  SVOffset + IncrementSize, ExtraVT, isVolatile,
2580                                  MinAlign(Alignment, IncrementSize));
2581         }
2582
2583         // The order of the stores doesn't matter.
2584         Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
2585       } else {
2586         if (Tmp1 != ST->getChain() || Tmp3 != ST->getValue() ||
2587             Tmp2 != ST->getBasePtr())
2588           Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
2589                                           ST->getOffset());
2590
2591         switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) {
2592         default: assert(0 && "This action is not supported yet!");
2593         case TargetLowering::Legal:
2594           // If this is an unaligned store and the target doesn't support it,
2595           // expand it.
2596           if (!TLI.allowsUnalignedMemoryAccesses()) {
2597             unsigned ABIAlignment = TLI.getTargetData()->
2598               getABITypeAlignment(ST->getMemoryVT().getTypeForMVT());
2599             if (ST->getAlignment() < ABIAlignment)
2600               Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()), DAG,
2601                                             TLI);
2602           }
2603           break;
2604         case TargetLowering::Custom:
2605           Result = TLI.LowerOperation(Result, DAG);
2606           break;
2607         case Expand:
2608           // TRUNCSTORE:i16 i32 -> STORE i16
2609           assert(isTypeLegal(StVT) && "Do not know how to expand this store!");
2610           Tmp3 = DAG.getNode(ISD::TRUNCATE, dl, StVT, Tmp3);
2611           Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
2612                                 SVOffset, isVolatile, Alignment);
2613           break;
2614         }
2615       }
2616     }
2617     break;
2618   }
2619   case ISD::PCMARKER:
2620     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2621     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
2622     break;
2623   case ISD::STACKSAVE:
2624     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2625     Result = DAG.UpdateNodeOperands(Result, Tmp1);
2626     Tmp1 = Result.getValue(0);
2627     Tmp2 = Result.getValue(1);
2628
2629     switch (TLI.getOperationAction(ISD::STACKSAVE, MVT::Other)) {
2630     default: assert(0 && "This action is not supported yet!");
2631     case TargetLowering::Legal: break;
2632     case TargetLowering::Custom:
2633       Tmp3 = TLI.LowerOperation(Result, DAG);
2634       if (Tmp3.getNode()) {
2635         Tmp1 = LegalizeOp(Tmp3);
2636         Tmp2 = LegalizeOp(Tmp3.getValue(1));
2637       }
2638       break;
2639     case TargetLowering::Expand:
2640       // Expand to CopyFromReg if the target set
2641       // StackPointerRegisterToSaveRestore.
2642       if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2643         Tmp1 = DAG.getCopyFromReg(Result.getOperand(0), dl, SP,
2644                                   Node->getValueType(0));
2645         Tmp2 = Tmp1.getValue(1);
2646       } else {
2647         Tmp1 = DAG.getUNDEF(Node->getValueType(0));
2648         Tmp2 = Node->getOperand(0);
2649       }
2650       break;
2651     }
2652
2653     // Since stacksave produce two values, make sure to remember that we
2654     // legalized both of them.
2655     AddLegalizedOperand(SDValue(Node, 0), Tmp1);
2656     AddLegalizedOperand(SDValue(Node, 1), Tmp2);
2657     return Op.getResNo() ? Tmp2 : Tmp1;
2658
2659   case ISD::STACKRESTORE:
2660     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2661     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2662     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2663
2664     switch (TLI.getOperationAction(ISD::STACKRESTORE, MVT::Other)) {
2665     default: assert(0 && "This action is not supported yet!");
2666     case TargetLowering::Legal: break;
2667     case TargetLowering::Custom:
2668       Tmp1 = TLI.LowerOperation(Result, DAG);
2669       if (Tmp1.getNode()) Result = Tmp1;
2670       break;
2671     case TargetLowering::Expand:
2672       // Expand to CopyToReg if the target set
2673       // StackPointerRegisterToSaveRestore.
2674       if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2675         Result = DAG.getCopyToReg(Tmp1, dl, SP, Tmp2);
2676       } else {
2677         Result = Tmp1;
2678       }
2679       break;
2680     }
2681     break;
2682
2683   case ISD::READCYCLECOUNTER:
2684     Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain
2685     Result = DAG.UpdateNodeOperands(Result, Tmp1);
2686     switch (TLI.getOperationAction(ISD::READCYCLECOUNTER,
2687                                    Node->getValueType(0))) {
2688     default: assert(0 && "This action is not supported yet!");
2689     case TargetLowering::Legal:
2690       Tmp1 = Result.getValue(0);
2691       Tmp2 = Result.getValue(1);
2692       break;
2693     case TargetLowering::Custom:
2694       Result = TLI.LowerOperation(Result, DAG);
2695       Tmp1 = LegalizeOp(Result.getValue(0));
2696       Tmp2 = LegalizeOp(Result.getValue(1));
2697       break;
2698     }
2699
2700     // Since rdcc produce two values, make sure to remember that we legalized
2701     // both of them.
2702     AddLegalizedOperand(SDValue(Node, 0), Tmp1);
2703     AddLegalizedOperand(SDValue(Node, 1), Tmp2);
2704     return Result;
2705
2706   case ISD::SELECT:
2707     Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
2708     Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
2709     Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
2710
2711     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2712
2713     switch (TLI.getOperationAction(ISD::SELECT, Tmp2.getValueType())) {
2714     default: assert(0 && "This action is not supported yet!");
2715     case TargetLowering::Legal: break;
2716     case TargetLowering::Custom: {
2717       Tmp1 = TLI.LowerOperation(Result, DAG);
2718       if (Tmp1.getNode()) Result = Tmp1;
2719       break;
2720     }
2721     case TargetLowering::Expand:
2722       if (Tmp1.getOpcode() == ISD::SETCC) {
2723         Result = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1),
2724                               Tmp2, Tmp3,
2725                               cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
2726       } else {
2727         Result = DAG.getSelectCC(dl, Tmp1,
2728                                  DAG.getConstant(0, Tmp1.getValueType()),
2729                                  Tmp2, Tmp3, ISD::SETNE);
2730       }
2731       break;
2732     case TargetLowering::Promote: {
2733       MVT NVT =
2734         TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
2735       unsigned ExtOp, TruncOp;
2736       if (Tmp2.getValueType().isVector()) {
2737         ExtOp   = ISD::BIT_CONVERT;
2738         TruncOp = ISD::BIT_CONVERT;
2739       } else if (Tmp2.getValueType().isInteger()) {
2740         ExtOp   = ISD::ANY_EXTEND;
2741         TruncOp = ISD::TRUNCATE;
2742       } else {
2743         ExtOp   = ISD::FP_EXTEND;
2744         TruncOp = ISD::FP_ROUND;
2745       }
2746       // Promote each of the values to the new type.
2747       Tmp2 = DAG.getNode(ExtOp, dl, NVT, Tmp2);
2748       Tmp3 = DAG.getNode(ExtOp, dl, NVT, Tmp3);
2749       // Perform the larger operation, then round down.
2750       Result = DAG.getNode(ISD::SELECT, dl, NVT, Tmp1, Tmp2, Tmp3);
2751       if (TruncOp != ISD::FP_ROUND)
2752         Result = DAG.getNode(TruncOp, dl, Node->getValueType(0), Result);
2753       else
2754         Result = DAG.getNode(TruncOp, dl, Node->getValueType(0), Result,
2755                              DAG.getIntPtrConstant(0));
2756       break;
2757     }
2758     }
2759     break;
2760   case ISD::SELECT_CC: {
2761     Tmp1 = Node->getOperand(0);               // LHS
2762     Tmp2 = Node->getOperand(1);               // RHS
2763     Tmp3 = LegalizeOp(Node->getOperand(2));   // True
2764     Tmp4 = LegalizeOp(Node->getOperand(3));   // False
2765     SDValue CC = Node->getOperand(4);
2766
2767     LegalizeSetCC(TLI.getSetCCResultType(Tmp1.getValueType()),
2768                   Tmp1, Tmp2, CC, dl);
2769
2770     // If we didn't get both a LHS and RHS back from LegalizeSetCC,
2771     // the LHS is a legal SETCC itself.  In this case, we need to compare
2772     // the result against zero to select between true and false values.
2773     if (Tmp2.getNode() == 0) {
2774       Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
2775       CC = DAG.getCondCode(ISD::SETNE);
2776     }
2777     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4, CC);
2778
2779     // Everything is legal, see if we should expand this op or something.
2780     switch (TLI.getOperationAction(ISD::SELECT_CC, Tmp3.getValueType())) {
2781     default: assert(0 && "This action is not supported yet!");
2782     case TargetLowering::Legal: break;
2783     case TargetLowering::Custom:
2784       Tmp1 = TLI.LowerOperation(Result, DAG);
2785       if (Tmp1.getNode()) Result = Tmp1;
2786       break;
2787     }
2788     break;
2789   }
2790   case ISD::SETCC:
2791     Tmp1 = Node->getOperand(0);
2792     Tmp2 = Node->getOperand(1);
2793     Tmp3 = Node->getOperand(2);
2794     LegalizeSetCC(Node->getValueType(0), Tmp1, Tmp2, Tmp3, dl);
2795
2796     // If we had to Expand the SetCC operands into a SELECT node, then it may
2797     // not always be possible to return a true LHS & RHS.  In this case, just
2798     // return the value we legalized, returned in the LHS
2799     if (Tmp2.getNode() == 0) {
2800       Result = Tmp1;
2801       break;
2802     }
2803
2804     switch (TLI.getOperationAction(ISD::SETCC, Tmp1.getValueType())) {
2805     default: assert(0 && "Cannot handle this action for SETCC yet!");
2806     case TargetLowering::Custom:
2807       isCustom = true;
2808       // FALLTHROUGH.
2809     case TargetLowering::Legal:
2810       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2811       if (isCustom) {
2812         Tmp4 = TLI.LowerOperation(Result, DAG);
2813         if (Tmp4.getNode()) Result = Tmp4;
2814       }
2815       break;
2816     case TargetLowering::Promote: {
2817       // First step, figure out the appropriate operation to use.
2818       // Allow SETCC to not be supported for all legal data types
2819       // Mostly this targets FP
2820       MVT NewInTy = Node->getOperand(0).getValueType();
2821       MVT OldVT = NewInTy; OldVT = OldVT;
2822
2823       // Scan for the appropriate larger type to use.
2824       while (1) {
2825         NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT()+1);
2826
2827         assert(NewInTy.isInteger() == OldVT.isInteger() &&
2828                "Fell off of the edge of the integer world");
2829         assert(NewInTy.isFloatingPoint() == OldVT.isFloatingPoint() &&
2830                "Fell off of the edge of the floating point world");
2831
2832         // If the target supports SETCC of this type, use it.
2833         if (TLI.isOperationLegalOrCustom(ISD::SETCC, NewInTy))
2834           break;
2835       }
2836       if (NewInTy.isInteger())
2837         assert(0 && "Cannot promote Legal Integer SETCC yet");
2838       else {
2839         Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NewInTy, Tmp1);
2840         Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NewInTy, Tmp2);
2841       }
2842       Tmp1 = LegalizeOp(Tmp1);
2843       Tmp2 = LegalizeOp(Tmp2);
2844       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2845       Result = LegalizeOp(Result);
2846       break;
2847     }
2848     case TargetLowering::Expand:
2849       // Expand a setcc node into a select_cc of the same condition, lhs, and
2850       // rhs that selects between const 1 (true) and const 0 (false).
2851       MVT VT = Node->getValueType(0);
2852       Result = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
2853                            DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2854                            Tmp3);
2855       break;
2856     }
2857     break;
2858   case ISD::VSETCC: {
2859     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2860     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
2861     SDValue CC = Node->getOperand(2);
2862
2863     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, CC);
2864
2865     // Everything is legal, see if we should expand this op or something.
2866     switch (TLI.getOperationAction(ISD::VSETCC, Tmp1.getValueType())) {
2867     default: assert(0 && "This action is not supported yet!");
2868     case TargetLowering::Legal: break;
2869     case TargetLowering::Custom:
2870       Tmp1 = TLI.LowerOperation(Result, DAG);
2871       if (Tmp1.getNode()) Result = Tmp1;
2872       break;
2873     case TargetLowering::Expand: {
2874       // Unroll into a nasty set of scalar code for now.
2875       MVT VT = Node->getValueType(0);
2876       unsigned NumElems = VT.getVectorNumElements();
2877       MVT EltVT = VT.getVectorElementType();
2878       MVT TmpEltVT = Tmp1.getValueType().getVectorElementType();
2879       SmallVector<SDValue, 8> Ops(NumElems);
2880       for (unsigned i = 0; i < NumElems; ++i) {
2881         SDValue In1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT,
2882                                   Tmp1, DAG.getIntPtrConstant(i));
2883         Ops[i] = DAG.getNode(ISD::SETCC, dl, TLI.getSetCCResultType(TmpEltVT),
2884                              In1, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
2885                                               TmpEltVT, Tmp2,
2886                                               DAG.getIntPtrConstant(i)),
2887                              CC);
2888         Ops[i] = DAG.getNode(ISD::SELECT, dl, EltVT, Ops[i],
2889                              DAG.getConstant(APInt::getAllOnesValue
2890                                              (EltVT.getSizeInBits()), EltVT),
2891                              DAG.getConstant(0, EltVT));
2892       }
2893       Result = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], NumElems);
2894       break;
2895     }
2896     }
2897     break;
2898   }
2899
2900   case ISD::SHL_PARTS:
2901   case ISD::SRA_PARTS:
2902   case ISD::SRL_PARTS: {
2903     SmallVector<SDValue, 8> Ops;
2904     bool Changed = false;
2905     unsigned N = Node->getNumOperands();
2906     for (unsigned i = 0; i + 1 < N; ++i) {
2907       Ops.push_back(LegalizeOp(Node->getOperand(i)));
2908       Changed |= Ops.back() != Node->getOperand(i);
2909     }
2910     Ops.push_back(LegalizeOp(DAG.getShiftAmountOperand(Node->getOperand(N-1))));
2911     Changed |= Ops.back() != Node->getOperand(N-1);
2912     if (Changed)
2913       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
2914
2915     switch (TLI.getOperationAction(Node->getOpcode(),
2916                                    Node->getValueType(0))) {
2917     default: assert(0 && "This action is not supported yet!");
2918     case TargetLowering::Legal: break;
2919     case TargetLowering::Custom:
2920       Tmp1 = TLI.LowerOperation(Result, DAG);
2921       if (Tmp1.getNode()) {
2922         SDValue Tmp2, RetVal(0, 0);
2923         for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
2924           Tmp2 = LegalizeOp(Tmp1.getValue(i));
2925           AddLegalizedOperand(SDValue(Node, i), Tmp2);
2926           if (i == Op.getResNo())
2927             RetVal = Tmp2;
2928         }
2929         assert(RetVal.getNode() && "Illegal result number");
2930         return RetVal;
2931       }
2932       break;
2933     }
2934
2935     // Since these produce multiple values, make sure to remember that we
2936     // legalized all of them.
2937     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
2938       AddLegalizedOperand(SDValue(Node, i), Result.getValue(i));
2939     return Result.getValue(Op.getResNo());
2940   }
2941
2942     // Binary operators
2943   case ISD::ADD:
2944   case ISD::SUB:
2945   case ISD::MUL:
2946   case ISD::MULHS:
2947   case ISD::MULHU:
2948   case ISD::UDIV:
2949   case ISD::SDIV:
2950   case ISD::AND:
2951   case ISD::OR:
2952   case ISD::XOR:
2953   case ISD::SHL:
2954   case ISD::SRL:
2955   case ISD::SRA:
2956   case ISD::FADD:
2957   case ISD::FSUB:
2958   case ISD::FMUL:
2959   case ISD::FDIV:
2960   case ISD::FPOW:
2961     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2962     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
2963
2964     if ((Node->getOpcode() == ISD::SHL ||
2965          Node->getOpcode() == ISD::SRL ||
2966          Node->getOpcode() == ISD::SRA) &&
2967         !Node->getValueType(0).isVector())
2968       Tmp2 = DAG.getShiftAmountOperand(Tmp2);
2969
2970     Tmp2 = LegalizeOp(Tmp2); // Legalize the RHS.
2971
2972     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2973
2974     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2975     default: assert(0 && "BinOp legalize operation not supported");
2976     case TargetLowering::Legal: break;
2977     case TargetLowering::Custom:
2978       Tmp1 = TLI.LowerOperation(Result, DAG);
2979       if (Tmp1.getNode()) {
2980         Result = Tmp1;
2981         break;
2982       }
2983       // Fall through if the custom lower can't deal with the operation
2984     case TargetLowering::Expand: {
2985       MVT VT = Op.getValueType();
2986
2987       // See if multiply or divide can be lowered using two-result operations.
2988       SDVTList VTs = DAG.getVTList(VT, VT);
2989       if (Node->getOpcode() == ISD::MUL) {
2990         // We just need the low half of the multiply; try both the signed
2991         // and unsigned forms. If the target supports both SMUL_LOHI and
2992         // UMUL_LOHI, form a preference by checking which forms of plain
2993         // MULH it supports.
2994         bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
2995         bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
2996         bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
2997         bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
2998         unsigned OpToUse = 0;
2999         if (HasSMUL_LOHI && !HasMULHS) {
3000           OpToUse = ISD::SMUL_LOHI;
3001         } else if (HasUMUL_LOHI && !HasMULHU) {
3002           OpToUse = ISD::UMUL_LOHI;
3003         } else if (HasSMUL_LOHI) {
3004           OpToUse = ISD::SMUL_LOHI;
3005         } else if (HasUMUL_LOHI) {
3006           OpToUse = ISD::UMUL_LOHI;
3007         }
3008         if (OpToUse) {
3009           Result = DAG.getNode(OpToUse, dl, VTs, Tmp1, Tmp2);
3010           break;
3011         }
3012       }
3013       if (Node->getOpcode() == ISD::MULHS &&
3014           TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT)) {
3015         Result = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl,
3016                                      VTs, Tmp1, Tmp2).getNode(),
3017                          1);
3018         break;
3019       }
3020       if (Node->getOpcode() == ISD::MULHU &&
3021           TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT)) {
3022         Result = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl,
3023                                      VTs, Tmp1, Tmp2).getNode(),
3024                          1);
3025         break;
3026       }
3027       if (Node->getOpcode() == ISD::SDIV &&
3028           TLI.isOperationLegalOrCustom(ISD::SDIVREM, VT)) {
3029         Result = DAG.getNode(ISD::SDIVREM, dl, VTs, Tmp1, Tmp2);
3030         break;
3031       }
3032       if (Node->getOpcode() == ISD::UDIV &&
3033           TLI.isOperationLegalOrCustom(ISD::UDIVREM, VT)) {
3034         Result = DAG.getNode(ISD::UDIVREM, dl, VTs, Tmp1, Tmp2);
3035         break;
3036       }
3037       if (Node->getOpcode() == ISD::SUB &&
3038           TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
3039           TLI.isOperationLegalOrCustom(ISD::XOR, VT)) {
3040         Tmp2 = DAG.getNode(ISD::XOR, dl, VT, Tmp2,
3041                DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT));
3042         Tmp2 = DAG.getNode(ISD::ADD, dl, VT, Tmp2, DAG.getConstant(1, VT));
3043         Result = DAG.getNode(ISD::ADD, dl, VT, Tmp1, Tmp2);
3044         break;
3045       }
3046
3047       // Check to see if we have a libcall for this operator.
3048       RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3049       bool isSigned = false;
3050       switch (Node->getOpcode()) {
3051       case ISD::UDIV:
3052       case ISD::SDIV:
3053        isSigned = Node->getOpcode() == ISD::SDIV;
3054        if (VT == MVT::i16)
3055          LC = (isSigned ? RTLIB::SDIV_I16  : RTLIB::UDIV_I16);
3056        else if (VT == MVT::i32)
3057          LC = (isSigned ? RTLIB::SDIV_I32  : RTLIB::UDIV_I32);
3058        else if (VT == MVT::i64)
3059          LC = (isSigned ? RTLIB::SDIV_I64  : RTLIB::UDIV_I64);
3060        else if (VT == MVT::i128)
3061          LC = (isSigned ? RTLIB::SDIV_I128 : RTLIB::UDIV_I128);
3062        break;
3063       case ISD::MUL:
3064         if (VT == MVT::i16)
3065           LC = RTLIB::MUL_I16;
3066         else if (VT == MVT::i32)
3067           LC = RTLIB::MUL_I32;
3068         else if (VT == MVT::i64)
3069           LC = RTLIB::MUL_I64;
3070         else if (VT == MVT::i128)
3071           LC = RTLIB::MUL_I128;
3072         break;
3073       case ISD::FPOW:
3074         LC = GetFPLibCall(VT, RTLIB::POW_F32, RTLIB::POW_F64, RTLIB::POW_F80,
3075                           RTLIB::POW_PPCF128);
3076         break;
3077       case ISD::FDIV:
3078         LC = GetFPLibCall(VT, RTLIB::DIV_F32, RTLIB::DIV_F64, RTLIB::DIV_F80,
3079                           RTLIB::DIV_PPCF128);
3080         break;
3081       default: break;
3082       }
3083       if (LC != RTLIB::UNKNOWN_LIBCALL) {
3084         SDValue Dummy;
3085         Result = ExpandLibCall(LC, Node, isSigned, Dummy);
3086         break;
3087       }
3088
3089       assert(Node->getValueType(0).isVector() &&
3090              "Cannot expand this binary operator!");
3091       // Expand the operation into a bunch of nasty scalar code.
3092       Result = LegalizeOp(UnrollVectorOp(Op));
3093       break;
3094     }
3095     case TargetLowering::Promote: {
3096       switch (Node->getOpcode()) {
3097       default:  assert(0 && "Do not know how to promote this BinOp!");
3098       case ISD::AND:
3099       case ISD::OR:
3100       case ISD::XOR: {
3101         MVT OVT = Node->getValueType(0);
3102         MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3103         assert(OVT.isVector() && "Cannot promote this BinOp!");
3104         // Bit convert each of the values to the new type.
3105         Tmp1 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Tmp1);
3106         Tmp2 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Tmp2);
3107         Result = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
3108         // Bit convert the result back the original type.
3109         Result = DAG.getNode(ISD::BIT_CONVERT, dl, OVT, Result);
3110         break;
3111       }
3112       }
3113     }
3114     }
3115     break;
3116
3117   case ISD::SMUL_LOHI:
3118   case ISD::UMUL_LOHI:
3119   case ISD::SDIVREM:
3120   case ISD::UDIVREM:
3121     // These nodes will only be produced by target-specific lowering, so
3122     // they shouldn't be here if they aren't legal.
3123     assert(TLI.isOperationLegal(Node->getOpcode(), Node->getValueType(0)) &&
3124            "This must be legal!");
3125
3126     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3127     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
3128     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3129     break;
3130
3131   case ISD::FCOPYSIGN:  // FCOPYSIGN does not require LHS/RHS to match type!
3132     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3133     Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
3134
3135     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3136
3137     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3138     default: assert(0 && "Operation not supported");
3139     case TargetLowering::Custom:
3140       Tmp1 = TLI.LowerOperation(Result, DAG);
3141       if (Tmp1.getNode()) Result = Tmp1;
3142       break;
3143     case TargetLowering::Legal: break;
3144     case TargetLowering::Expand: {
3145       assert((Tmp2.getValueType() == MVT::f32 ||
3146               Tmp2.getValueType() == MVT::f64) && isTypeLegal(MVT::i32) &&
3147               "Ugly special-cased code!");
3148       // Get the sign bit of the RHS.
3149       SDValue StackPtr = DAG.CreateStackTemporary(Tmp2.getValueType());
3150       SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Tmp2, StackPtr, NULL,
3151                                 0);
3152       if (Tmp2.getValueType() == MVT::f64 && TLI.isLittleEndian())
3153         StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(),
3154                                StackPtr, DAG.getIntPtrConstant(4));
3155       SDValue SignBit = DAG.getLoad(MVT::i32, dl, Ch, StackPtr, NULL, 0);
3156       SignBit = DAG.getSetCC(dl, TLI.getSetCCResultType(MVT::i32),
3157                              SignBit, DAG.getConstant(0, MVT::i32), ISD::SETLT);
3158       // Get the absolute value of the result.
3159       SDValue AbsVal = DAG.getNode(ISD::FABS, dl, Tmp1.getValueType(), Tmp1);
3160       // Select between the nabs and abs value based on the sign bit of
3161       // the input.
3162       Result = DAG.getNode(ISD::SELECT, dl, AbsVal.getValueType(), SignBit,
3163                            DAG.getNode(ISD::FNEG, dl, AbsVal.getValueType(),
3164                                        AbsVal),
3165                            AbsVal);
3166       Result = LegalizeOp(Result);
3167       break;
3168     }
3169     }
3170     break;
3171
3172   case ISD::ADDC:
3173   case ISD::SUBC:
3174     Tmp1 = LegalizeOp(Node->getOperand(0));
3175     Tmp2 = LegalizeOp(Node->getOperand(1));
3176     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3177     Tmp3 = Result.getValue(0);
3178     Tmp4 = Result.getValue(1);
3179
3180     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3181     default: assert(0 && "This action is not supported yet!");
3182     case TargetLowering::Legal:
3183       break;
3184     case TargetLowering::Custom:
3185       Tmp1 = TLI.LowerOperation(Tmp3, DAG);
3186       if (Tmp1.getNode() != NULL) {
3187         Tmp3 = LegalizeOp(Tmp1);
3188         Tmp4 = LegalizeOp(Tmp1.getValue(1));
3189       }
3190       break;
3191     }
3192     // Since this produces two values, make sure to remember that we legalized
3193     // both of them.
3194     AddLegalizedOperand(SDValue(Node, 0), Tmp3);
3195     AddLegalizedOperand(SDValue(Node, 1), Tmp4);
3196     return Op.getResNo() ? Tmp4 : Tmp3;
3197
3198   case ISD::ADDE:
3199   case ISD::SUBE:
3200     Tmp1 = LegalizeOp(Node->getOperand(0));
3201     Tmp2 = LegalizeOp(Node->getOperand(1));
3202     Tmp3 = LegalizeOp(Node->getOperand(2));
3203     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
3204     Tmp3 = Result.getValue(0);
3205     Tmp4 = Result.getValue(1);
3206
3207     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3208     default: assert(0 && "This action is not supported yet!");
3209     case TargetLowering::Legal:
3210       break;
3211     case TargetLowering::Custom:
3212       Tmp1 = TLI.LowerOperation(Tmp3, DAG);
3213       if (Tmp1.getNode() != NULL) {
3214         Tmp3 = LegalizeOp(Tmp1);
3215         Tmp4 = LegalizeOp(Tmp1.getValue(1));
3216       }
3217       break;
3218     }
3219     // Since this produces two values, make sure to remember that we legalized
3220     // both of them.
3221     AddLegalizedOperand(SDValue(Node, 0), Tmp3);
3222     AddLegalizedOperand(SDValue(Node, 1), Tmp4);
3223     return Op.getResNo() ? Tmp4 : Tmp3;
3224
3225   case ISD::BUILD_PAIR: {
3226     MVT PairTy = Node->getValueType(0);
3227     // TODO: handle the case where the Lo and Hi operands are not of legal type
3228     Tmp1 = LegalizeOp(Node->getOperand(0));   // Lo
3229     Tmp2 = LegalizeOp(Node->getOperand(1));   // Hi
3230     switch (TLI.getOperationAction(ISD::BUILD_PAIR, PairTy)) {
3231     case TargetLowering::Promote:
3232     case TargetLowering::Custom:
3233       assert(0 && "Cannot promote/custom this yet!");
3234     case TargetLowering::Legal:
3235       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
3236         Result = DAG.getNode(ISD::BUILD_PAIR, dl, PairTy, Tmp1, Tmp2);
3237       break;
3238     case TargetLowering::Expand:
3239       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Tmp1);
3240       Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Tmp2);
3241       Tmp2 = DAG.getNode(ISD::SHL, dl, PairTy, Tmp2,
3242                          DAG.getConstant(PairTy.getSizeInBits()/2,
3243                                          TLI.getShiftAmountTy()));
3244       Result = DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2);
3245       break;
3246     }
3247     break;
3248   }
3249
3250   case ISD::UREM:
3251   case ISD::SREM:
3252   case ISD::FREM:
3253     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3254     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
3255
3256     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3257     case TargetLowering::Promote: assert(0 && "Cannot promote this yet!");
3258     case TargetLowering::Custom:
3259       isCustom = true;
3260       // FALLTHROUGH
3261     case TargetLowering::Legal:
3262       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3263       if (isCustom) {
3264         Tmp1 = TLI.LowerOperation(Result, DAG);
3265         if (Tmp1.getNode()) Result = Tmp1;
3266       }
3267       break;
3268     case TargetLowering::Expand: {
3269       unsigned DivOpc= (Node->getOpcode() == ISD::UREM) ? ISD::UDIV : ISD::SDIV;
3270       bool isSigned = DivOpc == ISD::SDIV;
3271       MVT VT = Node->getValueType(0);
3272
3273       // See if remainder can be lowered using two-result operations.
3274       SDVTList VTs = DAG.getVTList(VT, VT);
3275       if (Node->getOpcode() == ISD::SREM &&
3276           TLI.isOperationLegalOrCustom(ISD::SDIVREM, VT)) {
3277         Result = SDValue(DAG.getNode(ISD::SDIVREM, dl,
3278                                      VTs, Tmp1, Tmp2).getNode(), 1);
3279         break;
3280       }
3281       if (Node->getOpcode() == ISD::UREM &&
3282           TLI.isOperationLegalOrCustom(ISD::UDIVREM, VT)) {
3283         Result = SDValue(DAG.getNode(ISD::UDIVREM, dl,
3284                                      VTs, Tmp1, Tmp2).getNode(), 1);
3285         break;
3286       }
3287
3288       if (VT.isInteger() &&
3289           TLI.getOperationAction(DivOpc, VT) == TargetLowering::Legal) {
3290         // X % Y -> X-X/Y*Y
3291         Result = DAG.getNode(DivOpc, dl, VT, Tmp1, Tmp2);
3292         Result = DAG.getNode(ISD::MUL, dl, VT, Result, Tmp2);
3293         Result = DAG.getNode(ISD::SUB, dl, VT, Tmp1, Result);
3294         break;
3295       }
3296
3297       // Check to see if we have a libcall for this operator.
3298       RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3299       switch (Node->getOpcode()) {
3300       default: break;
3301       case ISD::UREM:
3302       case ISD::SREM:
3303        if (VT == MVT::i16)
3304          LC = (isSigned ? RTLIB::SREM_I16  : RTLIB::UREM_I16);
3305        else if (VT == MVT::i32)
3306          LC = (isSigned ? RTLIB::SREM_I32  : RTLIB::UREM_I32);
3307        else if (VT == MVT::i64)
3308          LC = (isSigned ? RTLIB::SREM_I64  : RTLIB::UREM_I64);
3309        else if (VT == MVT::i128)
3310          LC = (isSigned ? RTLIB::SREM_I128 : RTLIB::UREM_I128);
3311        break;
3312        case ISD::FREM:
3313         // Floating point mod -> fmod libcall.
3314         LC = GetFPLibCall(VT, RTLIB::REM_F32, RTLIB::REM_F64,
3315                           RTLIB::REM_F80, RTLIB::REM_PPCF128);
3316         break;
3317       }
3318
3319       if (LC != RTLIB::UNKNOWN_LIBCALL) {
3320         SDValue Dummy;
3321         Result = ExpandLibCall(LC, Node, isSigned, Dummy);
3322         break;
3323       }
3324
3325       assert(VT.isVector() &&
3326              "Cannot expand this binary operator!");
3327       // Expand the operation into a bunch of nasty scalar code.
3328       Result = LegalizeOp(UnrollVectorOp(Op));
3329       break;
3330     }
3331     }
3332     break;
3333   case ISD::VAARG: {
3334     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
3335     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
3336
3337     MVT VT = Node->getValueType(0);
3338     switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
3339     default: assert(0 && "This action is not supported yet!");
3340     case TargetLowering::Custom:
3341       isCustom = true;
3342       // FALLTHROUGH
3343     case TargetLowering::Legal:
3344       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
3345       Result = Result.getValue(0);
3346       Tmp1 = Result.getValue(1);
3347
3348       if (isCustom) {
3349         Tmp2 = TLI.LowerOperation(Result, DAG);
3350         if (Tmp2.getNode()) {
3351           Result = LegalizeOp(Tmp2);
3352           Tmp1 = LegalizeOp(Tmp2.getValue(1));
3353         }
3354       }
3355       break;
3356     case TargetLowering::Expand: {
3357       const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3358       SDValue VAList = DAG.getLoad(TLI.getPointerTy(), dl, Tmp1, Tmp2, V, 0);
3359       // Increment the pointer, VAList, to the next vaarg
3360       Tmp3 = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), VAList,
3361                          DAG.getConstant(TLI.getTargetData()->
3362                                          getTypeAllocSize(VT.getTypeForMVT()),
3363                                          TLI.getPointerTy()));
3364       // Store the incremented VAList to the legalized pointer
3365       Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Tmp2, V, 0);
3366       // Load the actual argument out of the pointer VAList
3367       Result = DAG.getLoad(VT, dl, Tmp3, VAList, NULL, 0);
3368       Tmp1 = LegalizeOp(Result.getValue(1));
3369       Result = LegalizeOp(Result);
3370       break;
3371     }
3372     }
3373     // Since VAARG produces two values, make sure to remember that we
3374     // legalized both of them.
3375     AddLegalizedOperand(SDValue(Node, 0), Result);
3376     AddLegalizedOperand(SDValue(Node, 1), Tmp1);
3377     return Op.getResNo() ? Tmp1 : Result;
3378   }
3379
3380   case ISD::VACOPY:
3381     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
3382     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the dest pointer.
3383     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the source pointer.
3384
3385     switch (TLI.getOperationAction(ISD::VACOPY, MVT::Other)) {
3386     default: assert(0 && "This action is not supported yet!");
3387     case TargetLowering::Custom:
3388       isCustom = true;
3389       // FALLTHROUGH
3390     case TargetLowering::Legal:
3391       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3,
3392                                       Node->getOperand(3), Node->getOperand(4));
3393       if (isCustom) {
3394         Tmp1 = TLI.LowerOperation(Result, DAG);
3395         if (Tmp1.getNode()) Result = Tmp1;
3396       }
3397       break;
3398     case TargetLowering::Expand:
3399       // This defaults to loading a pointer from the input and storing it to the
3400       // output, returning the chain.
3401       const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
3402       const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
3403       Tmp4 = DAG.getLoad(TLI.getPointerTy(), dl, Tmp1, Tmp3, VS, 0);
3404       Result = DAG.getStore(Tmp4.getValue(1), dl, Tmp4, Tmp2, VD, 0);
3405       break;
3406     }
3407     break;
3408
3409   case ISD::VAEND:
3410     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
3411     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
3412
3413     switch (TLI.getOperationAction(ISD::VAEND, MVT::Other)) {
3414     default: assert(0 && "This action is not supported yet!");
3415     case TargetLowering::Custom:
3416       isCustom = true;
3417       // FALLTHROUGH
3418     case TargetLowering::Legal:
3419       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
3420       if (isCustom) {
3421         Tmp1 = TLI.LowerOperation(Tmp1, DAG);
3422         if (Tmp1.getNode()) Result = Tmp1;
3423       }
3424       break;
3425     case TargetLowering::Expand:
3426       Result = Tmp1; // Default to a no-op, return the chain
3427       break;
3428     }
3429     break;
3430
3431   case ISD::VASTART:
3432     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
3433     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
3434
3435     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
3436
3437     switch (TLI.getOperationAction(ISD::VASTART, MVT::Other)) {
3438     default: assert(0 && "This action is not supported yet!");
3439     case TargetLowering::Legal: break;
3440     case TargetLowering::Custom:
3441       Tmp1 = TLI.LowerOperation(Result, DAG);
3442       if (Tmp1.getNode()) Result = Tmp1;
3443       break;
3444     }
3445     break;
3446
3447   case ISD::ROTL:
3448   case ISD::ROTR:
3449     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3450     Tmp2 = LegalizeOp(DAG.getShiftAmountOperand(Node->getOperand(1)));   // RHS
3451     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3452     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3453     default:
3454       assert(0 && "ROTL/ROTR legalize operation not supported");
3455       break;
3456     case TargetLowering::Legal:
3457       break;
3458     case TargetLowering::Custom:
3459       Tmp1 = TLI.LowerOperation(Result, DAG);
3460       if (Tmp1.getNode()) Result = Tmp1;
3461       break;
3462     case TargetLowering::Promote:
3463       assert(0 && "Do not know how to promote ROTL/ROTR");
3464       break;
3465     case TargetLowering::Expand:
3466       assert(0 && "Do not know how to expand ROTL/ROTR");
3467       break;
3468     }
3469     break;
3470
3471   case ISD::BSWAP:
3472     Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
3473     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3474     case TargetLowering::Custom:
3475       assert(0 && "Cannot custom legalize this yet!");
3476     case TargetLowering::Legal:
3477       Result = DAG.UpdateNodeOperands(Result, Tmp1);
3478       break;
3479     case TargetLowering::Promote: {
3480       MVT OVT = Tmp1.getValueType();
3481       MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3482       unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
3483
3484       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Tmp1);
3485       Tmp1 = DAG.getNode(ISD::BSWAP, dl, NVT, Tmp1);
3486       Result = DAG.getNode(ISD::SRL, dl, NVT, Tmp1,
3487                            DAG.getConstant(DiffBits, TLI.getShiftAmountTy()));
3488       break;
3489     }
3490     case TargetLowering::Expand:
3491       Result = ExpandBSWAP(Tmp1, dl);
3492       break;
3493     }
3494     break;
3495
3496   case ISD::CTPOP:
3497   case ISD::CTTZ:
3498   case ISD::CTLZ:
3499     Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
3500     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3501     case TargetLowering::Custom:
3502     case TargetLowering::Legal:
3503       Result = DAG.UpdateNodeOperands(Result, Tmp1);
3504       if (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)) ==
3505           TargetLowering::Custom) {
3506         Tmp1 = TLI.LowerOperation(Result, DAG);
3507         if (Tmp1.getNode()) {
3508           Result = Tmp1;
3509         }
3510       }
3511       break;
3512     case TargetLowering::Promote: {
3513       MVT OVT = Tmp1.getValueType();
3514       MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3515
3516       // Zero extend the argument.
3517       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Tmp1);
3518       // Perform the larger operation, then subtract if needed.
3519       Tmp1 = DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0), Tmp1);
3520       switch (Node->getOpcode()) {
3521       case ISD::CTPOP:
3522         Result = Tmp1;
3523         break;
3524       case ISD::CTTZ:
3525         //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
3526         Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(Tmp1.getValueType()),
3527                             Tmp1, DAG.getConstant(NVT.getSizeInBits(), NVT),
3528                             ISD::SETEQ);
3529         Result = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2,
3530                              DAG.getConstant(OVT.getSizeInBits(), NVT), Tmp1);
3531         break;
3532       case ISD::CTLZ:
3533         // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
3534         Result = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
3535                              DAG.getConstant(NVT.getSizeInBits() -
3536                                              OVT.getSizeInBits(), NVT));
3537         break;
3538       }
3539       break;
3540     }
3541     case TargetLowering::Expand:
3542       Result = ExpandBitCount(Node->getOpcode(), Tmp1, dl);
3543       break;
3544     }
3545     break;
3546
3547     // Unary operators
3548   case ISD::FABS:
3549   case ISD::FNEG:
3550   case ISD::FSQRT:
3551   case ISD::FSIN:
3552   case ISD::FCOS:
3553   case ISD::FLOG:
3554   case ISD::FLOG2:
3555   case ISD::FLOG10:
3556   case ISD::FEXP:
3557   case ISD::FEXP2:
3558   case ISD::FTRUNC:
3559   case ISD::FFLOOR:
3560   case ISD::FCEIL:
3561   case ISD::FRINT:
3562   case ISD::FNEARBYINT:
3563     Tmp1 = LegalizeOp(Node->getOperand(0));
3564     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3565     case TargetLowering::Promote:
3566     case TargetLowering::Custom:
3567      isCustom = true;
3568      // FALLTHROUGH
3569     case TargetLowering::Legal:
3570       Result = DAG.UpdateNodeOperands(Result, Tmp1);
3571       if (isCustom) {
3572         Tmp1 = TLI.LowerOperation(Result, DAG);
3573         if (Tmp1.getNode()) Result = Tmp1;
3574       }
3575       break;
3576     case TargetLowering::Expand:
3577       switch (Node->getOpcode()) {
3578       default: assert(0 && "Unreachable!");
3579       case ISD::FNEG:
3580         // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
3581         Tmp2 = DAG.getConstantFP(-0.0, Node->getValueType(0));
3582         Result = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp2, Tmp1);
3583         break;
3584       case ISD::FABS: {
3585         // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
3586         MVT VT = Node->getValueType(0);
3587         Tmp2 = DAG.getConstantFP(0.0, VT);
3588         Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(Tmp1.getValueType()),
3589                             Tmp1, Tmp2, ISD::SETUGT);
3590         Tmp3 = DAG.getNode(ISD::FNEG, dl, VT, Tmp1);
3591         Result = DAG.getNode(ISD::SELECT, dl, VT, Tmp2, Tmp1, Tmp3);
3592         break;
3593       }
3594       case ISD::FSQRT:
3595       case ISD::FSIN:
3596       case ISD::FCOS:
3597       case ISD::FLOG:
3598       case ISD::FLOG2:
3599       case ISD::FLOG10:
3600       case ISD::FEXP:
3601       case ISD::FEXP2:
3602       case ISD::FTRUNC:
3603       case ISD::FFLOOR:
3604       case ISD::FCEIL:
3605       case ISD::FRINT:
3606       case ISD::FNEARBYINT: {
3607         MVT VT = Node->getValueType(0);
3608
3609         // Expand unsupported unary vector operators by unrolling them.
3610         if (VT.isVector()) {
3611           Result = LegalizeOp(UnrollVectorOp(Op));
3612           break;
3613         }
3614
3615         RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3616         switch(Node->getOpcode()) {
3617         case ISD::FSQRT:
3618           LC = GetFPLibCall(VT, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
3619                             RTLIB::SQRT_F80, RTLIB::SQRT_PPCF128);
3620           break;
3621         case ISD::FSIN:
3622           LC = GetFPLibCall(VT, RTLIB::SIN_F32, RTLIB::SIN_F64,
3623                             RTLIB::SIN_F80, RTLIB::SIN_PPCF128);
3624           break;
3625         case ISD::FCOS:
3626           LC = GetFPLibCall(VT, RTLIB::COS_F32, RTLIB::COS_F64,
3627                             RTLIB::COS_F80, RTLIB::COS_PPCF128);
3628           break;
3629         case ISD::FLOG:
3630           LC = GetFPLibCall(VT, RTLIB::LOG_F32, RTLIB::LOG_F64,
3631                             RTLIB::LOG_F80, RTLIB::LOG_PPCF128);
3632           break;
3633         case ISD::FLOG2:
3634           LC = GetFPLibCall(VT, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
3635                             RTLIB::LOG2_F80, RTLIB::LOG2_PPCF128);
3636           break;
3637         case ISD::FLOG10:
3638           LC = GetFPLibCall(VT, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
3639                             RTLIB::LOG10_F80, RTLIB::LOG10_PPCF128);
3640           break;
3641         case ISD::FEXP:
3642           LC = GetFPLibCall(VT, RTLIB::EXP_F32, RTLIB::EXP_F64,
3643                             RTLIB::EXP_F80, RTLIB::EXP_PPCF128);
3644           break;
3645         case ISD::FEXP2:
3646           LC = GetFPLibCall(VT, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
3647                             RTLIB::EXP2_F80, RTLIB::EXP2_PPCF128);
3648           break;
3649         case ISD::FTRUNC:
3650           LC = GetFPLibCall(VT, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
3651                             RTLIB::TRUNC_F80, RTLIB::TRUNC_PPCF128);
3652           break;
3653         case ISD::FFLOOR:
3654           LC = GetFPLibCall(VT, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
3655                             RTLIB::FLOOR_F80, RTLIB::FLOOR_PPCF128);
3656           break;
3657         case ISD::FCEIL:
3658           LC = GetFPLibCall(VT, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
3659                             RTLIB::CEIL_F80, RTLIB::CEIL_PPCF128);
3660           break;
3661         case ISD::FRINT:
3662           LC = GetFPLibCall(VT, RTLIB::RINT_F32, RTLIB::RINT_F64,
3663                             RTLIB::RINT_F80, RTLIB::RINT_PPCF128);
3664           break;
3665         case ISD::FNEARBYINT:
3666           LC = GetFPLibCall(VT, RTLIB::NEARBYINT_F32, RTLIB::NEARBYINT_F64,
3667                             RTLIB::NEARBYINT_F80, RTLIB::NEARBYINT_PPCF128);
3668           break;
3669       break;
3670         default: assert(0 && "Unreachable!");
3671         }
3672         SDValue Dummy;
3673         Result = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Dummy);
3674         break;
3675       }
3676       }
3677       break;
3678     }
3679     break;
3680   case ISD::FPOWI: {
3681     MVT VT = Node->getValueType(0);
3682
3683     // Expand unsupported unary vector operators by unrolling them.
3684     if (VT.isVector()) {
3685       Result = LegalizeOp(UnrollVectorOp(Op));
3686       break;
3687     }
3688
3689     // We always lower FPOWI into a libcall.  No target support for it yet.
3690     RTLIB::Libcall LC = GetFPLibCall(VT, RTLIB::POWI_F32, RTLIB::POWI_F64,
3691                                      RTLIB::POWI_F80, RTLIB::POWI_PPCF128);
3692     SDValue Dummy;
3693     Result = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Dummy);
3694     break;
3695   }
3696   case ISD::BIT_CONVERT:
3697     switch (TLI.getOperationAction(ISD::BIT_CONVERT,
3698                                    Node->getOperand(0).getValueType())) {
3699     default: assert(0 && "Unknown operation action!");
3700     case TargetLowering::Expand:
3701       Result = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
3702                                 Node->getValueType(0), dl);
3703       break;
3704     case TargetLowering::Legal:
3705       Tmp1 = LegalizeOp(Node->getOperand(0));
3706       Result = DAG.UpdateNodeOperands(Result, Tmp1);
3707       break;
3708     }
3709     break;
3710   case ISD::CONVERT_RNDSAT: {
3711     ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(Node)->getCvtCode();
3712     switch (CvtCode) {
3713     default: assert(0 && "Unknown cvt code!");
3714     case ISD::CVT_SF:
3715     case ISD::CVT_UF:
3716     case ISD::CVT_FF:
3717       break;
3718     case ISD::CVT_FS:
3719     case ISD::CVT_FU:
3720     case ISD::CVT_SS:
3721     case ISD::CVT_SU:
3722     case ISD::CVT_US:
3723     case ISD::CVT_UU: {
3724       SDValue DTyOp = Node->getOperand(1);
3725       SDValue STyOp = Node->getOperand(2);
3726       SDValue RndOp = Node->getOperand(3);
3727       SDValue SatOp = Node->getOperand(4);
3728       Tmp1 = LegalizeOp(Node->getOperand(0));
3729       Result = DAG.UpdateNodeOperands(Result, Tmp1, DTyOp, STyOp,
3730                                       RndOp, SatOp);
3731       if (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)) ==
3732           TargetLowering::Custom) {
3733         Tmp1 = TLI.LowerOperation(Result, DAG);
3734         if (Tmp1.getNode()) Result = Tmp1;
3735       }
3736       break;
3737     }
3738     } // end switch CvtCode
3739     break;
3740   }
3741     // Conversion operators.  The source and destination have different types.
3742   case ISD::SINT_TO_FP:
3743   case ISD::UINT_TO_FP: {
3744     bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
3745     Result = LegalizeINT_TO_FP(Result, isSigned,
3746                                Node->getValueType(0), Node->getOperand(0), dl);
3747     break;
3748   }
3749   case ISD::TRUNCATE:
3750     Tmp1 = LegalizeOp(Node->getOperand(0));
3751     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3752     default: assert(0 && "Unknown TRUNCATE legalization operation action!");
3753     case TargetLowering::Custom:
3754       isCustom = true;
3755       // FALLTHROUGH
3756     case TargetLowering::Legal:
3757       Result = DAG.UpdateNodeOperands(Result, Tmp1);
3758       if (isCustom) {
3759         Tmp1 = TLI.LowerOperation(Result, DAG);
3760         if (Tmp1.getNode()) Result = Tmp1;
3761       }
3762       break;
3763     case TargetLowering::Expand:
3764       assert(Result.getValueType().isVector() && "must be vector type");
3765       // Unroll the truncate.  We should do better.
3766       Result = LegalizeOp(UnrollVectorOp(Result));
3767       break;
3768     }
3769     break;
3770
3771   case ISD::FP_TO_SINT:
3772   case ISD::FP_TO_UINT:
3773     Tmp1 = LegalizeOp(Node->getOperand(0));
3774
3775     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))){
3776     default: assert(0 && "Unknown operation action!");
3777     case TargetLowering::Custom:
3778       isCustom = true;
3779       // FALLTHROUGH
3780     case TargetLowering::Legal:
3781       Result = DAG.UpdateNodeOperands(Result, Tmp1);
3782       if (isCustom) {
3783         Tmp1 = TLI.LowerOperation(Result, DAG);
3784         if (Tmp1.getNode()) Result = Tmp1;
3785       }
3786       break;
3787     case TargetLowering::Promote:
3788       Result = PromoteLegalFP_TO_INT(Tmp1, Node->getValueType(0),
3789                                      Node->getOpcode() == ISD::FP_TO_SINT,
3790                                      dl);
3791       break;
3792     case TargetLowering::Expand:
3793       if (Node->getOpcode() == ISD::FP_TO_UINT) {
3794         SDValue True, False;
3795         MVT VT =  Node->getOperand(0).getValueType();
3796         MVT NVT = Node->getValueType(0);
3797         const uint64_t zero[] = {0, 0};
3798         APFloat apf = APFloat(APInt(VT.getSizeInBits(), 2, zero));
3799         APInt x = APInt::getSignBit(NVT.getSizeInBits());
3800         (void)apf.convertFromAPInt(x, false, APFloat::rmNearestTiesToEven);
3801         Tmp2 = DAG.getConstantFP(apf, VT);
3802         Tmp3 = DAG.getSetCC(dl, TLI.getSetCCResultType(VT),
3803                             Node->getOperand(0),
3804                             Tmp2, ISD::SETLT);
3805         True = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, Node->getOperand(0));
3806         False = DAG.getNode(ISD::FP_TO_SINT, dl, NVT,
3807                             DAG.getNode(ISD::FSUB, dl, VT,
3808                                         Node->getOperand(0), Tmp2));
3809         False = DAG.getNode(ISD::XOR, dl, NVT, False,
3810                             DAG.getConstant(x, NVT));
3811         Result = DAG.getNode(ISD::SELECT, dl, NVT, Tmp3, True, False);
3812       } else {
3813         assert(0 && "Do not know how to expand FP_TO_SINT yet!");
3814       }
3815       break;
3816     }
3817     break;
3818
3819   case ISD::FP_EXTEND: {
3820     MVT DstVT = Op.getValueType();
3821     MVT SrcVT = Op.getOperand(0).getValueType();
3822     if (TLI.getConvertAction(SrcVT, DstVT) == TargetLowering::Expand) {
3823       // The only other way we can lower this is to turn it into a STORE,
3824       // LOAD pair, targetting a temporary location (a stack slot).
3825       Result = EmitStackConvert(Node->getOperand(0), SrcVT, DstVT, dl);
3826       break;
3827     }
3828     Tmp1 = LegalizeOp(Node->getOperand(0));
3829     Result = DAG.UpdateNodeOperands(Result, Tmp1);
3830     break;
3831   }
3832   case ISD::FP_ROUND: {
3833     MVT DstVT = Op.getValueType();
3834     MVT SrcVT = Op.getOperand(0).getValueType();
3835     if (TLI.getConvertAction(SrcVT, DstVT) == TargetLowering::Expand) {
3836       if (SrcVT == MVT::ppcf128) {
3837         // FIXME: Figure out how to extract the double without
3838         // help from type legalization
3839       }
3840       // The only other way we can lower this is to turn it into a STORE,
3841       // LOAD pair, targetting a temporary location (a stack slot).
3842       Result = EmitStackConvert(Node->getOperand(0), DstVT, DstVT, dl);
3843       break;
3844     }
3845     Tmp1 = LegalizeOp(Node->getOperand(0));
3846     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
3847     break;
3848   }
3849   case ISD::ANY_EXTEND:
3850   case ISD::ZERO_EXTEND:
3851   case ISD::SIGN_EXTEND:
3852     Tmp1 = LegalizeOp(Node->getOperand(0));
3853     Result = DAG.UpdateNodeOperands(Result, Tmp1);
3854     if (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)) ==
3855         TargetLowering::Custom) {
3856       Tmp1 = TLI.LowerOperation(Result, DAG);
3857       if (Tmp1.getNode()) Result = Tmp1;
3858     }
3859     break;
3860   case ISD::FP_ROUND_INREG:
3861   case ISD::SIGN_EXTEND_INREG: {
3862     Tmp1 = LegalizeOp(Node->getOperand(0));
3863     MVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
3864
3865     // If this operation is not supported, convert it to a shl/shr or load/store
3866     // pair.
3867     switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
3868     default: assert(0 && "This action not supported for this op yet!");
3869     case TargetLowering::Legal:
3870       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
3871       break;
3872     case TargetLowering::Expand:
3873       // If this is an integer extend and shifts are supported, do that.
3874       if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
3875         // NOTE: we could fall back on load/store here too for targets without
3876         // SAR.  However, it is doubtful that any exist.
3877         unsigned BitsDiff = Node->getValueType(0).getSizeInBits() -
3878                             ExtraVT.getSizeInBits();
3879         SDValue ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
3880         Result = DAG.getNode(ISD::SHL, dl, Node->getValueType(0),
3881                              Node->getOperand(0), ShiftCst);
3882         Result = DAG.getNode(ISD::SRA, dl, Node->getValueType(0),
3883                              Result, ShiftCst);
3884       } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
3885         // The only way we can lower this is to turn it into a TRUNCSTORE,
3886         // EXTLOAD pair, targetting a temporary location (a stack slot).
3887
3888         // NOTE: there is a choice here between constantly creating new stack
3889         // slots and always reusing the same one.  We currently always create
3890         // new ones, as reuse may inhibit scheduling.
3891         Result = EmitStackConvert(Node->getOperand(0), ExtraVT,
3892                                   Node->getValueType(0), dl);
3893       } else {
3894         assert(0 && "Unknown op");
3895       }
3896       break;
3897     }
3898     break;
3899   }
3900   case ISD::TRAMPOLINE: {
3901     SDValue Ops[6];
3902     for (unsigned i = 0; i != 6; ++i)
3903       Ops[i] = LegalizeOp(Node->getOperand(i));
3904     Result = DAG.UpdateNodeOperands(Result, Ops, 6);
3905     // The only option for this node is to custom lower it.
3906     Result = TLI.LowerOperation(Result, DAG);
3907     assert(Result.getNode() && "Should always custom lower!");
3908
3909     // Since trampoline produces two values, make sure to remember that we
3910     // legalized both of them.
3911     Tmp1 = LegalizeOp(Result.getValue(1));
3912     Result = LegalizeOp(Result);
3913     AddLegalizedOperand(SDValue(Node, 0), Result);
3914     AddLegalizedOperand(SDValue(Node, 1), Tmp1);
3915     return Op.getResNo() ? Tmp1 : Result;
3916   }
3917   case ISD::FLT_ROUNDS_: {
3918     MVT VT = Node->getValueType(0);
3919     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
3920     default: assert(0 && "This action not supported for this op yet!");
3921     case TargetLowering::Custom:
3922       Result = TLI.LowerOperation(Op, DAG);
3923       if (Result.getNode()) break;
3924       // Fall Thru
3925     case TargetLowering::Legal:
3926       // If this operation is not supported, lower it to constant 1
3927       Result = DAG.getConstant(1, VT);
3928       break;
3929     }
3930     break;
3931   }
3932   case ISD::TRAP: {
3933     MVT VT = Node->getValueType(0);
3934     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
3935     default: assert(0 && "This action not supported for this op yet!");
3936     case TargetLowering::Legal:
3937       Tmp1 = LegalizeOp(Node->getOperand(0));
3938       Result = DAG.UpdateNodeOperands(Result, Tmp1);
3939       break;
3940     case TargetLowering::Custom:
3941       Result = TLI.LowerOperation(Op, DAG);
3942       if (Result.getNode()) break;
3943       // Fall Thru
3944     case TargetLowering::Expand:
3945       // If this operation is not supported, lower it to 'abort()' call
3946       Tmp1 = LegalizeOp(Node->getOperand(0));
3947       TargetLowering::ArgListTy Args;
3948       std::pair<SDValue, SDValue> CallResult =
3949         TLI.LowerCallTo(Tmp1, Type::VoidTy,
3950                         false, false, false, false, CallingConv::C, false,
3951                         DAG.getExternalSymbol("abort", TLI.getPointerTy()),
3952                         Args, DAG, dl);
3953       Result = CallResult.second;
3954       break;
3955     }
3956     break;
3957   }
3958
3959   case ISD::SADDO:
3960   case ISD::SSUBO: {
3961     MVT VT = Node->getValueType(0);
3962     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
3963     default: assert(0 && "This action not supported for this op yet!");
3964     case TargetLowering::Custom:
3965       Result = TLI.LowerOperation(Op, DAG);
3966       if (Result.getNode()) break;
3967       // FALLTHROUGH
3968     case TargetLowering::Legal: {
3969       SDValue LHS = LegalizeOp(Node->getOperand(0));
3970       SDValue RHS = LegalizeOp(Node->getOperand(1));
3971
3972       SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
3973                                 ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3974                                 LHS, RHS);
3975       MVT OType = Node->getValueType(1);
3976
3977       SDValue Zero = DAG.getConstant(0, LHS.getValueType());
3978
3979       //   LHSSign -> LHS >= 0
3980       //   RHSSign -> RHS >= 0
3981       //   SumSign -> Sum >= 0
3982       //
3983       //   Add:
3984       //   Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
3985       //   Sub:
3986       //   Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
3987       //
3988       SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
3989       SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
3990       SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
3991                                         Node->getOpcode() == ISD::SADDO ?
3992                                         ISD::SETEQ : ISD::SETNE);
3993
3994       SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
3995       SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
3996
3997       SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
3998
3999       MVT ValueVTs[] = { LHS.getValueType(), OType };
4000       SDValue Ops[] = { Sum, Cmp };
4001
4002       Result = DAG.getNode(ISD::MERGE_VALUES, dl,
4003                            DAG.getVTList(&ValueVTs[0], 2),
4004                            &Ops[0], 2);
4005       SDNode *RNode = Result.getNode();
4006       DAG.ReplaceAllUsesWith(Node, RNode);
4007       break;
4008     }
4009     }
4010
4011     break;
4012   }
4013   case ISD::UADDO:
4014   case ISD::USUBO: {
4015     MVT VT = Node->getValueType(0);
4016     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
4017     default: assert(0 && "This action not supported for this op yet!");
4018     case TargetLowering::Custom:
4019       Result = TLI.LowerOperation(Op, DAG);
4020       if (Result.getNode()) break;
4021       // FALLTHROUGH
4022     case TargetLowering::Legal: {
4023       SDValue LHS = LegalizeOp(Node->getOperand(0));
4024       SDValue RHS = LegalizeOp(Node->getOperand(1));
4025
4026       SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::UADDO ?
4027                                 ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
4028                                 LHS, RHS);
4029       MVT OType = Node->getValueType(1);
4030       SDValue Cmp = DAG.getSetCC(dl, OType, Sum, LHS,
4031                                  Node->getOpcode () == ISD::UADDO ?
4032                                  ISD::SETULT : ISD::SETUGT);
4033
4034       MVT ValueVTs[] = { LHS.getValueType(), OType };
4035       SDValue Ops[] = { Sum, Cmp };
4036
4037       Result = DAG.getNode(ISD::MERGE_VALUES, dl,
4038                            DAG.getVTList(&ValueVTs[0], 2),
4039                            &Ops[0], 2);
4040       SDNode *RNode = Result.getNode();
4041       DAG.ReplaceAllUsesWith(Node, RNode);
4042       break;
4043     }
4044     }
4045
4046     break;
4047   }
4048   case ISD::SMULO:
4049   case ISD::UMULO: {
4050     MVT VT = Node->getValueType(0);
4051     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
4052     default: assert(0 && "This action is not supported at all!");
4053     case TargetLowering::Custom:
4054       Result = TLI.LowerOperation(Op, DAG);
4055       if (Result.getNode()) break;
4056       // Fall Thru
4057     case TargetLowering::Legal:
4058       // FIXME: According to Hacker's Delight, this can be implemented in
4059       // target independent lowering, but it would be inefficient, since it
4060       // requires a division + a branch.
4061       assert(0 && "Target independent lowering is not supported for SMULO/UMULO!");
4062     break;
4063     }
4064     break;
4065   }
4066
4067   }
4068
4069   assert(Result.getValueType() == Op.getValueType() &&
4070          "Bad legalization!");
4071
4072   // Make sure that the generated code is itself legal.
4073   if (Result != Op)
4074     Result = LegalizeOp(Result);
4075
4076   // Note that LegalizeOp may be reentered even from single-use nodes, which
4077   // means that we always must cache transformed nodes.
4078   AddLegalizedOperand(Op, Result);
4079   return Result;
4080 }
4081
4082 /// PromoteOp - Given an operation that produces a value in an invalid type,
4083 /// promote it to compute the value into a larger type.  The produced value will
4084 /// have the correct bits for the low portion of the register, but no guarantee
4085 /// is made about the top bits: it may be zero, sign-extended, or garbage.
4086 SDValue SelectionDAGLegalize::PromoteOp(SDValue Op) {
4087   assert(0 && "This should be dead!");
4088   MVT VT = Op.getValueType();
4089   MVT NVT = TLI.getTypeToTransformTo(VT);
4090   assert(getTypeAction(VT) == Promote &&
4091          "Caller should expand or legalize operands that are not promotable!");
4092   assert(NVT.bitsGT(VT) && NVT.isInteger() == VT.isInteger() &&
4093          "Cannot promote to smaller type!");
4094
4095   SDValue Tmp1, Tmp2, Tmp3;
4096   SDValue Result;
4097   SDNode *Node = Op.getNode();
4098   DebugLoc dl = Node->getDebugLoc();
4099
4100   DenseMap<SDValue, SDValue>::iterator I = PromotedNodes.find(Op);
4101   if (I != PromotedNodes.end()) return I->second;
4102
4103   switch (Node->getOpcode()) {
4104   case ISD::CopyFromReg:
4105     assert(0 && "CopyFromReg must be legal!");
4106   default:
4107 #ifndef NDEBUG
4108     cerr << "NODE: "; Node->dump(&DAG); cerr << "\n";
4109 #endif
4110     assert(0 && "Do not know how to promote this operator!");
4111     abort();
4112   case ISD::UNDEF:
4113     Result = DAG.getUNDEF(NVT);
4114     break;
4115   case ISD::Constant:
4116     if (VT != MVT::i1)
4117       Result = DAG.getNode(ISD::SIGN_EXTEND, dl, NVT, Op);
4118     else
4119       Result = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Op);
4120     assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
4121     break;
4122   case ISD::ConstantFP:
4123     Result = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Op);
4124     assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
4125     break;
4126
4127   case ISD::SETCC: {
4128     MVT VT0 = Node->getOperand(0).getValueType();
4129     assert(isTypeLegal(TLI.getSetCCResultType(VT0))
4130            && "SetCC type is not legal??");
4131     Result = DAG.getNode(ISD::SETCC, dl, TLI.getSetCCResultType(VT0),
4132                          Node->getOperand(0), Node->getOperand(1),
4133                          Node->getOperand(2));
4134     break;
4135   }
4136   case ISD::TRUNCATE:
4137     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4138     case Legal:
4139       Result = LegalizeOp(Node->getOperand(0));
4140       assert(Result.getValueType().bitsGE(NVT) &&
4141              "This truncation doesn't make sense!");
4142       if (Result.getValueType().bitsGT(NVT))    // Truncate to NVT instead of VT
4143         Result = DAG.getNode(ISD::TRUNCATE, dl, NVT, Result);
4144       break;
4145     case Promote:
4146       // The truncation is not required, because we don't guarantee anything
4147       // about high bits anyway.
4148       Result = PromoteOp(Node->getOperand(0));
4149       break;
4150     case Expand:
4151       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
4152       // Truncate the low part of the expanded value to the result type
4153       Result = DAG.getNode(ISD::TRUNCATE, dl, NVT, Tmp1);
4154     }
4155     break;
4156   case ISD::SIGN_EXTEND:
4157   case ISD::ZERO_EXTEND:
4158   case ISD::ANY_EXTEND:
4159     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4160     case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
4161     case Legal:
4162       // Input is legal?  Just do extend all the way to the larger type.
4163       Result = DAG.getNode(Node->getOpcode(), dl, NVT, Node->getOperand(0));
4164       break;
4165     case Promote:
4166       // Promote the reg if it's smaller.
4167       Result = PromoteOp(Node->getOperand(0));
4168       // The high bits are not guaranteed to be anything.  Insert an extend.
4169       if (Node->getOpcode() == ISD::SIGN_EXTEND)
4170         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Result,
4171                          DAG.getValueType(Node->getOperand(0).getValueType()));
4172       else if (Node->getOpcode() == ISD::ZERO_EXTEND)
4173         Result = DAG.getZeroExtendInReg(Result, dl,
4174                                         Node->getOperand(0).getValueType());
4175       break;
4176     }
4177     break;
4178   case ISD::CONVERT_RNDSAT: {
4179     ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(Node)->getCvtCode();
4180     assert ((CvtCode == ISD::CVT_SS || CvtCode == ISD::CVT_SU ||
4181              CvtCode == ISD::CVT_US || CvtCode == ISD::CVT_UU ||
4182              CvtCode == ISD::CVT_SF || CvtCode == ISD::CVT_UF) &&
4183             "can only promote integers");
4184     Result = DAG.getConvertRndSat(NVT, dl, Node->getOperand(0),
4185                                   Node->getOperand(1), Node->getOperand(2),
4186                                   Node->getOperand(3), Node->getOperand(4),
4187                                   CvtCode);
4188     break;
4189
4190   }
4191   case ISD::BIT_CONVERT:
4192     Result = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
4193                               Node->getValueType(0), dl);
4194     Result = PromoteOp(Result);
4195     break;
4196
4197   case ISD::FP_EXTEND:
4198     assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
4199   case ISD::FP_ROUND:
4200     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4201     case Expand: assert(0 && "BUG: Cannot expand FP regs!");
4202     case Promote:  assert(0 && "Unreachable with 2 FP types!");
4203     case Legal:
4204       if (Node->getConstantOperandVal(1) == 0) {
4205         // Input is legal?  Do an FP_ROUND_INREG.
4206         Result = DAG.getNode(ISD::FP_ROUND_INREG, dl, NVT, Node->getOperand(0),
4207                              DAG.getValueType(VT));
4208       } else {
4209         // Just remove the truncate, it isn't affecting the value.
4210         Result = DAG.getNode(ISD::FP_ROUND, dl, NVT, Node->getOperand(0),
4211                              Node->getOperand(1));
4212       }
4213       break;
4214     }
4215     break;
4216   case ISD::SINT_TO_FP:
4217   case ISD::UINT_TO_FP:
4218     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4219     case Legal:
4220       // No extra round required here.
4221       Result = DAG.getNode(Node->getOpcode(), dl, NVT, Node->getOperand(0));
4222       break;
4223
4224     case Promote:
4225       Result = PromoteOp(Node->getOperand(0));
4226       if (Node->getOpcode() == ISD::SINT_TO_FP)
4227         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Result.getValueType(),
4228                              Result,
4229                          DAG.getValueType(Node->getOperand(0).getValueType()));
4230       else
4231         Result = DAG.getZeroExtendInReg(Result, dl,
4232                                         Node->getOperand(0).getValueType());
4233       // No extra round required here.
4234       Result = DAG.getNode(Node->getOpcode(), dl, NVT, Result);
4235       break;
4236     case Expand:
4237       Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, NVT,
4238                              Node->getOperand(0), dl);
4239       // Round if we cannot tolerate excess precision.
4240       if (NoExcessFPPrecision)
4241         Result = DAG.getNode(ISD::FP_ROUND_INREG, dl, NVT, Result,
4242                              DAG.getValueType(VT));
4243       break;
4244     }
4245     break;
4246
4247   case ISD::SIGN_EXTEND_INREG:
4248     Result = PromoteOp(Node->getOperand(0));
4249     Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Result,
4250                          Node->getOperand(1));
4251     break;
4252   case ISD::FP_TO_SINT:
4253   case ISD::FP_TO_UINT:
4254     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4255     case Legal:
4256     case Expand:
4257       Tmp1 = Node->getOperand(0);
4258       break;
4259     case Promote:
4260       // The input result is prerounded, so we don't have to do anything
4261       // special.
4262       Tmp1 = PromoteOp(Node->getOperand(0));
4263       break;
4264     }
4265     // If we're promoting a UINT to a larger size, check to see if the new node
4266     // will be legal.  If it isn't, check to see if FP_TO_SINT is legal, since
4267     // we can use that instead.  This allows us to generate better code for
4268     // FP_TO_UINT for small destination sizes on targets where FP_TO_UINT is not
4269     // legal, such as PowerPC.
4270     if (Node->getOpcode() == ISD::FP_TO_UINT &&
4271         !TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NVT) &&
4272         (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NVT) ||
4273          TLI.getOperationAction(ISD::FP_TO_SINT, NVT)==TargetLowering::Custom)){
4274       Result = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, Tmp1);
4275     } else {
4276       Result = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4277     }
4278     break;
4279
4280   case ISD::FABS:
4281   case ISD::FNEG:
4282     Tmp1 = PromoteOp(Node->getOperand(0));
4283     assert(Tmp1.getValueType() == NVT);
4284     Result = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4285     // NOTE: we do not have to do any extra rounding here for
4286     // NoExcessFPPrecision, because we know the input will have the appropriate
4287     // precision, and these operations don't modify precision at all.
4288     break;
4289
4290   case ISD::FLOG:
4291   case ISD::FLOG2:
4292   case ISD::FLOG10:
4293   case ISD::FEXP:
4294   case ISD::FEXP2:
4295   case ISD::FSQRT:
4296   case ISD::FSIN:
4297   case ISD::FCOS:
4298   case ISD::FTRUNC:
4299   case ISD::FFLOOR:
4300   case ISD::FCEIL:
4301   case ISD::FRINT:
4302   case ISD::FNEARBYINT:
4303     Tmp1 = PromoteOp(Node->getOperand(0));
4304     assert(Tmp1.getValueType() == NVT);
4305     Result = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4306     if (NoExcessFPPrecision)
4307       Result = DAG.getNode(ISD::FP_ROUND_INREG, dl, NVT, Result,
4308                            DAG.getValueType(VT));
4309     break;
4310
4311   case ISD::FPOW:
4312   case ISD::FPOWI: {
4313     // Promote f32 pow(i) to f64 pow(i).  Note that this could insert a libcall
4314     // directly as well, which may be better.
4315     Tmp1 = PromoteOp(Node->getOperand(0));
4316     Tmp2 = Node->getOperand(1);
4317     if (Node->getOpcode() == ISD::FPOW)
4318       Tmp2 = PromoteOp(Tmp2);
4319     assert(Tmp1.getValueType() == NVT);
4320     Result = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4321     if (NoExcessFPPrecision)
4322       Result = DAG.getNode(ISD::FP_ROUND_INREG, dl, NVT, Result,
4323                            DAG.getValueType(VT));
4324     break;
4325   }
4326
4327   case ISD::ATOMIC_CMP_SWAP: {
4328     AtomicSDNode* AtomNode = cast<AtomicSDNode>(Node);
4329     Tmp2 = PromoteOp(Node->getOperand(2));
4330     Tmp3 = PromoteOp(Node->getOperand(3));
4331     Result = DAG.getAtomic(Node->getOpcode(), dl, AtomNode->getMemoryVT(),
4332                            AtomNode->getChain(),
4333                            AtomNode->getBasePtr(), Tmp2, Tmp3,
4334                            AtomNode->getSrcValue(),
4335                            AtomNode->getAlignment());
4336     // Remember that we legalized the chain.
4337     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4338     break;
4339   }
4340   case ISD::ATOMIC_LOAD_ADD:
4341   case ISD::ATOMIC_LOAD_SUB:
4342   case ISD::ATOMIC_LOAD_AND:
4343   case ISD::ATOMIC_LOAD_OR:
4344   case ISD::ATOMIC_LOAD_XOR:
4345   case ISD::ATOMIC_LOAD_NAND:
4346   case ISD::ATOMIC_LOAD_MIN:
4347   case ISD::ATOMIC_LOAD_MAX:
4348   case ISD::ATOMIC_LOAD_UMIN:
4349   case ISD::ATOMIC_LOAD_UMAX:
4350   case ISD::ATOMIC_SWAP: {
4351     AtomicSDNode* AtomNode = cast<AtomicSDNode>(Node);
4352     Tmp2 = PromoteOp(Node->getOperand(2));
4353     Result = DAG.getAtomic(Node->getOpcode(), dl, AtomNode->getMemoryVT(),
4354                            AtomNode->getChain(),
4355                            AtomNode->getBasePtr(), Tmp2,
4356                            AtomNode->getSrcValue(),
4357                            AtomNode->getAlignment());
4358     // Remember that we legalized the chain.
4359     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4360     break;
4361   }
4362
4363   case ISD::AND:
4364   case ISD::OR:
4365   case ISD::XOR:
4366   case ISD::ADD:
4367   case ISD::SUB:
4368   case ISD::MUL:
4369     // The input may have strange things in the top bits of the registers, but
4370     // these operations don't care.  They may have weird bits going out, but
4371     // that too is okay if they are integer operations.
4372     Tmp1 = PromoteOp(Node->getOperand(0));
4373     Tmp2 = PromoteOp(Node->getOperand(1));
4374     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
4375     Result = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4376     break;
4377   case ISD::FADD:
4378   case ISD::FSUB:
4379   case ISD::FMUL:
4380     Tmp1 = PromoteOp(Node->getOperand(0));
4381     Tmp2 = PromoteOp(Node->getOperand(1));
4382     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
4383     Result = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4384
4385     // Floating point operations will give excess precision that we may not be
4386     // able to tolerate.  If we DO allow excess precision, just leave it,
4387     // otherwise excise it.
4388     // FIXME: Why would we need to round FP ops more than integer ones?
4389     //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
4390     if (NoExcessFPPrecision)
4391       Result = DAG.getNode(ISD::FP_ROUND_INREG, dl, NVT, Result,
4392                            DAG.getValueType(VT));
4393     break;
4394
4395   case ISD::SDIV:
4396   case ISD::SREM:
4397     // These operators require that their input be sign extended.
4398     Tmp1 = PromoteOp(Node->getOperand(0));
4399     Tmp2 = PromoteOp(Node->getOperand(1));
4400     if (NVT.isInteger()) {
4401       Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Tmp1,
4402                          DAG.getValueType(VT));
4403       Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Tmp2,
4404                          DAG.getValueType(VT));
4405     }
4406     Result = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4407
4408     // Perform FP_ROUND: this is probably overly pessimistic.
4409     if (NVT.isFloatingPoint() && NoExcessFPPrecision)
4410       Result = DAG.getNode(ISD::FP_ROUND_INREG, dl, NVT, Result,
4411                            DAG.getValueType(VT));
4412     break;
4413   case ISD::FDIV:
4414   case ISD::FREM:
4415   case ISD::FCOPYSIGN:
4416     // These operators require that their input be fp extended.
4417     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4418     case Expand: assert(0 && "not implemented");
4419     case Legal:   Tmp1 = LegalizeOp(Node->getOperand(0)); break;
4420     case Promote: Tmp1 = PromoteOp(Node->getOperand(0));  break;
4421     }
4422     switch (getTypeAction(Node->getOperand(1).getValueType())) {
4423     case Expand: assert(0 && "not implemented");
4424     case Legal:   Tmp2 = LegalizeOp(Node->getOperand(1)); break;
4425     case Promote: Tmp2 = PromoteOp(Node->getOperand(1)); break;
4426     }
4427     Result = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4428
4429     // Perform FP_ROUND: this is probably overly pessimistic.
4430     if (NoExcessFPPrecision && Node->getOpcode() != ISD::FCOPYSIGN)
4431       Result = DAG.getNode(ISD::FP_ROUND_INREG, dl, NVT, Result,
4432                            DAG.getValueType(VT));
4433     break;
4434
4435   case ISD::UDIV:
4436   case ISD::UREM:
4437     // These operators require that their input be zero extended.
4438     Tmp1 = PromoteOp(Node->getOperand(0));
4439     Tmp2 = PromoteOp(Node->getOperand(1));
4440     assert(NVT.isInteger() && "Operators don't apply to FP!");
4441     Tmp1 = DAG.getZeroExtendInReg(Tmp1, dl, VT);
4442     Tmp2 = DAG.getZeroExtendInReg(Tmp2, dl, VT);
4443     Result = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4444     break;
4445
4446   case ISD::SHL:
4447     Tmp1 = PromoteOp(Node->getOperand(0));
4448     Result = DAG.getNode(ISD::SHL, dl, NVT, Tmp1, Node->getOperand(1));
4449     break;
4450   case ISD::SRA:
4451     // The input value must be properly sign extended.
4452     Tmp1 = PromoteOp(Node->getOperand(0));
4453     Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Tmp1,
4454                        DAG.getValueType(VT));
4455     Result = DAG.getNode(ISD::SRA, dl, NVT, Tmp1, Node->getOperand(1));
4456     break;
4457   case ISD::SRL:
4458     // The input value must be properly zero extended.
4459     Tmp1 = PromoteOp(Node->getOperand(0));
4460     Tmp1 = DAG.getZeroExtendInReg(Tmp1, dl, VT);
4461     Result = DAG.getNode(ISD::SRL, dl, NVT, Tmp1, Node->getOperand(1));
4462     break;
4463
4464   case ISD::VAARG:
4465     Tmp1 = Node->getOperand(0);   // Get the chain.
4466     Tmp2 = Node->getOperand(1);   // Get the pointer.
4467     if (TLI.getOperationAction(ISD::VAARG, VT) == TargetLowering::Custom) {
4468       Tmp3 = DAG.getVAArg(VT, dl, Tmp1, Tmp2, Node->getOperand(2));
4469       Result = TLI.LowerOperation(Tmp3, DAG);
4470     } else {
4471       const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
4472       SDValue VAList = DAG.getLoad(TLI.getPointerTy(), dl, Tmp1, Tmp2, V, 0);
4473       // Increment the pointer, VAList, to the next vaarg
4474       Tmp3 = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), VAList,
4475                          DAG.getConstant(VT.getSizeInBits()/8,
4476                                          TLI.getPointerTy()));
4477       // Store the incremented VAList to the legalized pointer
4478       Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Tmp2, V, 0);
4479       // Load the actual argument out of the pointer VAList
4480       Result = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Tmp3, VAList, NULL, 0, VT);
4481     }
4482     // Remember that we legalized the chain.
4483     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4484     break;
4485
4486   case ISD::LOAD: {
4487     LoadSDNode *LD = cast<LoadSDNode>(Node);
4488     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(Node)
4489       ? ISD::EXTLOAD : LD->getExtensionType();
4490     Result = DAG.getExtLoad(ExtType, dl, NVT,
4491                             LD->getChain(), LD->getBasePtr(),
4492                             LD->getSrcValue(), LD->getSrcValueOffset(),
4493                             LD->getMemoryVT(),
4494                             LD->isVolatile(),
4495                             LD->getAlignment());
4496     // Remember that we legalized the chain.
4497     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4498     break;
4499   }
4500   case ISD::SELECT: {
4501     Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
4502     Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
4503
4504     MVT VT2 = Tmp2.getValueType();
4505     assert(VT2 == Tmp3.getValueType()
4506            && "PromoteOp SELECT: Operands 2 and 3 ValueTypes don't match");
4507     // Ensure that the resulting node is at least the same size as the operands'
4508     // value types, because we cannot assume that TLI.getSetCCValueType() is
4509     // constant.
4510     Result = DAG.getNode(ISD::SELECT, dl, VT2, Node->getOperand(0), Tmp2, Tmp3);
4511     break;
4512   }
4513   case ISD::SELECT_CC:
4514     Tmp2 = PromoteOp(Node->getOperand(2));   // True
4515     Tmp3 = PromoteOp(Node->getOperand(3));   // False
4516     Result = DAG.getNode(ISD::SELECT_CC, dl, NVT, Node->getOperand(0),
4517                          Node->getOperand(1), Tmp2, Tmp3, Node->getOperand(4));
4518     break;
4519   case ISD::BSWAP:
4520     Tmp1 = Node->getOperand(0);
4521     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Tmp1);
4522     Tmp1 = DAG.getNode(ISD::BSWAP, dl, NVT, Tmp1);
4523     Result = DAG.getNode(ISD::SRL, dl, NVT, Tmp1,
4524                          DAG.getConstant(NVT.getSizeInBits() -
4525                                          VT.getSizeInBits(),
4526                                          TLI.getShiftAmountTy()));
4527     break;
4528   case ISD::CTPOP:
4529   case ISD::CTTZ:
4530   case ISD::CTLZ:
4531     // Zero extend the argument
4532     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
4533     // Perform the larger operation, then subtract if needed.
4534     Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4535     switch(Node->getOpcode()) {
4536     case ISD::CTPOP:
4537       Result = Tmp1;
4538       break;
4539     case ISD::CTTZ:
4540       // if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
4541       Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(Tmp1.getValueType()), Tmp1,
4542                           DAG.getConstant(NVT.getSizeInBits(), NVT),
4543                           ISD::SETEQ);
4544       Result = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2,
4545                            DAG.getConstant(VT.getSizeInBits(), NVT), Tmp1);
4546       break;
4547     case ISD::CTLZ:
4548       //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
4549       Result = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
4550                            DAG.getConstant(NVT.getSizeInBits() -
4551                                            VT.getSizeInBits(), NVT));
4552       break;
4553     }
4554     break;
4555   case ISD::EXTRACT_SUBVECTOR:
4556     Result = PromoteOp(ExpandEXTRACT_SUBVECTOR(Op));
4557     break;
4558   case ISD::EXTRACT_VECTOR_ELT:
4559     Result = PromoteOp(ExpandEXTRACT_VECTOR_ELT(Op));
4560     break;
4561   }
4562
4563   assert(Result.getNode() && "Didn't set a result!");
4564
4565   // Make sure the result is itself legal.
4566   Result = LegalizeOp(Result);
4567
4568   // Remember that we promoted this!
4569   AddPromotedOperand(Op, Result);
4570   return Result;
4571 }
4572
4573 /// ExpandEXTRACT_VECTOR_ELT - Expand an EXTRACT_VECTOR_ELT operation into
4574 /// a legal EXTRACT_VECTOR_ELT operation, scalar code, or memory traffic,
4575 /// based on the vector type. The return type of this matches the element type
4576 /// of the vector, which may not be legal for the target.
4577 SDValue SelectionDAGLegalize::ExpandEXTRACT_VECTOR_ELT(SDValue Op) {
4578   // We know that operand #0 is the Vec vector.  If the index is a constant
4579   // or if the invec is a supported hardware type, we can use it.  Otherwise,
4580   // lower to a store then an indexed load.
4581   SDValue Vec = Op.getOperand(0);
4582   SDValue Idx = Op.getOperand(1);
4583   DebugLoc dl = Op.getDebugLoc();
4584
4585   MVT TVT = Vec.getValueType();
4586   unsigned NumElems = TVT.getVectorNumElements();
4587
4588   switch (TLI.getOperationAction(ISD::EXTRACT_VECTOR_ELT, TVT)) {
4589   default: assert(0 && "This action is not supported yet!");
4590   case TargetLowering::Custom: {
4591     Vec = LegalizeOp(Vec);
4592     Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
4593     SDValue Tmp3 = TLI.LowerOperation(Op, DAG);
4594     if (Tmp3.getNode())
4595       return Tmp3;
4596     break;
4597   }
4598   case TargetLowering::Legal:
4599     if (isTypeLegal(TVT)) {
4600       Vec = LegalizeOp(Vec);
4601       Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
4602       return Op;
4603     }
4604     break;
4605   case TargetLowering::Promote:
4606     assert(TVT.isVector() && "not vector type");
4607     // fall thru to expand since vectors are by default are promote
4608   case TargetLowering::Expand:
4609     break;
4610   }
4611
4612   if (NumElems == 1)
4613     // This must be an access of the only element.  Return it.
4614     return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Vec);
4615   else
4616     return ExpandExtractFromVectorThroughStack(Op);
4617 }
4618
4619 SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
4620   SDValue Vec = Op.getOperand(0);
4621   SDValue Idx = Op.getOperand(1);
4622   DebugLoc dl = Op.getDebugLoc();
4623   // Store the value to a temporary stack slot, then LOAD the returned part.
4624   SDValue StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
4625   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, NULL, 0);
4626
4627   // Add the offset to the index.
4628   unsigned EltSize =
4629       Vec.getValueType().getVectorElementType().getSizeInBits()/8;
4630   Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
4631                     DAG.getConstant(EltSize, Idx.getValueType()));
4632
4633   if (Idx.getValueType().bitsGT(TLI.getPointerTy()))
4634     Idx = DAG.getNode(ISD::TRUNCATE, dl, TLI.getPointerTy(), Idx);
4635   else
4636     Idx = DAG.getNode(ISD::ZERO_EXTEND, dl, TLI.getPointerTy(), Idx);
4637
4638   StackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx, StackPtr);
4639
4640   return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, NULL, 0);
4641 }
4642
4643 /// ExpandEXTRACT_SUBVECTOR - Expand a EXTRACT_SUBVECTOR operation.  For now
4644 /// we assume the operation can be split if it is not already legal.
4645 SDValue SelectionDAGLegalize::ExpandEXTRACT_SUBVECTOR(SDValue Op) {
4646   // We know that operand #0 is the Vec vector.  For now we assume the index
4647   // is a constant and that the extracted result is a supported hardware type.
4648   SDValue Vec = Op.getOperand(0);
4649   SDValue Idx = LegalizeOp(Op.getOperand(1));
4650
4651   unsigned NumElems = Vec.getValueType().getVectorNumElements();
4652
4653   if (NumElems == Op.getValueType().getVectorNumElements()) {
4654     // This must be an access of the desired vector length.  Return it.
4655     return Vec;
4656   }
4657
4658   ConstantSDNode *CIdx = cast<ConstantSDNode>(Idx);
4659   SDValue Lo, Hi;
4660   SplitVectorOp(Vec, Lo, Hi);
4661   if (CIdx->getZExtValue() < NumElems/2) {
4662     Vec = Lo;
4663   } else {
4664     Vec = Hi;
4665     Idx = DAG.getConstant(CIdx->getZExtValue() - NumElems/2,
4666                           Idx.getValueType());
4667   }
4668
4669   // It's now an extract from the appropriate high or low part.  Recurse.
4670   Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
4671   return ExpandEXTRACT_SUBVECTOR(Op);
4672 }
4673
4674 /// LegalizeSetCCOperands - Attempts to create a legal LHS and RHS for a SETCC
4675 /// with condition CC on the current target.  This usually involves legalizing
4676 /// or promoting the arguments.  In the case where LHS and RHS must be expanded,
4677 /// there may be no choice but to create a new SetCC node to represent the
4678 /// legalized value of setcc lhs, rhs.  In this case, the value is returned in
4679 /// LHS, and the SDValue returned in RHS has a nil SDNode value.
4680 void SelectionDAGLegalize::LegalizeSetCCOperands(SDValue &LHS,
4681                                                  SDValue &RHS,
4682                                                  SDValue &CC,
4683                                                  DebugLoc dl) {
4684   SDValue Tmp1, Tmp2, Tmp3, Result;
4685
4686   switch (getTypeAction(LHS.getValueType())) {
4687   case Legal:
4688     Tmp1 = LegalizeOp(LHS);   // LHS
4689     Tmp2 = LegalizeOp(RHS);   // RHS
4690     break;
4691   case Promote:
4692     Tmp1 = PromoteOp(LHS);   // LHS
4693     Tmp2 = PromoteOp(RHS);   // RHS
4694
4695     // If this is an FP compare, the operands have already been extended.
4696     if (LHS.getValueType().isInteger()) {
4697       MVT VT = LHS.getValueType();
4698       MVT NVT = TLI.getTypeToTransformTo(VT);
4699
4700       // Otherwise, we have to insert explicit sign or zero extends.  Note
4701       // that we could insert sign extends for ALL conditions, but zero extend
4702       // is cheaper on many machines (an AND instead of two shifts), so prefer
4703       // it.
4704       switch (cast<CondCodeSDNode>(CC)->get()) {
4705       default: assert(0 && "Unknown integer comparison!");
4706       case ISD::SETEQ:
4707       case ISD::SETNE:
4708       case ISD::SETUGE:
4709       case ISD::SETUGT:
4710       case ISD::SETULE:
4711       case ISD::SETULT:
4712         // ALL of these operations will work if we either sign or zero extend
4713         // the operands (including the unsigned comparisons!).  Zero extend is
4714         // usually a simpler/cheaper operation, so prefer it.
4715         Tmp1 = DAG.getZeroExtendInReg(Tmp1, dl, VT);
4716         Tmp2 = DAG.getZeroExtendInReg(Tmp2, dl, VT);
4717         break;
4718       case ISD::SETGE:
4719       case ISD::SETGT:
4720       case ISD::SETLT:
4721       case ISD::SETLE:
4722         Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Tmp1,
4723                            DAG.getValueType(VT));
4724         Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Tmp2,
4725                            DAG.getValueType(VT));
4726         Tmp1 = LegalizeOp(Tmp1); // Relegalize new nodes.
4727         Tmp2 = LegalizeOp(Tmp2); // Relegalize new nodes.
4728         break;
4729       }
4730     }
4731     break;
4732   case Expand: {
4733     MVT VT = LHS.getValueType();
4734     if (VT == MVT::f32 || VT == MVT::f64) {
4735       // Expand into one or more soft-fp libcall(s).
4736       RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
4737       switch (cast<CondCodeSDNode>(CC)->get()) {
4738       case ISD::SETEQ:
4739       case ISD::SETOEQ:
4740         LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : RTLIB::OEQ_F64;
4741         break;
4742       case ISD::SETNE:
4743       case ISD::SETUNE:
4744         LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 : RTLIB::UNE_F64;
4745         break;
4746       case ISD::SETGE:
4747       case ISD::SETOGE:
4748         LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : RTLIB::OGE_F64;
4749         break;
4750       case ISD::SETLT:
4751       case ISD::SETOLT:
4752         LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : RTLIB::OLT_F64;
4753         break;
4754       case ISD::SETLE:
4755       case ISD::SETOLE:
4756         LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : RTLIB::OLE_F64;
4757         break;
4758       case ISD::SETGT:
4759       case ISD::SETOGT:
4760         LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : RTLIB::OGT_F64;
4761         break;
4762       case ISD::SETUO:
4763         LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : RTLIB::UO_F64;
4764         break;
4765       case ISD::SETO:
4766         LC1 = (VT == MVT::f32) ? RTLIB::O_F32 : RTLIB::O_F64;
4767         break;
4768       default:
4769         LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : RTLIB::UO_F64;
4770         switch (cast<CondCodeSDNode>(CC)->get()) {
4771         case ISD::SETONE:
4772           // SETONE = SETOLT | SETOGT
4773           LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : RTLIB::OLT_F64;
4774           // Fallthrough
4775         case ISD::SETUGT:
4776           LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 : RTLIB::OGT_F64;
4777           break;
4778         case ISD::SETUGE:
4779           LC2 = (VT == MVT::f32) ? RTLIB::OGE_F32 : RTLIB::OGE_F64;
4780           break;
4781         case ISD::SETULT:
4782           LC2 = (VT == MVT::f32) ? RTLIB::OLT_F32 : RTLIB::OLT_F64;
4783           break;
4784         case ISD::SETULE:
4785           LC2 = (VT == MVT::f32) ? RTLIB::OLE_F32 : RTLIB::OLE_F64;
4786           break;
4787         case ISD::SETUEQ:
4788           LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : RTLIB::OEQ_F64;
4789           break;
4790         default: assert(0 && "Unsupported FP setcc!");
4791         }
4792       }
4793
4794       SDValue Dummy;
4795       SDValue Ops[2] = { LHS, RHS };
4796       Tmp1 = ExpandLibCall(LC1, DAG.getMergeValues(Ops, 2, dl).getNode(),
4797                            false /*sign irrelevant*/, Dummy);
4798       Tmp2 = DAG.getConstant(0, MVT::i32);
4799       CC = DAG.getCondCode(TLI.getCmpLibcallCC(LC1));
4800       if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
4801         Tmp1 = DAG.getNode(ISD::SETCC, dl,
4802                            TLI.getSetCCResultType(Tmp1.getValueType()),
4803                            Tmp1, Tmp2, CC);
4804         LHS = ExpandLibCall(LC2, DAG.getMergeValues(Ops, 2, dl).getNode(),
4805                             false /*sign irrelevant*/, Dummy);
4806         Tmp2 = DAG.getNode(ISD::SETCC, dl,
4807                            TLI.getSetCCResultType(LHS.getValueType()), LHS,
4808                            Tmp2, DAG.getCondCode(TLI.getCmpLibcallCC(LC2)));
4809         Tmp1 = DAG.getNode(ISD::OR, dl, Tmp1.getValueType(), Tmp1, Tmp2);
4810         Tmp2 = SDValue();
4811       }
4812       LHS = LegalizeOp(Tmp1);
4813       RHS = Tmp2;
4814       return;
4815     }
4816
4817     SDValue LHSLo, LHSHi, RHSLo, RHSHi;
4818     ExpandOp(LHS, LHSLo, LHSHi);
4819     ExpandOp(RHS, RHSLo, RHSHi);
4820     ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
4821
4822     if (VT==MVT::ppcf128) {
4823       // FIXME:  This generated code sucks.  We want to generate
4824       //         FCMPU crN, hi1, hi2
4825       //         BNE crN, L:
4826       //         FCMPU crN, lo1, lo2
4827       // The following can be improved, but not that much.
4828       Tmp1 = DAG.getSetCC(dl, TLI.getSetCCResultType(LHSHi.getValueType()),
4829                           LHSHi, RHSHi, ISD::SETOEQ);
4830       Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(LHSLo.getValueType()),
4831                           LHSLo, RHSLo, CCCode);
4832       Tmp3 = DAG.getNode(ISD::AND, dl, Tmp1.getValueType(), Tmp1, Tmp2);
4833       Tmp1 = DAG.getSetCC(dl, TLI.getSetCCResultType(LHSHi.getValueType()),
4834                           LHSHi, RHSHi, ISD::SETUNE);
4835       Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(LHSHi.getValueType()),
4836                           LHSHi, RHSHi, CCCode);
4837       Tmp1 = DAG.getNode(ISD::AND, dl, Tmp1.getValueType(), Tmp1, Tmp2);
4838       Tmp1 = DAG.getNode(ISD::OR, dl, Tmp1.getValueType(), Tmp1, Tmp3);
4839       Tmp2 = SDValue();
4840       break;
4841     }
4842
4843     switch (CCCode) {
4844     case ISD::SETEQ:
4845     case ISD::SETNE:
4846       if (RHSLo == RHSHi)
4847         if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo))
4848           if (RHSCST->isAllOnesValue()) {
4849             // Comparison to -1.
4850             Tmp1 = DAG.getNode(ISD::AND, dl,LHSLo.getValueType(), LHSLo, LHSHi);
4851             Tmp2 = RHSLo;
4852             break;
4853           }
4854
4855       Tmp1 = DAG.getNode(ISD::XOR, dl, LHSLo.getValueType(), LHSLo, RHSLo);
4856       Tmp2 = DAG.getNode(ISD::XOR, dl, LHSLo.getValueType(), LHSHi, RHSHi);
4857       Tmp1 = DAG.getNode(ISD::OR, dl, Tmp1.getValueType(), Tmp1, Tmp2);
4858       Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
4859       break;
4860     default:
4861       // If this is a comparison of the sign bit, just look at the top part.
4862       // X > -1,  x < 0
4863       if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(RHS))
4864         if ((cast<CondCodeSDNode>(CC)->get() == ISD::SETLT &&
4865              CST->isNullValue()) ||               // X < 0
4866             (cast<CondCodeSDNode>(CC)->get() == ISD::SETGT &&
4867              CST->isAllOnesValue())) {            // X > -1
4868           Tmp1 = LHSHi;
4869           Tmp2 = RHSHi;
4870           break;
4871         }
4872
4873       // FIXME: This generated code sucks.
4874       ISD::CondCode LowCC;
4875       switch (CCCode) {
4876       default: assert(0 && "Unknown integer setcc!");
4877       case ISD::SETLT:
4878       case ISD::SETULT: LowCC = ISD::SETULT; break;
4879       case ISD::SETGT:
4880       case ISD::SETUGT: LowCC = ISD::SETUGT; break;
4881       case ISD::SETLE:
4882       case ISD::SETULE: LowCC = ISD::SETULE; break;
4883       case ISD::SETGE:
4884       case ISD::SETUGE: LowCC = ISD::SETUGE; break;
4885       }
4886
4887       // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
4888       // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
4889       // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
4890
4891       // NOTE: on targets without efficient SELECT of bools, we can always use
4892       // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
4893       TargetLowering::DAGCombinerInfo DagCombineInfo(DAG, false, true, NULL);
4894       Tmp1 = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSLo.getValueType()),
4895                                LHSLo, RHSLo, LowCC, false, DagCombineInfo, dl);
4896       if (!Tmp1.getNode())
4897         Tmp1 = DAG.getSetCC(dl, TLI.getSetCCResultType(LHSLo.getValueType()),
4898                             LHSLo, RHSLo, LowCC);
4899       Tmp2 = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSHi.getValueType()),
4900                                LHSHi, RHSHi, CCCode, false, DagCombineInfo, dl);
4901       if (!Tmp2.getNode())
4902         Tmp2 = DAG.getNode(ISD::SETCC, dl,
4903                            TLI.getSetCCResultType(LHSHi.getValueType()),
4904                            LHSHi, RHSHi, CC);
4905
4906       ConstantSDNode *Tmp1C = dyn_cast<ConstantSDNode>(Tmp1.getNode());
4907       ConstantSDNode *Tmp2C = dyn_cast<ConstantSDNode>(Tmp2.getNode());
4908       if ((Tmp1C && Tmp1C->isNullValue()) ||
4909           (Tmp2C && Tmp2C->isNullValue() &&
4910            (CCCode == ISD::SETLE || CCCode == ISD::SETGE ||
4911             CCCode == ISD::SETUGE || CCCode == ISD::SETULE)) ||
4912           (Tmp2C && Tmp2C->getAPIntValue() == 1 &&
4913            (CCCode == ISD::SETLT || CCCode == ISD::SETGT ||
4914             CCCode == ISD::SETUGT || CCCode == ISD::SETULT))) {
4915         // low part is known false, returns high part.
4916         // For LE / GE, if high part is known false, ignore the low part.
4917         // For LT / GT, if high part is known true, ignore the low part.
4918         Tmp1 = Tmp2;
4919         Tmp2 = SDValue();
4920       } else {
4921         Result = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSHi.getValueType()),
4922                                    LHSHi, RHSHi, ISD::SETEQ, false,
4923                                    DagCombineInfo, dl);
4924         if (!Result.getNode())
4925           Result=DAG.getSetCC(dl, TLI.getSetCCResultType(LHSHi.getValueType()),
4926                               LHSHi, RHSHi, ISD::SETEQ);
4927         Result = LegalizeOp(DAG.getNode(ISD::SELECT, dl, Tmp1.getValueType(),
4928                                         Result, Tmp1, Tmp2));
4929         Tmp1 = Result;
4930         Tmp2 = SDValue();
4931       }
4932     }
4933   }
4934   }
4935   LHS = Tmp1;
4936   RHS = Tmp2;
4937 }
4938
4939 /// LegalizeSetCCCondCode - Legalize a SETCC with given LHS and RHS and
4940 /// condition code CC on the current target. This routine assumes LHS and rHS
4941 /// have already been legalized by LegalizeSetCCOperands. It expands SETCC with
4942 /// illegal condition code into AND / OR of multiple SETCC values.
4943 void SelectionDAGLegalize::LegalizeSetCCCondCode(MVT VT,
4944                                                  SDValue &LHS, SDValue &RHS,
4945                                                  SDValue &CC,
4946                                                  DebugLoc dl) {
4947   MVT OpVT = LHS.getValueType();
4948   ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
4949   switch (TLI.getCondCodeAction(CCCode, OpVT)) {
4950   default: assert(0 && "Unknown condition code action!");
4951   case TargetLowering::Legal:
4952     // Nothing to do.
4953     break;
4954   case TargetLowering::Expand: {
4955     ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
4956     unsigned Opc = 0;
4957     switch (CCCode) {
4958     default: assert(0 && "Don't know how to expand this condition!"); abort();
4959     case ISD::SETOEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETO;  Opc = ISD::AND; break;
4960     case ISD::SETOGT: CC1 = ISD::SETGT; CC2 = ISD::SETO;  Opc = ISD::AND; break;
4961     case ISD::SETOGE: CC1 = ISD::SETGE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
4962     case ISD::SETOLT: CC1 = ISD::SETLT; CC2 = ISD::SETO;  Opc = ISD::AND; break;
4963     case ISD::SETOLE: CC1 = ISD::SETLE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
4964     case ISD::SETONE: CC1 = ISD::SETNE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
4965     case ISD::SETUEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
4966     case ISD::SETUGT: CC1 = ISD::SETGT; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
4967     case ISD::SETUGE: CC1 = ISD::SETGE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
4968     case ISD::SETULT: CC1 = ISD::SETLT; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
4969     case ISD::SETULE: CC1 = ISD::SETLE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
4970     case ISD::SETUNE: CC1 = ISD::SETNE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
4971     // FIXME: Implement more expansions.
4972     }
4973
4974     SDValue SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1);
4975     SDValue SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2);
4976     LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
4977     RHS = SDValue();
4978     CC  = SDValue();
4979     break;
4980   }
4981   }
4982 }
4983
4984 /// EmitStackConvert - Emit a store/load combination to the stack.  This stores
4985 /// SrcOp to a stack slot of type SlotVT, truncating it if needed.  It then does
4986 /// a load from the stack slot to DestVT, extending it if needed.
4987 /// The resultant code need not be legal.
4988 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp,
4989                                                MVT SlotVT,
4990                                                MVT DestVT,
4991                                                DebugLoc dl) {
4992   // Create the stack frame object.
4993   unsigned SrcAlign =
4994     TLI.getTargetData()->getPrefTypeAlignment(SrcOp.getValueType().
4995                                               getTypeForMVT());
4996   SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign);
4997
4998   FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
4999   int SPFI = StackPtrFI->getIndex();
5000   const Value *SV = PseudoSourceValue::getFixedStack(SPFI);
5001
5002   unsigned SrcSize = SrcOp.getValueType().getSizeInBits();
5003   unsigned SlotSize = SlotVT.getSizeInBits();
5004   unsigned DestSize = DestVT.getSizeInBits();
5005   unsigned DestAlign =
5006     TLI.getTargetData()->getPrefTypeAlignment(DestVT.getTypeForMVT());
5007
5008   // Emit a store to the stack slot.  Use a truncstore if the input value is
5009   // later than DestVT.
5010   SDValue Store;
5011
5012   if (SrcSize > SlotSize)
5013     Store = DAG.getTruncStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
5014                               SV, 0, SlotVT, false, SrcAlign);
5015   else {
5016     assert(SrcSize == SlotSize && "Invalid store");
5017     Store = DAG.getStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
5018                          SV, 0, false, SrcAlign);
5019   }
5020
5021   // Result is a load from the stack slot.
5022   if (SlotSize == DestSize)
5023     return DAG.getLoad(DestVT, dl, Store, FIPtr, SV, 0, false, DestAlign);
5024
5025   assert(SlotSize < DestSize && "Unknown extension!");
5026   return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr, SV, 0, SlotVT,
5027                         false, DestAlign);
5028 }
5029
5030 SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
5031   DebugLoc dl = Node->getDebugLoc();
5032   // Create a vector sized/aligned stack slot, store the value to element #0,
5033   // then load the whole vector back out.
5034   SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
5035
5036   FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
5037   int SPFI = StackPtrFI->getIndex();
5038
5039   SDValue Ch = DAG.getTruncStore(DAG.getEntryNode(), dl, Node->getOperand(0),
5040                                  StackPtr,
5041                                  PseudoSourceValue::getFixedStack(SPFI), 0,
5042                                  Node->getValueType(0).getVectorElementType());
5043   return DAG.getLoad(Node->getValueType(0), dl, Ch, StackPtr,
5044                      PseudoSourceValue::getFixedStack(SPFI), 0);
5045 }
5046
5047
5048 /// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
5049 /// support the operation, but do support the resultant vector type.
5050 SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
5051   unsigned NumElems = Node->getNumOperands();
5052   SDValue SplatValue = Node->getOperand(0);
5053   DebugLoc dl = Node->getDebugLoc();
5054   MVT VT = Node->getValueType(0);
5055   MVT OpVT = SplatValue.getValueType();
5056   MVT EltVT = VT.getVectorElementType();
5057
5058   // If the only non-undef value is the low element, turn this into a
5059   // SCALAR_TO_VECTOR node.  If this is { X, X, X, X }, determine X.
5060   bool isOnlyLowElement = true;
5061
5062   // FIXME: it would be far nicer to change this into map<SDValue,uint64_t>
5063   // and use a bitmask instead of a list of elements.
5064   // FIXME: this doesn't treat <0, u, 0, u> for example, as a splat.
5065   std::map<SDValue, std::vector<unsigned> > Values;
5066   Values[SplatValue].push_back(0);
5067   bool isConstant = true;
5068   if (!isa<ConstantFPSDNode>(SplatValue) && !isa<ConstantSDNode>(SplatValue) &&
5069       SplatValue.getOpcode() != ISD::UNDEF)
5070     isConstant = false;
5071
5072   for (unsigned i = 1; i < NumElems; ++i) {
5073     SDValue V = Node->getOperand(i);
5074     Values[V].push_back(i);
5075     if (V.getOpcode() != ISD::UNDEF)
5076       isOnlyLowElement = false;
5077     if (SplatValue != V)
5078       SplatValue = SDValue(0, 0);
5079
5080     // If this isn't a constant element or an undef, we can't use a constant
5081     // pool load.
5082     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V) &&
5083         V.getOpcode() != ISD::UNDEF)
5084       isConstant = false;
5085   }
5086
5087   if (isOnlyLowElement) {
5088     // If the low element is an undef too, then this whole things is an undef.
5089     if (Node->getOperand(0).getOpcode() == ISD::UNDEF)
5090       return DAG.getUNDEF(VT);
5091     // Otherwise, turn this into a scalar_to_vector node.
5092     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
5093   }
5094
5095   // If all elements are constants, create a load from the constant pool.
5096   if (isConstant) {
5097     std::vector<Constant*> CV;
5098     for (unsigned i = 0, e = NumElems; i != e; ++i) {
5099       if (ConstantFPSDNode *V =
5100           dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
5101         CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
5102       } else if (ConstantSDNode *V =
5103                  dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
5104         CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
5105       } else {
5106         assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
5107         const Type *OpNTy = OpVT.getTypeForMVT();
5108         CV.push_back(UndefValue::get(OpNTy));
5109       }
5110     }
5111     Constant *CP = ConstantVector::get(CV);
5112     SDValue CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
5113     unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
5114     return DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5115                        PseudoSourceValue::getConstantPool(), 0,
5116                        false, Alignment);
5117   }
5118
5119   if (SplatValue.getNode()) {   // Splat of one value?
5120     // Build the shuffle constant vector: <0, 0, 0, 0>
5121     SmallVector<int, 8> ZeroVec(NumElems, 0);
5122
5123     // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
5124     if (TLI.isShuffleMaskLegal(ZeroVec, Node->getValueType(0))) {
5125       // Get the splatted value into the low element of a vector register.
5126       SDValue LowValVec =
5127         DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, SplatValue);
5128
5129       // Return shuffle(LowValVec, undef, <0,0,0,0>)
5130       return DAG.getVectorShuffle(VT, dl, LowValVec, DAG.getUNDEF(VT),
5131                                   &ZeroVec[0]);
5132     }
5133   }
5134
5135   // If there are only two unique elements, we may be able to turn this into a
5136   // vector shuffle.
5137   if (Values.size() == 2) {
5138     // Get the two values in deterministic order.
5139     SDValue Val1 = Node->getOperand(1);
5140     SDValue Val2;
5141     std::map<SDValue, std::vector<unsigned> >::iterator MI = Values.begin();
5142     if (MI->first != Val1)
5143       Val2 = MI->first;
5144     else
5145       Val2 = (++MI)->first;
5146
5147     // If Val1 is an undef, make sure it ends up as Val2, to ensure that our
5148     // vector shuffle has the undef vector on the RHS.
5149     if (Val1.getOpcode() == ISD::UNDEF)
5150       std::swap(Val1, Val2);
5151
5152     // Build the shuffle constant vector: e.g. <0, 4, 0, 4>
5153     SmallVector<int, 8> ShuffleMask(NumElems, -1);
5154
5155     // Set elements of the shuffle mask for Val1.
5156     std::vector<unsigned> &Val1Elts = Values[Val1];
5157     for (unsigned i = 0, e = Val1Elts.size(); i != e; ++i)
5158       ShuffleMask[Val1Elts[i]] = 0;
5159
5160     // Set elements of the shuffle mask for Val2.
5161     std::vector<unsigned> &Val2Elts = Values[Val2];
5162     for (unsigned i = 0, e = Val2Elts.size(); i != e; ++i)
5163       if (Val2.getOpcode() != ISD::UNDEF)
5164         ShuffleMask[Val2Elts[i]] = NumElems;
5165
5166     // If the target supports SCALAR_TO_VECTOR and this shuffle mask, use it.
5167     if (TLI.isOperationLegalOrCustom(ISD::SCALAR_TO_VECTOR, VT) &&
5168         TLI.isShuffleMaskLegal(ShuffleMask, VT)) {
5169       Val1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Val1);
5170       Val2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Val2);
5171       return DAG.getVectorShuffle(VT, dl, Val1, Val2, &ShuffleMask[0]);
5172     }
5173   }
5174
5175   // Otherwise, we can't handle this case efficiently.  Allocate a sufficiently
5176   // aligned object on the stack, store each element into it, then load
5177   // the result as a vector.
5178   // Create the stack frame object.
5179   SDValue FIPtr = DAG.CreateStackTemporary(VT);
5180   int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
5181   const Value *SV = PseudoSourceValue::getFixedStack(FI);
5182
5183   // Emit a store of each element to the stack slot.
5184   SmallVector<SDValue, 8> Stores;
5185   unsigned TypeByteSize = OpVT.getSizeInBits() / 8;
5186   // Store (in the right endianness) the elements to memory.
5187   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
5188     // Ignore undef elements.
5189     if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
5190
5191     unsigned Offset = TypeByteSize*i;
5192
5193     SDValue Idx = DAG.getConstant(Offset, FIPtr.getValueType());
5194     Idx = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, Idx);
5195
5196     Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, Node->getOperand(i),
5197                                   Idx, SV, Offset));
5198   }
5199
5200   SDValue StoreChain;
5201   if (!Stores.empty())    // Not all undef elements?
5202     StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5203                              &Stores[0], Stores.size());
5204   else
5205     StoreChain = DAG.getEntryNode();
5206
5207   // Result is a load from the stack slot.
5208   return DAG.getLoad(VT, dl, StoreChain, FIPtr, SV, 0);
5209 }
5210
5211 void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
5212                                             SDValue Op, SDValue Amt,
5213                                             SDValue &Lo, SDValue &Hi,
5214                                             DebugLoc dl) {
5215   // Expand the subcomponents.
5216   SDValue LHSL, LHSH;
5217   ExpandOp(Op, LHSL, LHSH);
5218
5219   SDValue Ops[] = { LHSL, LHSH, Amt };
5220   MVT VT = LHSL.getValueType();
5221   Lo = DAG.getNode(NodeOp, dl, DAG.getVTList(VT, VT), Ops, 3);
5222   Hi = Lo.getValue(1);
5223 }
5224
5225
5226 /// ExpandShift - Try to find a clever way to expand this shift operation out to
5227 /// smaller elements.  If we can't find a way that is more efficient than a
5228 /// libcall on this target, return false.  Otherwise, return true with the
5229 /// low-parts expanded into Lo and Hi.
5230 bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDValue Op, SDValue Amt,
5231                                        SDValue &Lo, SDValue &Hi,
5232                                        DebugLoc dl) {
5233   assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
5234          "This is not a shift!");
5235
5236   MVT NVT = TLI.getTypeToTransformTo(Op.getValueType());
5237   SDValue ShAmt = LegalizeOp(Amt);
5238   MVT ShTy = ShAmt.getValueType();
5239   unsigned ShBits = ShTy.getSizeInBits();
5240   unsigned VTBits = Op.getValueType().getSizeInBits();
5241   unsigned NVTBits = NVT.getSizeInBits();
5242
5243   // Handle the case when Amt is an immediate.
5244   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Amt.getNode())) {
5245     unsigned Cst = CN->getZExtValue();
5246     // Expand the incoming operand to be shifted, so that we have its parts
5247     SDValue InL, InH;
5248     ExpandOp(Op, InL, InH);
5249     switch(Opc) {
5250     case ISD::SHL:
5251       if (Cst > VTBits) {
5252         Lo = DAG.getConstant(0, NVT);
5253         Hi = DAG.getConstant(0, NVT);
5254       } else if (Cst > NVTBits) {
5255         Lo = DAG.getConstant(0, NVT);
5256         Hi = DAG.getNode(ISD::SHL, dl,
5257                          NVT, InL, DAG.getConstant(Cst-NVTBits, ShTy));
5258       } else if (Cst == NVTBits) {
5259         Lo = DAG.getConstant(0, NVT);
5260         Hi = InL;
5261       } else {
5262         Lo = DAG.getNode(ISD::SHL, dl, NVT, InL, DAG.getConstant(Cst, ShTy));
5263         Hi = DAG.getNode(ISD::OR, dl, NVT,
5264            DAG.getNode(ISD::SHL, dl, NVT, InH, DAG.getConstant(Cst, ShTy)),
5265            DAG.getNode(ISD::SRL, dl, NVT, InL,
5266                        DAG.getConstant(NVTBits-Cst, ShTy)));
5267       }
5268       return true;
5269     case ISD::SRL:
5270       if (Cst > VTBits) {
5271         Lo = DAG.getConstant(0, NVT);
5272         Hi = DAG.getConstant(0, NVT);
5273       } else if (Cst > NVTBits) {
5274         Lo = DAG.getNode(ISD::SRL, dl, NVT,
5275                          InH, DAG.getConstant(Cst-NVTBits, ShTy));
5276         Hi = DAG.getConstant(0, NVT);
5277       } else if (Cst == NVTBits) {
5278         Lo = InH;
5279         Hi = DAG.getConstant(0, NVT);
5280       } else {
5281         Lo = DAG.getNode(ISD::OR, dl, NVT,
5282            DAG.getNode(ISD::SRL, dl, NVT, InL, DAG.getConstant(Cst, ShTy)),
5283            DAG.getNode(ISD::SHL, dl, NVT, InH,
5284                        DAG.getConstant(NVTBits-Cst, ShTy)));
5285         Hi = DAG.getNode(ISD::SRL, dl, NVT, InH, DAG.getConstant(Cst, ShTy));
5286       }
5287       return true;
5288     case ISD::SRA:
5289       if (Cst > VTBits) {
5290         Hi = Lo = DAG.getNode(ISD::SRA, dl, NVT, InH,
5291                               DAG.getConstant(NVTBits-1, ShTy));
5292       } else if (Cst > NVTBits) {
5293         Lo = DAG.getNode(ISD::SRA, dl, NVT, InH,
5294                            DAG.getConstant(Cst-NVTBits, ShTy));
5295         Hi = DAG.getNode(ISD::SRA, dl, NVT, InH,
5296                               DAG.getConstant(NVTBits-1, ShTy));
5297       } else if (Cst == NVTBits) {
5298         Lo = InH;
5299         Hi = DAG.getNode(ISD::SRA, dl, NVT, InH,
5300                               DAG.getConstant(NVTBits-1, ShTy));
5301       } else {
5302         Lo = DAG.getNode(ISD::OR, dl, NVT,
5303            DAG.getNode(ISD::SRL, dl, NVT, InL, DAG.getConstant(Cst, ShTy)),
5304            DAG.getNode(ISD::SHL, dl,
5305                        NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
5306         Hi = DAG.getNode(ISD::SRA, dl, NVT, InH, DAG.getConstant(Cst, ShTy));
5307       }
5308       return true;
5309     }
5310   }
5311
5312   // Okay, the shift amount isn't constant.  However, if we can tell that it is
5313   // >= 32 or < 32, we can still simplify it, without knowing the actual value.
5314   APInt Mask = APInt::getHighBitsSet(ShBits, ShBits - Log2_32(NVTBits));
5315   APInt KnownZero, KnownOne;
5316   DAG.ComputeMaskedBits(Amt, Mask, KnownZero, KnownOne);
5317
5318   // If we know that if any of the high bits of the shift amount are one, then
5319   // we can do this as a couple of simple shifts.
5320   if (KnownOne.intersects(Mask)) {
5321     // Mask out the high bit, which we know is set.
5322     Amt = DAG.getNode(ISD::AND, dl, Amt.getValueType(), Amt,
5323                       DAG.getConstant(~Mask, Amt.getValueType()));
5324
5325     // Expand the incoming operand to be shifted, so that we have its parts
5326     SDValue InL, InH;
5327     ExpandOp(Op, InL, InH);
5328     switch(Opc) {
5329     case ISD::SHL:
5330       Lo = DAG.getConstant(0, NVT);              // Low part is zero.
5331       Hi = DAG.getNode(ISD::SHL, dl, NVT, InL, Amt); // High part from Lo part.
5332       return true;
5333     case ISD::SRL:
5334       Hi = DAG.getConstant(0, NVT);              // Hi part is zero.
5335       Lo = DAG.getNode(ISD::SRL, dl, NVT, InH, Amt); // Lo part from Hi part.
5336       return true;
5337     case ISD::SRA:
5338       Hi = DAG.getNode(ISD::SRA, dl, NVT, InH,       // Sign extend high part.
5339                        DAG.getConstant(NVTBits-1, Amt.getValueType()));
5340       Lo = DAG.getNode(ISD::SRA, dl, NVT, InH, Amt); // Lo part from Hi part.
5341       return true;
5342     }
5343   }
5344
5345   // If we know that the high bits of the shift amount are all zero, then we can
5346   // do this as a couple of simple shifts.
5347   if ((KnownZero & Mask) == Mask) {
5348     // Compute 32-amt.
5349     SDValue Amt2 = DAG.getNode(ISD::SUB, dl, Amt.getValueType(),
5350                                  DAG.getConstant(NVTBits, Amt.getValueType()),
5351                                  Amt);
5352
5353     // Expand the incoming operand to be shifted, so that we have its parts
5354     SDValue InL, InH;
5355     ExpandOp(Op, InL, InH);
5356     switch(Opc) {
5357     case ISD::SHL:
5358       Lo = DAG.getNode(ISD::SHL, dl, NVT, InL, Amt);
5359       Hi = DAG.getNode(ISD::OR, dl, NVT,
5360                        DAG.getNode(ISD::SHL, dl, NVT, InH, Amt),
5361                        DAG.getNode(ISD::SRL, dl, NVT, InL, Amt2));
5362       return true;
5363     case ISD::SRL:
5364       Hi = DAG.getNode(ISD::SRL, dl, NVT, InH, Amt);
5365       Lo = DAG.getNode(ISD::OR, dl, NVT,
5366                        DAG.getNode(ISD::SRL, dl, NVT, InL, Amt),
5367                        DAG.getNode(ISD::SHL, dl, NVT, InH, Amt2));
5368       return true;
5369     case ISD::SRA:
5370       Hi = DAG.getNode(ISD::SRA, dl, NVT, InH, Amt);
5371       Lo = DAG.getNode(ISD::OR, dl, NVT,
5372                        DAG.getNode(ISD::SRL, dl, NVT, InL, Amt),
5373                        DAG.getNode(ISD::SHL, dl, NVT, InH, Amt2));
5374       return true;
5375     }
5376   }
5377
5378   return false;
5379 }
5380
5381
5382 // ExpandLibCall - Expand a node into a call to a libcall.  If the result value
5383 // does not fit into a register, return the lo part and set the hi part to the
5384 // by-reg argument.  If it does fit into a single register, return the result
5385 // and leave the Hi part unset.
5386 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
5387                                             bool isSigned, SDValue &Hi) {
5388   assert(!IsLegalizingCall && "Cannot overlap legalization of calls!");
5389   // The input chain to this libcall is the entry node of the function.
5390   // Legalizing the call will automatically add the previous call to the
5391   // dependence.
5392   SDValue InChain = DAG.getEntryNode();
5393
5394   TargetLowering::ArgListTy Args;
5395   TargetLowering::ArgListEntry Entry;
5396   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
5397     MVT ArgVT = Node->getOperand(i).getValueType();
5398     const Type *ArgTy = ArgVT.getTypeForMVT();
5399     Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy;
5400     Entry.isSExt = isSigned;
5401     Entry.isZExt = !isSigned;
5402     Args.push_back(Entry);
5403   }
5404   SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
5405                                          TLI.getPointerTy());
5406
5407   // Splice the libcall in wherever FindInputOutputChains tells us to.
5408   const Type *RetTy = Node->getValueType(0).getTypeForMVT();
5409   std::pair<SDValue, SDValue> CallInfo =
5410     TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
5411                     CallingConv::C, false, Callee, Args, DAG,
5412                     Node->getDebugLoc());
5413
5414   // Legalize the call sequence, starting with the chain.  This will advance
5415   // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
5416   // was added by LowerCallTo (guaranteeing proper serialization of calls).
5417   LegalizeOp(CallInfo.second);
5418   SDValue Result;
5419   switch (getTypeAction(CallInfo.first.getValueType())) {
5420   default: assert(0 && "Unknown thing");
5421   case Legal:
5422     Result = CallInfo.first;
5423     break;
5424   case Expand:
5425     ExpandOp(CallInfo.first, Result, Hi);
5426     break;
5427   }
5428   return Result;
5429 }
5430
5431 /// LegalizeINT_TO_FP - Legalize a [US]INT_TO_FP operation.
5432 ///
5433 SDValue SelectionDAGLegalize::
5434 LegalizeINT_TO_FP(SDValue Result, bool isSigned, MVT DestTy, SDValue Op,
5435                   DebugLoc dl) {
5436   bool isCustom = false;
5437   SDValue Tmp1;
5438   switch (getTypeAction(Op.getValueType())) {
5439   case Legal:
5440     switch (TLI.getOperationAction(isSigned ? ISD::SINT_TO_FP : ISD::UINT_TO_FP,
5441                                    Op.getValueType())) {
5442     default: assert(0 && "Unknown operation action!");
5443     case TargetLowering::Custom:
5444       isCustom = true;
5445       // FALLTHROUGH
5446     case TargetLowering::Legal:
5447       Tmp1 = LegalizeOp(Op);
5448       if (Result.getNode())
5449         Result = DAG.UpdateNodeOperands(Result, Tmp1);
5450       else
5451         Result = DAG.getNode(isSigned ? ISD::SINT_TO_FP : ISD::UINT_TO_FP, dl,
5452                              DestTy, Tmp1);
5453       if (isCustom) {
5454         Tmp1 = TLI.LowerOperation(Result, DAG);
5455         if (Tmp1.getNode()) Result = Tmp1;
5456       }
5457       break;
5458     case TargetLowering::Expand:
5459       Result = ExpandLegalINT_TO_FP(isSigned, LegalizeOp(Op), DestTy, dl);
5460       break;
5461     case TargetLowering::Promote:
5462       Result = PromoteLegalINT_TO_FP(LegalizeOp(Op), DestTy, isSigned, dl);
5463       break;
5464     }
5465     break;
5466   case Expand:
5467     Result = ExpandIntToFP(isSigned, DestTy, Op, dl) ;
5468     break;
5469   case Promote:
5470     Tmp1 = PromoteOp(Op);
5471     if (isSigned) {
5472       Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Tmp1.getValueType(),
5473                          Tmp1, DAG.getValueType(Op.getValueType()));
5474     } else {
5475       Tmp1 = DAG.getZeroExtendInReg(Tmp1, dl, Op.getValueType());
5476     }
5477     if (Result.getNode())
5478       Result = DAG.UpdateNodeOperands(Result, Tmp1);
5479     else
5480       Result = DAG.getNode(isSigned ? ISD::SINT_TO_FP : ISD::UINT_TO_FP, dl,
5481                            DestTy, Tmp1);
5482     Result = LegalizeOp(Result);  // The 'op' is not necessarily legal!
5483     break;
5484   }
5485   return Result;
5486 }
5487
5488 /// ExpandIntToFP - Expand a [US]INT_TO_FP operation.
5489 ///
5490 SDValue SelectionDAGLegalize::
5491 ExpandIntToFP(bool isSigned, MVT DestTy, SDValue Source, DebugLoc dl) {
5492   MVT SourceVT = Source.getValueType();
5493   bool ExpandSource = getTypeAction(SourceVT) == Expand;
5494
5495   // Expand unsupported int-to-fp vector casts by unrolling them.
5496   if (DestTy.isVector()) {
5497     if (!ExpandSource)
5498       return LegalizeOp(UnrollVectorOp(Source));
5499     MVT DestEltTy = DestTy.getVectorElementType();
5500     if (DestTy.getVectorNumElements() == 1) {
5501       SDValue Scalar = ScalarizeVectorOp(Source);
5502       SDValue Result = LegalizeINT_TO_FP(SDValue(), isSigned,
5503                                          DestEltTy, Scalar, dl);
5504       return DAG.getNode(ISD::BUILD_VECTOR, dl, DestTy, Result);
5505     }
5506     SDValue Lo, Hi;
5507     SplitVectorOp(Source, Lo, Hi);
5508     MVT SplitDestTy = MVT::getVectorVT(DestEltTy,
5509                                        DestTy.getVectorNumElements() / 2);
5510     SDValue LoResult = LegalizeINT_TO_FP(SDValue(), isSigned, SplitDestTy,
5511                                          Lo, dl);
5512     SDValue HiResult = LegalizeINT_TO_FP(SDValue(), isSigned, SplitDestTy,
5513                                          Hi, dl);
5514     return LegalizeOp(DAG.getNode(ISD::CONCAT_VECTORS, dl, DestTy, LoResult,
5515                                   HiResult));
5516   }
5517
5518   // Special case for i32 source to take advantage of UINTTOFP_I32_F32, etc.
5519   if (!isSigned && SourceVT != MVT::i32) {
5520     // The integer value loaded will be incorrectly if the 'sign bit' of the
5521     // incoming integer is set.  To handle this, we dynamically test to see if
5522     // it is set, and, if so, add a fudge factor.
5523     SDValue Hi;
5524     if (ExpandSource) {
5525       SDValue Lo;
5526       ExpandOp(Source, Lo, Hi);
5527       Source = DAG.getNode(ISD::BUILD_PAIR, dl, SourceVT, Lo, Hi);
5528     } else {
5529       // The comparison for the sign bit will use the entire operand.
5530       Hi = Source;
5531     }
5532
5533     // Check to see if the target has a custom way to lower this.  If so, use
5534     // it.  (Note we've already expanded the operand in this case.)
5535     switch (TLI.getOperationAction(ISD::UINT_TO_FP, SourceVT)) {
5536     default: assert(0 && "This action not implemented for this operation!");
5537     case TargetLowering::Legal:
5538     case TargetLowering::Expand:
5539       break;   // This case is handled below.
5540     case TargetLowering::Custom: {
5541       SDValue NV = TLI.LowerOperation(DAG.getNode(ISD::UINT_TO_FP, dl, DestTy,
5542                                                   Source), DAG);
5543       if (NV.getNode())
5544         return LegalizeOp(NV);
5545       break;   // The target decided this was legal after all
5546     }
5547     }
5548
5549     // If this is unsigned, and not supported, first perform the conversion to
5550     // signed, then adjust the result if the sign bit is set.
5551     SDValue SignedConv = ExpandIntToFP(true, DestTy, Source, dl);
5552
5553     SDValue SignSet = DAG.getSetCC(dl,
5554                                    TLI.getSetCCResultType(Hi.getValueType()),
5555                                    Hi, DAG.getConstant(0, Hi.getValueType()),
5556                                    ISD::SETLT);
5557     SDValue Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
5558     SDValue CstOffset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(),
5559                                       SignSet, Four, Zero);
5560     uint64_t FF = 0x5f800000ULL;
5561     if (TLI.isLittleEndian()) FF <<= 32;
5562     Constant *FudgeFactor = ConstantInt::get(Type::Int64Ty, FF);
5563
5564     SDValue CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
5565     unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
5566     CPIdx = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), CPIdx, CstOffset);
5567     Alignment = std::min(Alignment, 4u);
5568     SDValue FudgeInReg;
5569     if (DestTy == MVT::f32)
5570       FudgeInReg = DAG.getLoad(MVT::f32, dl, DAG.getEntryNode(), CPIdx,
5571                                PseudoSourceValue::getConstantPool(), 0,
5572                                false, Alignment);
5573     else if (DestTy.bitsGT(MVT::f32))
5574       // FIXME: Avoid the extend by construction the right constantpool?
5575       FudgeInReg = DAG.getExtLoad(ISD::EXTLOAD, dl, DestTy, DAG.getEntryNode(),
5576                                   CPIdx,
5577                                   PseudoSourceValue::getConstantPool(), 0,
5578                                   MVT::f32, false, Alignment);
5579     else
5580       assert(0 && "Unexpected conversion");
5581
5582     MVT SCVT = SignedConv.getValueType();
5583     if (SCVT != DestTy) {
5584       // Destination type needs to be expanded as well. The FADD now we are
5585       // constructing will be expanded into a libcall.
5586       if (SCVT.getSizeInBits() != DestTy.getSizeInBits()) {
5587         assert(SCVT.getSizeInBits() * 2 == DestTy.getSizeInBits());
5588         SignedConv = DAG.getNode(ISD::BUILD_PAIR, dl, DestTy,
5589                                  SignedConv, SignedConv.getValue(1));
5590       }
5591       SignedConv = DAG.getNode(ISD::BIT_CONVERT, dl, DestTy, SignedConv);
5592     }
5593     return DAG.getNode(ISD::FADD, dl, DestTy, SignedConv, FudgeInReg);
5594   }
5595
5596   // Check to see if the target has a custom way to lower this.  If so, use it.
5597   switch (TLI.getOperationAction(ISD::SINT_TO_FP, SourceVT)) {
5598   default: assert(0 && "This action not implemented for this operation!");
5599   case TargetLowering::Legal:
5600   case TargetLowering::Expand:
5601     break;   // This case is handled below.
5602   case TargetLowering::Custom: {
5603     SDValue NV = TLI.LowerOperation(DAG.getNode(ISD::SINT_TO_FP, dl, DestTy,
5604                                                 Source), DAG);
5605     if (NV.getNode())
5606       return LegalizeOp(NV);
5607     break;   // The target decided this was legal after all
5608   }
5609   }
5610
5611   // Expand the source, then glue it back together for the call.  We must expand
5612   // the source in case it is shared (this pass of legalize must traverse it).
5613   if (ExpandSource) {
5614     SDValue SrcLo, SrcHi;
5615     ExpandOp(Source, SrcLo, SrcHi);
5616     Source = DAG.getNode(ISD::BUILD_PAIR, dl, SourceVT, SrcLo, SrcHi);
5617   }
5618
5619   RTLIB::Libcall LC = isSigned ?
5620     RTLIB::getSINTTOFP(SourceVT, DestTy) :
5621     RTLIB::getUINTTOFP(SourceVT, DestTy);
5622   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unknown int value type");
5623
5624   Source = DAG.getNode(ISD::SINT_TO_FP, dl, DestTy, Source);
5625   SDValue HiPart;
5626   SDValue Result = ExpandLibCall(LC, Source.getNode(), isSigned, HiPart);
5627   if (Result.getValueType() != DestTy && HiPart.getNode())
5628     Result = DAG.getNode(ISD::BUILD_PAIR, dl, DestTy, Result, HiPart);
5629   return Result;
5630 }
5631
5632 /// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
5633 /// INT_TO_FP operation of the specified operand when the target requests that
5634 /// we expand it.  At this point, we know that the result and operand types are
5635 /// legal for the target.
5636 SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
5637                                                    SDValue Op0,
5638                                                    MVT DestVT,
5639                                                    DebugLoc dl) {
5640   if (Op0.getValueType() == MVT::i32) {
5641     // simple 32-bit [signed|unsigned] integer to float/double expansion
5642
5643     // Get the stack frame index of a 8 byte buffer.
5644     SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
5645
5646     // word offset constant for Hi/Lo address computation
5647     SDValue WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
5648     // set up Hi and Lo (into buffer) address based on endian
5649     SDValue Hi = StackSlot;
5650     SDValue Lo = DAG.getNode(ISD::ADD, dl,
5651                              TLI.getPointerTy(), StackSlot, WordOff);
5652     if (TLI.isLittleEndian())
5653       std::swap(Hi, Lo);
5654
5655     // if signed map to unsigned space
5656     SDValue Op0Mapped;
5657     if (isSigned) {
5658       // constant used to invert sign bit (signed to unsigned mapping)
5659       SDValue SignBit = DAG.getConstant(0x80000000u, MVT::i32);
5660       Op0Mapped = DAG.getNode(ISD::XOR, dl, MVT::i32, Op0, SignBit);
5661     } else {
5662       Op0Mapped = Op0;
5663     }
5664     // store the lo of the constructed double - based on integer input
5665     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl,
5666                                   Op0Mapped, Lo, NULL, 0);
5667     // initial hi portion of constructed double
5668     SDValue InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
5669     // store the hi of the constructed double - biased exponent
5670     SDValue Store2=DAG.getStore(Store1, dl, InitialHi, Hi, NULL, 0);
5671     // load the constructed double
5672     SDValue Load = DAG.getLoad(MVT::f64, dl, Store2, StackSlot, NULL, 0);
5673     // FP constant to bias correct the final result
5674     SDValue Bias = DAG.getConstantFP(isSigned ?
5675                                      BitsToDouble(0x4330000080000000ULL) :
5676                                      BitsToDouble(0x4330000000000000ULL),
5677                                      MVT::f64);
5678     // subtract the bias
5679     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
5680     // final result
5681     SDValue Result;
5682     // handle final rounding
5683     if (DestVT == MVT::f64) {
5684       // do nothing
5685       Result = Sub;
5686     } else if (DestVT.bitsLT(MVT::f64)) {
5687       Result = DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5688                            DAG.getIntPtrConstant(0));
5689     } else if (DestVT.bitsGT(MVT::f64)) {
5690       Result = DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5691     }
5692     return Result;
5693   }
5694   assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
5695   SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
5696
5697   SDValue SignSet = DAG.getSetCC(dl, TLI.getSetCCResultType(Op0.getValueType()),
5698                                  Op0, DAG.getConstant(0, Op0.getValueType()),
5699                                  ISD::SETLT);
5700   SDValue Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
5701   SDValue CstOffset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(),
5702                                     SignSet, Four, Zero);
5703
5704   // If the sign bit of the integer is set, the large number will be treated
5705   // as a negative number.  To counteract this, the dynamic code adds an
5706   // offset depending on the data type.
5707   uint64_t FF;
5708   switch (Op0.getValueType().getSimpleVT()) {
5709   default: assert(0 && "Unsupported integer type!");
5710   case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
5711   case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
5712   case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
5713   case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
5714   }
5715   if (TLI.isLittleEndian()) FF <<= 32;
5716   Constant *FudgeFactor = ConstantInt::get(Type::Int64Ty, FF);
5717
5718   SDValue CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
5719   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
5720   CPIdx = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), CPIdx, CstOffset);
5721   Alignment = std::min(Alignment, 4u);
5722   SDValue FudgeInReg;
5723   if (DestVT == MVT::f32)
5724     FudgeInReg = DAG.getLoad(MVT::f32, dl, DAG.getEntryNode(), CPIdx,
5725                              PseudoSourceValue::getConstantPool(), 0,
5726                              false, Alignment);
5727   else {
5728     FudgeInReg =
5729       LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT,
5730                                 DAG.getEntryNode(), CPIdx,
5731                                 PseudoSourceValue::getConstantPool(), 0,
5732                                 MVT::f32, false, Alignment));
5733   }
5734
5735   return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
5736 }
5737
5738 /// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
5739 /// *INT_TO_FP operation of the specified operand when the target requests that
5740 /// we promote it.  At this point, we know that the result and operand types are
5741 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
5742 /// operation that takes a larger input.
5743 SDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp,
5744                                                     MVT DestVT,
5745                                                     bool isSigned,
5746                                                     DebugLoc dl) {
5747   // First step, figure out the appropriate *INT_TO_FP operation to use.
5748   MVT NewInTy = LegalOp.getValueType();
5749
5750   unsigned OpToUse = 0;
5751
5752   // Scan for the appropriate larger type to use.
5753   while (1) {
5754     NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT()+1);
5755     assert(NewInTy.isInteger() && "Ran out of possibilities!");
5756
5757     // If the target supports SINT_TO_FP of this type, use it.
5758     switch (TLI.getOperationAction(ISD::SINT_TO_FP, NewInTy)) {
5759       default: break;
5760       case TargetLowering::Legal:
5761         if (!TLI.isTypeLegal(NewInTy))
5762           break;  // Can't use this datatype.
5763         // FALL THROUGH.
5764       case TargetLowering::Custom:
5765         OpToUse = ISD::SINT_TO_FP;
5766         break;
5767     }
5768     if (OpToUse) break;
5769     if (isSigned) continue;
5770
5771     // If the target supports UINT_TO_FP of this type, use it.
5772     switch (TLI.getOperationAction(ISD::UINT_TO_FP, NewInTy)) {
5773       default: break;
5774       case TargetLowering::Legal:
5775         if (!TLI.isTypeLegal(NewInTy))
5776           break;  // Can't use this datatype.
5777         // FALL THROUGH.
5778       case TargetLowering::Custom:
5779         OpToUse = ISD::UINT_TO_FP;
5780         break;
5781     }
5782     if (OpToUse) break;
5783
5784     // Otherwise, try a larger type.
5785   }
5786
5787   // Okay, we found the operation and type to use.  Zero extend our input to the
5788   // desired type then run the operation on it.
5789   return DAG.getNode(OpToUse, dl, DestVT,
5790                      DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5791                                  dl, NewInTy, LegalOp));
5792 }
5793
5794 /// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
5795 /// FP_TO_*INT operation of the specified operand when the target requests that
5796 /// we promote it.  At this point, we know that the result and operand types are
5797 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
5798 /// operation that returns a larger result.
5799 SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp,
5800                                                     MVT DestVT,
5801                                                     bool isSigned,
5802                                                     DebugLoc dl) {
5803   // First step, figure out the appropriate FP_TO*INT operation to use.
5804   MVT NewOutTy = DestVT;
5805
5806   unsigned OpToUse = 0;
5807
5808   // Scan for the appropriate larger type to use.
5809   while (1) {
5810     NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT()+1);
5811     assert(NewOutTy.isInteger() && "Ran out of possibilities!");
5812
5813     // If the target supports FP_TO_SINT returning this type, use it.
5814     switch (TLI.getOperationAction(ISD::FP_TO_SINT, NewOutTy)) {
5815     default: break;
5816     case TargetLowering::Legal:
5817       if (!TLI.isTypeLegal(NewOutTy))
5818         break;  // Can't use this datatype.
5819       // FALL THROUGH.
5820     case TargetLowering::Custom:
5821       OpToUse = ISD::FP_TO_SINT;
5822       break;
5823     }
5824     if (OpToUse) break;
5825
5826     // If the target supports FP_TO_UINT of this type, use it.
5827     switch (TLI.getOperationAction(ISD::FP_TO_UINT, NewOutTy)) {
5828     default: break;
5829     case TargetLowering::Legal:
5830       if (!TLI.isTypeLegal(NewOutTy))
5831         break;  // Can't use this datatype.
5832       // FALL THROUGH.
5833     case TargetLowering::Custom:
5834       OpToUse = ISD::FP_TO_UINT;
5835       break;
5836     }
5837     if (OpToUse) break;
5838
5839     // Otherwise, try a larger type.
5840   }
5841
5842
5843   // Okay, we found the operation and type to use.
5844   SDValue Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
5845
5846   // If the operation produces an invalid type, it must be custom lowered.  Use
5847   // the target lowering hooks to expand it.  Just keep the low part of the
5848   // expanded operation, we know that we're truncating anyway.
5849   if (getTypeAction(NewOutTy) == Expand) {
5850     SmallVector<SDValue, 2> Results;
5851     TLI.ReplaceNodeResults(Operation.getNode(), Results, DAG);
5852     assert(Results.size() == 1 && "Incorrect FP_TO_XINT lowering!");
5853     Operation = Results[0];
5854   }
5855
5856   // Truncate the result of the extended FP_TO_*INT operation to the desired
5857   // size.
5858   return DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
5859 }
5860
5861 /// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
5862 ///
5863 SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op, DebugLoc dl) {
5864   MVT VT = Op.getValueType();
5865   MVT SHVT = TLI.getShiftAmountTy();
5866   SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
5867   switch (VT.getSimpleVT()) {
5868   default: assert(0 && "Unhandled Expand type in BSWAP!"); abort();
5869   case MVT::i16:
5870     Tmp2 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
5871     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
5872     return DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5873   case MVT::i32:
5874     Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
5875     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
5876     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
5877     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
5878     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
5879     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, VT));
5880     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
5881     Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
5882     return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
5883   case MVT::i64:
5884     Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, SHVT));
5885     Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, SHVT));
5886     Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
5887     Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
5888     Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
5889     Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
5890     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, SHVT));
5891     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, SHVT));
5892     Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
5893     Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
5894     Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
5895     Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
5896     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
5897     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
5898     Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
5899     Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
5900     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
5901     Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
5902     Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
5903     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
5904     return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
5905   }
5906 }
5907
5908 /// ExpandBitCount - Expand the specified bitcount instruction into operations.
5909 ///
5910 SDValue SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDValue Op,
5911                                              DebugLoc dl) {
5912   switch (Opc) {
5913   default: assert(0 && "Cannot expand this yet!");
5914   case ISD::CTPOP: {
5915     static const uint64_t mask[6] = {
5916       0x5555555555555555ULL, 0x3333333333333333ULL,
5917       0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
5918       0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
5919     };
5920     MVT VT = Op.getValueType();
5921     MVT ShVT = TLI.getShiftAmountTy();
5922     unsigned len = VT.getSizeInBits();
5923     for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
5924       //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
5925       unsigned EltSize = VT.isVector() ?
5926         VT.getVectorElementType().getSizeInBits() : len;
5927       SDValue Tmp2 = DAG.getConstant(APInt(EltSize, mask[i]), VT);
5928       SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
5929       Op = DAG.getNode(ISD::ADD, dl, VT,
5930                        DAG.getNode(ISD::AND, dl, VT, Op, Tmp2),
5931                        DAG.getNode(ISD::AND, dl, VT,
5932                                    DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3),
5933                                    Tmp2));
5934     }
5935     return Op;
5936   }
5937   case ISD::CTLZ: {
5938     // for now, we do this:
5939     // x = x | (x >> 1);
5940     // x = x | (x >> 2);
5941     // ...
5942     // x = x | (x >>16);
5943     // x = x | (x >>32); // for 64-bit input
5944     // return popcount(~x);
5945     //
5946     // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
5947     MVT VT = Op.getValueType();
5948     MVT ShVT = TLI.getShiftAmountTy();
5949     unsigned len = VT.getSizeInBits();
5950     for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
5951       SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
5952       Op = DAG.getNode(ISD::OR, dl, VT, Op,
5953                        DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3));
5954     }
5955     Op = DAG.getNOT(dl, Op, VT);
5956     return DAG.getNode(ISD::CTPOP, dl, VT, Op);
5957   }
5958   case ISD::CTTZ: {
5959     // for now, we use: { return popcount(~x & (x - 1)); }
5960     // unless the target has ctlz but not ctpop, in which case we use:
5961     // { return 32 - nlz(~x & (x-1)); }
5962     // see also http://www.hackersdelight.org/HDcode/ntz.cc
5963     MVT VT = Op.getValueType();
5964     SDValue Tmp3 = DAG.getNode(ISD::AND, dl, VT,
5965                                DAG.getNOT(dl, Op, VT),
5966                                DAG.getNode(ISD::SUB, dl, VT, Op,
5967                                            DAG.getConstant(1, VT)));
5968     // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
5969     if (!TLI.isOperationLegalOrCustom(ISD::CTPOP, VT) &&
5970         TLI.isOperationLegalOrCustom(ISD::CTLZ, VT))
5971       return DAG.getNode(ISD::SUB, dl, VT,
5972                          DAG.getConstant(VT.getSizeInBits(), VT),
5973                          DAG.getNode(ISD::CTLZ, dl, VT, Tmp3));
5974     return DAG.getNode(ISD::CTPOP, dl, VT, Tmp3);
5975   }
5976   }
5977 }
5978
5979 /// ExpandOp - Expand the specified SDValue into its two component pieces
5980 /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
5981 /// LegalizedNodes map is filled in for any results that are not expanded, the
5982 /// ExpandedNodes map is filled in for any results that are expanded, and the
5983 /// Lo/Hi values are returned.
5984 void SelectionDAGLegalize::ExpandOp(SDValue Op, SDValue &Lo, SDValue &Hi){
5985   assert(0 && "This should be dead!");
5986   MVT VT = Op.getValueType();
5987   MVT NVT = TLI.getTypeToTransformTo(VT);
5988   SDNode *Node = Op.getNode();
5989   DebugLoc dl = Node->getDebugLoc();
5990   assert(getTypeAction(VT) == Expand && "Not an expanded type!");
5991   assert(((NVT.isInteger() && NVT.bitsLT(VT)) || VT.isFloatingPoint() ||
5992          VT.isVector()) && "Cannot expand to FP value or to larger int value!");
5993
5994   // See if we already expanded it.
5995   DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator I
5996     = ExpandedNodes.find(Op);
5997   if (I != ExpandedNodes.end()) {
5998     Lo = I->second.first;
5999     Hi = I->second.second;
6000     return;
6001   }
6002
6003   switch (Node->getOpcode()) {
6004   case ISD::CopyFromReg:
6005     assert(0 && "CopyFromReg must be legal!");
6006   case ISD::FP_ROUND_INREG:
6007     if (VT == MVT::ppcf128 &&
6008         TLI.getOperationAction(ISD::FP_ROUND_INREG, VT) ==
6009             TargetLowering::Custom) {
6010       SDValue SrcLo, SrcHi, Src;
6011       ExpandOp(Op.getOperand(0), SrcLo, SrcHi);
6012       Src = DAG.getNode(ISD::BUILD_PAIR, dl, VT, SrcLo, SrcHi);
6013       SDValue Result =
6014         TLI.LowerOperation(DAG.getNode(ISD::FP_ROUND_INREG, dl, VT, Src,
6015                                        Op.getOperand(1)), DAG);
6016       assert(Result.getNode()->getOpcode() == ISD::BUILD_PAIR);
6017       Lo = Result.getNode()->getOperand(0);
6018       Hi = Result.getNode()->getOperand(1);
6019       break;
6020     }
6021     // fall through
6022   default:
6023 #ifndef NDEBUG
6024     cerr << "NODE: "; Node->dump(&DAG); cerr << "\n";
6025 #endif
6026     assert(0 && "Do not know how to expand this operator!");
6027     abort();
6028   case ISD::EXTRACT_ELEMENT:
6029     ExpandOp(Node->getOperand(0), Lo, Hi);
6030     if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue())
6031       return ExpandOp(Hi, Lo, Hi);
6032     return ExpandOp(Lo, Lo, Hi);
6033   case ISD::EXTRACT_VECTOR_ELT:
6034     // ExpandEXTRACT_VECTOR_ELT tolerates invalid result types.
6035     Lo  = ExpandEXTRACT_VECTOR_ELT(Op);
6036     return ExpandOp(Lo, Lo, Hi);
6037   case ISD::UNDEF:
6038     Lo = DAG.getUNDEF(NVT);
6039     Hi = DAG.getUNDEF(NVT);
6040     break;
6041   case ISD::Constant: {
6042     unsigned NVTBits = NVT.getSizeInBits();
6043     const APInt &Cst = cast<ConstantSDNode>(Node)->getAPIntValue();
6044     Lo = DAG.getConstant(APInt(Cst).trunc(NVTBits), NVT);
6045     Hi = DAG.getConstant(Cst.lshr(NVTBits).trunc(NVTBits), NVT);
6046     break;
6047   }
6048   case ISD::ConstantFP: {
6049     ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
6050     if (CFP->getValueType(0) == MVT::ppcf128) {
6051       APInt api = CFP->getValueAPF().bitcastToAPInt();
6052       Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &api.getRawData()[1])),
6053                              MVT::f64);
6054       Hi = DAG.getConstantFP(APFloat(APInt(64, 1, &api.getRawData()[0])),
6055                              MVT::f64);
6056       break;
6057     }
6058     Lo = ExpandConstantFP(CFP, false, DAG, TLI);
6059     if (getTypeAction(Lo.getValueType()) == Expand)
6060       ExpandOp(Lo, Lo, Hi);
6061     break;
6062   }
6063   case ISD::BUILD_PAIR:
6064     // Return the operands.
6065     Lo = Node->getOperand(0);
6066     Hi = Node->getOperand(1);
6067     break;
6068
6069   case ISD::MERGE_VALUES:
6070     if (Node->getNumValues() == 1) {
6071       ExpandOp(Op.getOperand(0), Lo, Hi);
6072       break;
6073     }
6074     // FIXME: For now only expand i64,chain = MERGE_VALUES (x, y)
6075     assert(Op.getResNo() == 0 && Node->getNumValues() == 2 &&
6076            Op.getValue(1).getValueType() == MVT::Other &&
6077            "unhandled MERGE_VALUES");
6078     ExpandOp(Op.getOperand(0), Lo, Hi);
6079     // Remember that we legalized the chain.
6080     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Op.getOperand(1)));
6081     break;
6082
6083   case ISD::SIGN_EXTEND_INREG:
6084     ExpandOp(Node->getOperand(0), Lo, Hi);
6085     // sext_inreg the low part if needed.
6086     Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Lo, Node->getOperand(1));
6087
6088     // The high part gets the sign extension from the lo-part.  This handles
6089     // things like sextinreg V:i64 from i8.
6090     Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
6091                      DAG.getConstant(NVT.getSizeInBits()-1,
6092                                      TLI.getShiftAmountTy()));
6093     break;
6094
6095   case ISD::BSWAP: {
6096     ExpandOp(Node->getOperand(0), Lo, Hi);
6097     SDValue TempLo = DAG.getNode(ISD::BSWAP, dl, NVT, Hi);
6098     Hi = DAG.getNode(ISD::BSWAP, dl, NVT, Lo);
6099     Lo = TempLo;
6100     break;
6101   }
6102
6103   case ISD::CTPOP:
6104     ExpandOp(Node->getOperand(0), Lo, Hi);
6105     Lo = DAG.getNode(ISD::ADD, dl, NVT,      // ctpop(HL) -> ctpop(H)+ctpop(L)
6106                      DAG.getNode(ISD::CTPOP, dl, NVT, Lo),
6107                      DAG.getNode(ISD::CTPOP, dl, NVT, Hi));
6108     Hi = DAG.getConstant(0, NVT);
6109     break;
6110
6111   case ISD::CTLZ: {
6112     // ctlz (HL) -> ctlz(H) != 32 ? ctlz(H) : (ctlz(L)+32)
6113     ExpandOp(Node->getOperand(0), Lo, Hi);
6114     SDValue BitsC = DAG.getConstant(NVT.getSizeInBits(), NVT);
6115     SDValue HLZ = DAG.getNode(ISD::CTLZ, dl, NVT, Hi);
6116     SDValue TopNotZero = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT), HLZ,
6117                                       BitsC, ISD::SETNE);
6118     SDValue LowPart = DAG.getNode(ISD::CTLZ, dl, NVT, Lo);
6119     LowPart = DAG.getNode(ISD::ADD, dl, NVT, LowPart, BitsC);
6120
6121     Lo = DAG.getNode(ISD::SELECT, dl, NVT, TopNotZero, HLZ, LowPart);
6122     Hi = DAG.getConstant(0, NVT);
6123     break;
6124   }
6125
6126   case ISD::CTTZ: {
6127     // cttz (HL) -> cttz(L) != 32 ? cttz(L) : (cttz(H)+32)
6128     ExpandOp(Node->getOperand(0), Lo, Hi);
6129     SDValue BitsC = DAG.getConstant(NVT.getSizeInBits(), NVT);
6130     SDValue LTZ = DAG.getNode(ISD::CTTZ, dl, NVT, Lo);
6131     SDValue BotNotZero = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT), LTZ,
6132                                       BitsC, ISD::SETNE);
6133     SDValue HiPart = DAG.getNode(ISD::CTTZ, dl, NVT, Hi);
6134     HiPart = DAG.getNode(ISD::ADD, dl, NVT, HiPart, BitsC);
6135
6136     Lo = DAG.getNode(ISD::SELECT, dl, NVT, BotNotZero, LTZ, HiPart);
6137     Hi = DAG.getConstant(0, NVT);
6138     break;
6139   }
6140
6141   case ISD::VAARG: {
6142     SDValue Ch = Node->getOperand(0);   // Legalize the chain.
6143     SDValue Ptr = Node->getOperand(1);  // Legalize the pointer.
6144     Lo = DAG.getVAArg(NVT, dl, Ch, Ptr, Node->getOperand(2));
6145     Hi = DAG.getVAArg(NVT, dl, Lo.getValue(1), Ptr, Node->getOperand(2));
6146
6147     // Remember that we legalized the chain.
6148     Hi = LegalizeOp(Hi);
6149     AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
6150     if (TLI.isBigEndian())
6151       std::swap(Lo, Hi);
6152     break;
6153   }
6154
6155   case ISD::LOAD: {
6156     LoadSDNode *LD = cast<LoadSDNode>(Node);
6157     SDValue Ch  = LD->getChain();    // Legalize the chain.
6158     SDValue Ptr = LD->getBasePtr();  // Legalize the pointer.
6159     ISD::LoadExtType ExtType = LD->getExtensionType();
6160     const Value *SV = LD->getSrcValue();
6161     int SVOffset = LD->getSrcValueOffset();
6162     unsigned Alignment = LD->getAlignment();
6163     bool isVolatile = LD->isVolatile();
6164
6165     if (ExtType == ISD::NON_EXTLOAD) {
6166       Lo = DAG.getLoad(NVT, dl, Ch, Ptr, SV, SVOffset,
6167                        isVolatile, Alignment);
6168       if (VT == MVT::f32 || VT == MVT::f64) {
6169         // f32->i32 or f64->i64 one to one expansion.
6170         // Remember that we legalized the chain.
6171         AddLegalizedOperand(SDValue(Node, 1), LegalizeOp(Lo.getValue(1)));
6172         // Recursively expand the new load.
6173         if (getTypeAction(NVT) == Expand)
6174           ExpandOp(Lo, Lo, Hi);
6175         break;
6176       }
6177
6178       // Increment the pointer to the other half.
6179       unsigned IncrementSize = Lo.getValueType().getSizeInBits()/8;
6180       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
6181                         DAG.getIntPtrConstant(IncrementSize));
6182       SVOffset += IncrementSize;
6183       Alignment = MinAlign(Alignment, IncrementSize);
6184       Hi = DAG.getLoad(NVT, dl, Ch, Ptr, SV, SVOffset,
6185                        isVolatile, Alignment);
6186
6187       // Build a factor node to remember that this load is independent of the
6188       // other one.
6189       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
6190                                Hi.getValue(1));
6191
6192       // Remember that we legalized the chain.
6193       AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
6194       if (TLI.isBigEndian())
6195         std::swap(Lo, Hi);
6196     } else {
6197       MVT EVT = LD->getMemoryVT();
6198
6199       if ((VT == MVT::f64 && EVT == MVT::f32) ||
6200           (VT == MVT::ppcf128 && (EVT==MVT::f64 || EVT==MVT::f32))) {
6201         // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
6202         SDValue Load = DAG.getLoad(EVT, dl, Ch, Ptr, SV,
6203                                    SVOffset, isVolatile, Alignment);
6204         // Remember that we legalized the chain.
6205         AddLegalizedOperand(SDValue(Node, 1), LegalizeOp(Load.getValue(1)));
6206         ExpandOp(DAG.getNode(ISD::FP_EXTEND, dl, VT, Load), Lo, Hi);
6207         break;
6208       }
6209
6210       if (EVT == NVT)
6211         Lo = DAG.getLoad(NVT, dl, Ch, Ptr, SV,
6212                          SVOffset, isVolatile, Alignment);
6213       else
6214         Lo = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr, SV,
6215                             SVOffset, EVT, isVolatile,
6216                             Alignment);
6217
6218       // Remember that we legalized the chain.
6219       AddLegalizedOperand(SDValue(Node, 1), LegalizeOp(Lo.getValue(1)));
6220
6221       if (ExtType == ISD::SEXTLOAD) {
6222         // The high part is obtained by SRA'ing all but one of the bits of the
6223         // lo part.
6224         unsigned LoSize = Lo.getValueType().getSizeInBits();
6225         Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
6226                          DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
6227       } else if (ExtType == ISD::ZEXTLOAD) {
6228         // The high part is just a zero.
6229         Hi = DAG.getConstant(0, NVT);
6230       } else /* if (ExtType == ISD::EXTLOAD) */ {
6231         // The high part is undefined.
6232         Hi = DAG.getUNDEF(NVT);
6233       }
6234     }
6235     break;
6236   }
6237   case ISD::AND:
6238   case ISD::OR:
6239   case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
6240     SDValue LL, LH, RL, RH;
6241     ExpandOp(Node->getOperand(0), LL, LH);
6242     ExpandOp(Node->getOperand(1), RL, RH);
6243     Lo = DAG.getNode(Node->getOpcode(), dl, NVT, LL, RL);
6244     Hi = DAG.getNode(Node->getOpcode(), dl, NVT, LH, RH);
6245     break;
6246   }
6247   case ISD::SELECT: {
6248     SDValue LL, LH, RL, RH;
6249     ExpandOp(Node->getOperand(1), LL, LH);
6250     ExpandOp(Node->getOperand(2), RL, RH);
6251     if (getTypeAction(NVT) == Expand)
6252       NVT = TLI.getTypeToExpandTo(NVT);
6253     Lo = DAG.getNode(ISD::SELECT, dl, NVT, Node->getOperand(0), LL, RL);
6254     if (VT != MVT::f32)
6255       Hi = DAG.getNode(ISD::SELECT, dl, NVT, Node->getOperand(0), LH, RH);
6256     break;
6257   }
6258   case ISD::SELECT_CC: {
6259     SDValue TL, TH, FL, FH;
6260     ExpandOp(Node->getOperand(2), TL, TH);
6261     ExpandOp(Node->getOperand(3), FL, FH);
6262     if (getTypeAction(NVT) == Expand)
6263       NVT = TLI.getTypeToExpandTo(NVT);
6264     Lo = DAG.getNode(ISD::SELECT_CC, dl, NVT, Node->getOperand(0),
6265                      Node->getOperand(1), TL, FL, Node->getOperand(4));
6266     if (VT != MVT::f32)
6267       Hi = DAG.getNode(ISD::SELECT_CC, dl, NVT, Node->getOperand(0),
6268                        Node->getOperand(1), TH, FH, Node->getOperand(4));
6269     break;
6270   }
6271   case ISD::ANY_EXTEND:
6272     // The low part is any extension of the input (which degenerates to a copy).
6273     Lo = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(0));
6274     // The high part is undefined.
6275     Hi = DAG.getUNDEF(NVT);
6276     break;
6277   case ISD::SIGN_EXTEND: {
6278     // The low part is just a sign extension of the input (which degenerates to
6279     // a copy).
6280     Lo = DAG.getNode(ISD::SIGN_EXTEND, dl, NVT, Node->getOperand(0));
6281
6282     // The high part is obtained by SRA'ing all but one of the bits of the lo
6283     // part.
6284     unsigned LoSize = Lo.getValueType().getSizeInBits();
6285     Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
6286                      DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
6287     break;
6288   }
6289   case ISD::ZERO_EXTEND:
6290     // The low part is just a zero extension of the input (which degenerates to
6291     // a copy).
6292     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
6293
6294     // The high part is just a zero.
6295     Hi = DAG.getConstant(0, NVT);
6296     break;
6297
6298   case ISD::TRUNCATE: {
6299     // The input value must be larger than this value.  Expand *it*.
6300     SDValue NewLo;
6301     ExpandOp(Node->getOperand(0), NewLo, Hi);
6302
6303     // The low part is now either the right size, or it is closer.  If not the
6304     // right size, make an illegal truncate so we recursively expand it.
6305     if (NewLo.getValueType() != Node->getValueType(0))
6306       NewLo = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), NewLo);
6307     ExpandOp(NewLo, Lo, Hi);
6308     break;
6309   }
6310
6311   case ISD::BIT_CONVERT: {
6312     SDValue Tmp;
6313     if (TLI.getOperationAction(ISD::BIT_CONVERT, VT) == TargetLowering::Custom){
6314       // If the target wants to, allow it to lower this itself.
6315       switch (getTypeAction(Node->getOperand(0).getValueType())) {
6316       case Expand: assert(0 && "cannot expand FP!");
6317       case Legal:   Tmp = LegalizeOp(Node->getOperand(0)); break;
6318       case Promote: Tmp = PromoteOp (Node->getOperand(0)); break;
6319       }
6320       Tmp = TLI.LowerOperation(DAG.getNode(ISD::BIT_CONVERT, dl, VT, Tmp), DAG);
6321     }
6322
6323     // f32 / f64 must be expanded to i32 / i64.
6324     if (VT == MVT::f32 || VT == MVT::f64) {
6325       Lo = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Node->getOperand(0));
6326       if (getTypeAction(NVT) == Expand)
6327         ExpandOp(Lo, Lo, Hi);
6328       break;
6329     }
6330
6331     // If source operand will be expanded to the same type as VT, i.e.
6332     // i64 <- f64, i32 <- f32, expand the source operand instead.
6333     MVT VT0 = Node->getOperand(0).getValueType();
6334     if (getTypeAction(VT0) == Expand && TLI.getTypeToTransformTo(VT0) == VT) {
6335       ExpandOp(Node->getOperand(0), Lo, Hi);
6336       break;
6337     }
6338
6339     // Turn this into a load/store pair by default.
6340     if (Tmp.getNode() == 0)
6341       Tmp = EmitStackConvert(Node->getOperand(0), VT, VT, dl);
6342
6343     ExpandOp(Tmp, Lo, Hi);
6344     break;
6345   }
6346
6347   case ISD::READCYCLECOUNTER: {
6348     assert(TLI.getOperationAction(ISD::READCYCLECOUNTER, VT) ==
6349                  TargetLowering::Custom &&
6350            "Must custom expand ReadCycleCounter");
6351     SDValue Tmp = TLI.LowerOperation(Op, DAG);
6352     assert(Tmp.getNode() && "Node must be custom expanded!");
6353     ExpandOp(Tmp.getValue(0), Lo, Hi);
6354     AddLegalizedOperand(SDValue(Node, 1), // Remember we legalized the chain.
6355                         LegalizeOp(Tmp.getValue(1)));
6356     break;
6357   }
6358
6359   case ISD::ATOMIC_CMP_SWAP: {
6360     // This operation does not need a loop.
6361     SDValue Tmp = TLI.LowerOperation(Op, DAG);
6362     assert(Tmp.getNode() && "Node must be custom expanded!");
6363     ExpandOp(Tmp.getValue(0), Lo, Hi);
6364     AddLegalizedOperand(SDValue(Node, 1), // Remember we legalized the chain.
6365                         LegalizeOp(Tmp.getValue(1)));
6366     break;
6367   }
6368
6369   case ISD::ATOMIC_LOAD_ADD:
6370   case ISD::ATOMIC_LOAD_SUB:
6371   case ISD::ATOMIC_LOAD_AND:
6372   case ISD::ATOMIC_LOAD_OR:
6373   case ISD::ATOMIC_LOAD_XOR:
6374   case ISD::ATOMIC_LOAD_NAND:
6375   case ISD::ATOMIC_SWAP: {
6376     // These operations require a loop to be generated.  We can't do that yet,
6377     // so substitute a target-dependent pseudo and expand that later.
6378     SDValue In2Lo, In2Hi, In2;
6379     ExpandOp(Op.getOperand(2), In2Lo, In2Hi);
6380     In2 = DAG.getNode(ISD::BUILD_PAIR, dl, VT, In2Lo, In2Hi);
6381     AtomicSDNode* Anode = cast<AtomicSDNode>(Node);
6382     SDValue Replace =
6383       DAG.getAtomic(Op.getOpcode(), dl, Anode->getMemoryVT(),
6384                     Op.getOperand(0), Op.getOperand(1), In2,
6385                     Anode->getSrcValue(), Anode->getAlignment());
6386     SDValue Result = TLI.LowerOperation(Replace, DAG);
6387     ExpandOp(Result.getValue(0), Lo, Hi);
6388     // Remember that we legalized the chain.
6389     AddLegalizedOperand(SDValue(Node, 1), LegalizeOp(Result.getValue(1)));
6390     break;
6391   }
6392
6393     // These operators cannot be expanded directly, emit them as calls to
6394     // library functions.
6395   case ISD::FP_TO_SINT: {
6396     if (TLI.getOperationAction(ISD::FP_TO_SINT, VT) == TargetLowering::Custom) {
6397       SDValue Op;
6398       switch (getTypeAction(Node->getOperand(0).getValueType())) {
6399       case Expand: assert(0 && "cannot expand FP!");
6400       case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
6401       case Promote: Op = PromoteOp (Node->getOperand(0)); break;
6402       }
6403
6404       Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op), DAG);
6405
6406       // Now that the custom expander is done, expand the result, which is still
6407       // VT.
6408       if (Op.getNode()) {
6409         ExpandOp(Op, Lo, Hi);
6410         break;
6411       }
6412     }
6413
6414     RTLIB::Libcall LC = RTLIB::getFPTOSINT(Node->getOperand(0).getValueType(),
6415                                            VT);
6416     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected uint-to-fp conversion!");
6417     Lo = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Hi);
6418     break;
6419   }
6420
6421   case ISD::FP_TO_UINT: {
6422     if (TLI.getOperationAction(ISD::FP_TO_UINT, VT) == TargetLowering::Custom) {
6423       SDValue Op;
6424       switch (getTypeAction(Node->getOperand(0).getValueType())) {
6425         case Expand: assert(0 && "cannot expand FP!");
6426         case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
6427         case Promote: Op = PromoteOp (Node->getOperand(0)); break;
6428       }
6429
6430       Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_UINT, dl, VT, Op), DAG);
6431
6432       // Now that the custom expander is done, expand the result.
6433       if (Op.getNode()) {
6434         ExpandOp(Op, Lo, Hi);
6435         break;
6436       }
6437     }
6438
6439     RTLIB::Libcall LC = RTLIB::getFPTOUINT(Node->getOperand(0).getValueType(),
6440                                            VT);
6441     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fp-to-uint conversion!");
6442     Lo = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Hi);
6443     break;
6444   }
6445
6446   case ISD::SHL: {
6447     // If the target wants custom lowering, do so.
6448     SDValue ShiftAmt = LegalizeOp(Node->getOperand(1));
6449     if (TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Custom) {
6450       SDValue Op = DAG.getNode(ISD::SHL, dl, VT, Node->getOperand(0), ShiftAmt);
6451       Op = TLI.LowerOperation(Op, DAG);
6452       if (Op.getNode()) {
6453         // Now that the custom expander is done, expand the result, which is
6454         // still VT.
6455         ExpandOp(Op, Lo, Hi);
6456         break;
6457       }
6458     }
6459
6460     // If ADDC/ADDE are supported and if the shift amount is a constant 1, emit
6461     // this X << 1 as X+X.
6462     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(ShiftAmt)) {
6463       if (ShAmt->getAPIntValue() == 1 &&
6464           TLI.isOperationLegalOrCustom(ISD::ADDC, NVT) &&
6465           TLI.isOperationLegalOrCustom(ISD::ADDE, NVT)) {
6466         SDValue LoOps[2], HiOps[3];
6467         ExpandOp(Node->getOperand(0), LoOps[0], HiOps[0]);
6468         SDVTList VTList = DAG.getVTList(LoOps[0].getValueType(), MVT::Flag);
6469         LoOps[1] = LoOps[0];
6470         Lo = DAG.getNode(ISD::ADDC, dl, VTList, LoOps, 2);
6471
6472         HiOps[1] = HiOps[0];
6473         HiOps[2] = Lo.getValue(1);
6474         Hi = DAG.getNode(ISD::ADDE, dl, VTList, HiOps, 3);
6475         break;
6476       }
6477     }
6478
6479     // If we can emit an efficient shift operation, do so now.
6480     if (ExpandShift(ISD::SHL, Node->getOperand(0), ShiftAmt, Lo, Hi, dl))
6481       break;
6482
6483     // If this target supports SHL_PARTS, use it.
6484     TargetLowering::LegalizeAction Action =
6485       TLI.getOperationAction(ISD::SHL_PARTS, NVT);
6486     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
6487         Action == TargetLowering::Custom) {
6488       ExpandShiftParts(ISD::SHL_PARTS, Node->getOperand(0),
6489                        ShiftAmt, Lo, Hi, dl);
6490       break;
6491     }
6492
6493     // Otherwise, emit a libcall.
6494     Lo = ExpandLibCall(RTLIB::SHL_I64, Node, false/*left shift=unsigned*/, Hi);
6495     break;
6496   }
6497
6498   case ISD::SRA: {
6499     // If the target wants custom lowering, do so.
6500     SDValue ShiftAmt = LegalizeOp(Node->getOperand(1));
6501     if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Custom) {
6502       SDValue Op = DAG.getNode(ISD::SRA, dl, VT, Node->getOperand(0), ShiftAmt);
6503       Op = TLI.LowerOperation(Op, DAG);
6504       if (Op.getNode()) {
6505         // Now that the custom expander is done, expand the result, which is
6506         // still VT.
6507         ExpandOp(Op, Lo, Hi);
6508         break;
6509       }
6510     }
6511
6512     // If we can emit an efficient shift operation, do so now.
6513     if (ExpandShift(ISD::SRA,  Node->getOperand(0), ShiftAmt, Lo, Hi, dl))
6514       break;
6515
6516     // If this target supports SRA_PARTS, use it.
6517     TargetLowering::LegalizeAction Action =
6518       TLI.getOperationAction(ISD::SRA_PARTS, NVT);
6519     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
6520         Action == TargetLowering::Custom) {
6521       ExpandShiftParts(ISD::SRA_PARTS, Node->getOperand(0),
6522                        ShiftAmt, Lo, Hi, dl);
6523       break;
6524     }
6525
6526     // Otherwise, emit a libcall.
6527     Lo = ExpandLibCall(RTLIB::SRA_I64, Node, true/*ashr is signed*/, Hi);
6528     break;
6529   }
6530
6531   case ISD::SRL: {
6532     // If the target wants custom lowering, do so.
6533     SDValue ShiftAmt = LegalizeOp(Node->getOperand(1));
6534     if (TLI.getOperationAction(ISD::SRL, VT) == TargetLowering::Custom) {
6535       SDValue Op = DAG.getNode(ISD::SRL, dl, VT, Node->getOperand(0), ShiftAmt);
6536       Op = TLI.LowerOperation(Op, DAG);
6537       if (Op.getNode()) {
6538         // Now that the custom expander is done, expand the result, which is
6539         // still VT.
6540         ExpandOp(Op, Lo, Hi);
6541         break;
6542       }
6543     }
6544
6545     // If we can emit an efficient shift operation, do so now.
6546     if (ExpandShift(ISD::SRL, Node->getOperand(0), ShiftAmt, Lo, Hi, dl))
6547       break;
6548
6549     // If this target supports SRL_PARTS, use it.
6550     TargetLowering::LegalizeAction Action =
6551       TLI.getOperationAction(ISD::SRL_PARTS, NVT);
6552     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
6553         Action == TargetLowering::Custom) {
6554       ExpandShiftParts(ISD::SRL_PARTS,
6555                        Node->getOperand(0), ShiftAmt, Lo, Hi, dl);
6556       break;
6557     }
6558
6559     // Otherwise, emit a libcall.
6560     Lo = ExpandLibCall(RTLIB::SRL_I64, Node, false/*lshr is unsigned*/, Hi);
6561     break;
6562   }
6563
6564   case ISD::ADD:
6565   case ISD::SUB: {
6566     // If the target wants to custom expand this, let them.
6567     if (TLI.getOperationAction(Node->getOpcode(), VT) ==
6568             TargetLowering::Custom) {
6569       SDValue Result = TLI.LowerOperation(Op, DAG);
6570       if (Result.getNode()) {
6571         ExpandOp(Result, Lo, Hi);
6572         break;
6573       }
6574     }
6575     // Expand the subcomponents.
6576     SDValue LHSL, LHSH, RHSL, RHSH;
6577     ExpandOp(Node->getOperand(0), LHSL, LHSH);
6578     ExpandOp(Node->getOperand(1), RHSL, RHSH);
6579     SDValue LoOps[2], HiOps[3];
6580     LoOps[0] = LHSL;
6581     LoOps[1] = RHSL;
6582     HiOps[0] = LHSH;
6583     HiOps[1] = RHSH;
6584
6585     //cascaded check to see if any smaller size has a a carry flag.
6586     unsigned OpV = Node->getOpcode() == ISD::ADD ? ISD::ADDC : ISD::SUBC;
6587     bool hasCarry = false;
6588     for (unsigned BitSize = NVT.getSizeInBits(); BitSize != 0; BitSize /= 2) {
6589       MVT AVT = MVT::getIntegerVT(BitSize);
6590       if (TLI.isOperationLegalOrCustom(OpV, AVT)) {
6591         hasCarry = true;
6592         break;
6593       }
6594     }
6595
6596     if(hasCarry) {
6597       SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
6598       if (Node->getOpcode() == ISD::ADD) {
6599         Lo = DAG.getNode(ISD::ADDC, dl, VTList, LoOps, 2);
6600         HiOps[2] = Lo.getValue(1);
6601         Hi = DAG.getNode(ISD::ADDE, dl, VTList, HiOps, 3);
6602       } else {
6603         Lo = DAG.getNode(ISD::SUBC, dl, VTList, LoOps, 2);
6604         HiOps[2] = Lo.getValue(1);
6605         Hi = DAG.getNode(ISD::SUBE, dl, VTList, HiOps, 3);
6606       }
6607       break;
6608     } else {
6609       if (Node->getOpcode() == ISD::ADD) {
6610         Lo = DAG.getNode(ISD::ADD, dl, NVT, LoOps, 2);
6611         Hi = DAG.getNode(ISD::ADD, dl, NVT, HiOps, 2);
6612         SDValue Cmp1 = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT),
6613                                     Lo, LoOps[0], ISD::SETULT);
6614         SDValue Carry1 = DAG.getNode(ISD::SELECT, dl, NVT, Cmp1,
6615                                      DAG.getConstant(1, NVT),
6616                                      DAG.getConstant(0, NVT));
6617         SDValue Cmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT),
6618                                     Lo, LoOps[1], ISD::SETULT);
6619         SDValue Carry2 = DAG.getNode(ISD::SELECT, dl, NVT, Cmp2,
6620                                     DAG.getConstant(1, NVT),
6621                                     Carry1);
6622         Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, Carry2);
6623       } else {
6624         Lo = DAG.getNode(ISD::SUB, dl, NVT, LoOps, 2);
6625         Hi = DAG.getNode(ISD::SUB, dl, NVT, HiOps, 2);
6626         SDValue Cmp = DAG.getSetCC(dl, NVT, LoOps[0], LoOps[1], ISD::SETULT);
6627         SDValue Borrow = DAG.getNode(ISD::SELECT, dl, NVT, Cmp,
6628                                      DAG.getConstant(1, NVT),
6629                                      DAG.getConstant(0, NVT));
6630         Hi = DAG.getNode(ISD::SUB, dl, NVT, Hi, Borrow);
6631       }
6632       break;
6633     }
6634   }
6635
6636   case ISD::ADDC:
6637   case ISD::SUBC: {
6638     // Expand the subcomponents.
6639     SDValue LHSL, LHSH, RHSL, RHSH;
6640     ExpandOp(Node->getOperand(0), LHSL, LHSH);
6641     ExpandOp(Node->getOperand(1), RHSL, RHSH);
6642     SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
6643     SDValue LoOps[2] = { LHSL, RHSL };
6644     SDValue HiOps[3] = { LHSH, RHSH };
6645
6646     if (Node->getOpcode() == ISD::ADDC) {
6647       Lo = DAG.getNode(ISD::ADDC, dl, VTList, LoOps, 2);
6648       HiOps[2] = Lo.getValue(1);
6649       Hi = DAG.getNode(ISD::ADDE, dl, VTList, HiOps, 3);
6650     } else {
6651       Lo = DAG.getNode(ISD::SUBC, dl, VTList, LoOps, 2);
6652       HiOps[2] = Lo.getValue(1);
6653       Hi = DAG.getNode(ISD::SUBE, dl, VTList, HiOps, 3);
6654     }
6655     // Remember that we legalized the flag.
6656     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Hi.getValue(1)));
6657     break;
6658   }
6659   case ISD::ADDE:
6660   case ISD::SUBE: {
6661     // Expand the subcomponents.
6662     SDValue LHSL, LHSH, RHSL, RHSH;
6663     ExpandOp(Node->getOperand(0), LHSL, LHSH);
6664     ExpandOp(Node->getOperand(1), RHSL, RHSH);
6665     SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
6666     SDValue LoOps[3] = { LHSL, RHSL, Node->getOperand(2) };
6667     SDValue HiOps[3] = { LHSH, RHSH };
6668
6669     Lo = DAG.getNode(Node->getOpcode(), dl, VTList, LoOps, 3);
6670     HiOps[2] = Lo.getValue(1);
6671     Hi = DAG.getNode(Node->getOpcode(), dl, VTList, HiOps, 3);
6672
6673     // Remember that we legalized the flag.
6674     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Hi.getValue(1)));
6675     break;
6676   }
6677   case ISD::MUL: {
6678     // If the target wants to custom expand this, let them.
6679     if (TLI.getOperationAction(ISD::MUL, VT) == TargetLowering::Custom) {
6680       SDValue New = TLI.LowerOperation(Op, DAG);
6681       if (New.getNode()) {
6682         ExpandOp(New, Lo, Hi);
6683         break;
6684       }
6685     }
6686
6687     bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, NVT);
6688     bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, NVT);
6689     bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, NVT);
6690     bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, NVT);
6691     if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
6692       SDValue LL, LH, RL, RH;
6693       ExpandOp(Node->getOperand(0), LL, LH);
6694       ExpandOp(Node->getOperand(1), RL, RH);
6695       unsigned OuterBitSize = Op.getValueSizeInBits();
6696       unsigned InnerBitSize = RH.getValueSizeInBits();
6697       unsigned LHSSB = DAG.ComputeNumSignBits(Op.getOperand(0));
6698       unsigned RHSSB = DAG.ComputeNumSignBits(Op.getOperand(1));
6699       APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
6700       if (DAG.MaskedValueIsZero(Node->getOperand(0), HighMask) &&
6701           DAG.MaskedValueIsZero(Node->getOperand(1), HighMask)) {
6702         // The inputs are both zero-extended.
6703         if (HasUMUL_LOHI) {
6704           // We can emit a umul_lohi.
6705           Lo = DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(NVT, NVT), LL, RL);
6706           Hi = SDValue(Lo.getNode(), 1);
6707           break;
6708         }
6709         if (HasMULHU) {
6710           // We can emit a mulhu+mul.
6711           Lo = DAG.getNode(ISD::MUL, dl, NVT, LL, RL);
6712           Hi = DAG.getNode(ISD::MULHU, dl, NVT, LL, RL);
6713           break;
6714         }
6715       }
6716       if (LHSSB > InnerBitSize && RHSSB > InnerBitSize) {
6717         // The input values are both sign-extended.
6718         if (HasSMUL_LOHI) {
6719           // We can emit a smul_lohi.
6720           Lo = DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(NVT, NVT), LL, RL);
6721           Hi = SDValue(Lo.getNode(), 1);
6722           break;
6723         }
6724         if (HasMULHS) {
6725           // We can emit a mulhs+mul.
6726           Lo = DAG.getNode(ISD::MUL, dl, NVT, LL, RL);
6727           Hi = DAG.getNode(ISD::MULHS, dl, NVT, LL, RL);
6728           break;
6729         }
6730       }
6731       if (HasUMUL_LOHI) {
6732         // Lo,Hi = umul LHS, RHS.
6733         SDValue UMulLOHI = DAG.getNode(ISD::UMUL_LOHI, dl,
6734                                          DAG.getVTList(NVT, NVT), LL, RL);
6735         Lo = UMulLOHI;
6736         Hi = UMulLOHI.getValue(1);
6737         RH = DAG.getNode(ISD::MUL, dl, NVT, LL, RH);
6738         LH = DAG.getNode(ISD::MUL, dl, NVT, LH, RL);
6739         Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, RH);
6740         Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, LH);
6741         break;
6742       }
6743       if (HasMULHU) {
6744         Lo = DAG.getNode(ISD::MUL, dl, NVT, LL, RL);
6745         Hi = DAG.getNode(ISD::MULHU, dl, NVT, LL, RL);
6746         RH = DAG.getNode(ISD::MUL, dl, NVT, LL, RH);
6747         LH = DAG.getNode(ISD::MUL, dl, NVT, LH, RL);
6748         Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, RH);
6749         Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, LH);
6750         break;
6751       }
6752     }
6753
6754     // If nothing else, we can make a libcall.
6755     Lo = ExpandLibCall(RTLIB::MUL_I64, Node, false/*sign irrelevant*/, Hi);
6756     break;
6757   }
6758   case ISD::SDIV:
6759     Lo = ExpandLibCall(RTLIB::SDIV_I64, Node, true, Hi);
6760     break;
6761   case ISD::UDIV:
6762     Lo = ExpandLibCall(RTLIB::UDIV_I64, Node, true, Hi);
6763     break;
6764   case ISD::SREM:
6765     Lo = ExpandLibCall(RTLIB::SREM_I64, Node, true, Hi);
6766     break;
6767   case ISD::UREM:
6768     Lo = ExpandLibCall(RTLIB::UREM_I64, Node, true, Hi);
6769     break;
6770
6771   case ISD::FADD:
6772     Lo = ExpandLibCall(GetFPLibCall(VT, RTLIB::ADD_F32,
6773                                         RTLIB::ADD_F64,
6774                                         RTLIB::ADD_F80,
6775                                         RTLIB::ADD_PPCF128),
6776                        Node, false, Hi);
6777     break;
6778   case ISD::FSUB:
6779     Lo = ExpandLibCall(GetFPLibCall(VT, RTLIB::SUB_F32,
6780                                         RTLIB::SUB_F64,
6781                                         RTLIB::SUB_F80,
6782                                         RTLIB::SUB_PPCF128),
6783                        Node, false, Hi);
6784     break;
6785   case ISD::FMUL:
6786     Lo = ExpandLibCall(GetFPLibCall(VT, RTLIB::MUL_F32,
6787                                         RTLIB::MUL_F64,
6788                                         RTLIB::MUL_F80,
6789                                         RTLIB::MUL_PPCF128),
6790                        Node, false, Hi);
6791     break;
6792   case ISD::FDIV:
6793     Lo = ExpandLibCall(GetFPLibCall(VT, RTLIB::DIV_F32,
6794                                         RTLIB::DIV_F64,
6795                                         RTLIB::DIV_F80,
6796                                         RTLIB::DIV_PPCF128),
6797                        Node, false, Hi);
6798     break;
6799   case ISD::FP_EXTEND: {
6800     if (VT == MVT::ppcf128) {
6801       assert(Node->getOperand(0).getValueType()==MVT::f32 ||
6802              Node->getOperand(0).getValueType()==MVT::f64);
6803       const uint64_t zero = 0;
6804       if (Node->getOperand(0).getValueType()==MVT::f32)
6805         Hi = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Node->getOperand(0));
6806       else
6807         Hi = Node->getOperand(0);
6808       Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &zero)), MVT::f64);
6809       break;
6810     }
6811     RTLIB::Libcall LC = RTLIB::getFPEXT(Node->getOperand(0).getValueType(), VT);
6812     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported FP_EXTEND!");
6813     Lo = ExpandLibCall(LC, Node, true, Hi);
6814     break;
6815   }
6816   case ISD::FP_ROUND: {
6817     RTLIB::Libcall LC = RTLIB::getFPROUND(Node->getOperand(0).getValueType(),
6818                                           VT);
6819     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported FP_ROUND!");
6820     Lo = ExpandLibCall(LC, Node, true, Hi);
6821     break;
6822   }
6823   case ISD::FSQRT:
6824   case ISD::FSIN:
6825   case ISD::FCOS:
6826   case ISD::FLOG:
6827   case ISD::FLOG2:
6828   case ISD::FLOG10:
6829   case ISD::FEXP:
6830   case ISD::FEXP2:
6831   case ISD::FTRUNC:
6832   case ISD::FFLOOR:
6833   case ISD::FCEIL:
6834   case ISD::FRINT:
6835   case ISD::FNEARBYINT:
6836   case ISD::FPOW:
6837   case ISD::FPOWI: {
6838     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
6839     switch(Node->getOpcode()) {
6840     case ISD::FSQRT:
6841       LC = GetFPLibCall(VT, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
6842                         RTLIB::SQRT_F80, RTLIB::SQRT_PPCF128);
6843       break;
6844     case ISD::FSIN:
6845       LC = GetFPLibCall(VT, RTLIB::SIN_F32, RTLIB::SIN_F64,
6846                         RTLIB::SIN_F80, RTLIB::SIN_PPCF128);
6847       break;
6848     case ISD::FCOS:
6849       LC = GetFPLibCall(VT, RTLIB::COS_F32, RTLIB::COS_F64,
6850                         RTLIB::COS_F80, RTLIB::COS_PPCF128);
6851       break;
6852     case ISD::FLOG:
6853       LC = GetFPLibCall(VT, RTLIB::LOG_F32, RTLIB::LOG_F64,
6854                         RTLIB::LOG_F80, RTLIB::LOG_PPCF128);
6855       break;
6856     case ISD::FLOG2:
6857       LC = GetFPLibCall(VT, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
6858                         RTLIB::LOG2_F80, RTLIB::LOG2_PPCF128);
6859       break;
6860     case ISD::FLOG10:
6861       LC = GetFPLibCall(VT, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
6862                         RTLIB::LOG10_F80, RTLIB::LOG10_PPCF128);
6863       break;
6864     case ISD::FEXP:
6865       LC = GetFPLibCall(VT, RTLIB::EXP_F32, RTLIB::EXP_F64,
6866                         RTLIB::EXP_F80, RTLIB::EXP_PPCF128);
6867       break;
6868     case ISD::FEXP2:
6869       LC = GetFPLibCall(VT, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
6870                         RTLIB::EXP2_F80, RTLIB::EXP2_PPCF128);
6871       break;
6872     case ISD::FTRUNC:
6873       LC = GetFPLibCall(VT, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
6874                         RTLIB::TRUNC_F80, RTLIB::TRUNC_PPCF128);
6875       break;
6876     case ISD::FFLOOR:
6877       LC = GetFPLibCall(VT, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
6878                         RTLIB::FLOOR_F80, RTLIB::FLOOR_PPCF128);
6879       break;
6880     case ISD::FCEIL:
6881       LC = GetFPLibCall(VT, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
6882                         RTLIB::CEIL_F80, RTLIB::CEIL_PPCF128);
6883       break;
6884     case ISD::FRINT:
6885       LC = GetFPLibCall(VT, RTLIB::RINT_F32, RTLIB::RINT_F64,
6886                         RTLIB::RINT_F80, RTLIB::RINT_PPCF128);
6887       break;
6888     case ISD::FNEARBYINT:
6889       LC = GetFPLibCall(VT, RTLIB::NEARBYINT_F32, RTLIB::NEARBYINT_F64,
6890                         RTLIB::NEARBYINT_F80, RTLIB::NEARBYINT_PPCF128);
6891       break;
6892     case ISD::FPOW:
6893       LC = GetFPLibCall(VT, RTLIB::POW_F32, RTLIB::POW_F64, RTLIB::POW_F80,
6894                         RTLIB::POW_PPCF128);
6895       break;
6896     case ISD::FPOWI:
6897       LC = GetFPLibCall(VT, RTLIB::POWI_F32, RTLIB::POWI_F64, RTLIB::POWI_F80,
6898                         RTLIB::POWI_PPCF128);
6899       break;
6900     default: assert(0 && "Unreachable!");
6901     }
6902     Lo = ExpandLibCall(LC, Node, false, Hi);
6903     break;
6904   }
6905   case ISD::FABS: {
6906     if (VT == MVT::ppcf128) {
6907       SDValue Tmp;
6908       ExpandOp(Node->getOperand(0), Lo, Tmp);
6909       Hi = DAG.getNode(ISD::FABS, dl, NVT, Tmp);
6910       // lo = hi==fabs(hi) ? lo : -lo;
6911       Lo = DAG.getNode(ISD::SELECT_CC, dl, NVT, Hi, Tmp,
6912                        Lo, DAG.getNode(ISD::FNEG, dl, NVT, Lo),
6913                        DAG.getCondCode(ISD::SETEQ));
6914       break;
6915     }
6916     SDValue Mask = (VT == MVT::f64)
6917       ? DAG.getConstantFP(BitsToDouble(~(1ULL << 63)), VT)
6918       : DAG.getConstantFP(BitsToFloat(~(1U << 31)), VT);
6919     Mask = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Mask);
6920     Lo = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Node->getOperand(0));
6921     Lo = DAG.getNode(ISD::AND, dl, NVT, Lo, Mask);
6922     if (getTypeAction(NVT) == Expand)
6923       ExpandOp(Lo, Lo, Hi);
6924     break;
6925   }
6926   case ISD::FNEG: {
6927     if (VT == MVT::ppcf128) {
6928       ExpandOp(Node->getOperand(0), Lo, Hi);
6929       Lo = DAG.getNode(ISD::FNEG, dl, MVT::f64, Lo);
6930       Hi = DAG.getNode(ISD::FNEG, dl, MVT::f64, Hi);
6931       break;
6932     }
6933     SDValue Mask = (VT == MVT::f64)
6934       ? DAG.getConstantFP(BitsToDouble(1ULL << 63), VT)
6935       : DAG.getConstantFP(BitsToFloat(1U << 31), VT);
6936     Mask = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Mask);
6937     Lo = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Node->getOperand(0));
6938     Lo = DAG.getNode(ISD::XOR, dl, NVT, Lo, Mask);
6939     if (getTypeAction(NVT) == Expand)
6940       ExpandOp(Lo, Lo, Hi);
6941     break;
6942   }
6943   case ISD::FCOPYSIGN: {
6944     Lo = ExpandFCOPYSIGNToBitwiseOps(Node, NVT, DAG, TLI);
6945     if (getTypeAction(NVT) == Expand)
6946       ExpandOp(Lo, Lo, Hi);
6947     break;
6948   }
6949   case ISD::SINT_TO_FP:
6950   case ISD::UINT_TO_FP: {
6951     bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
6952     MVT SrcVT = Node->getOperand(0).getValueType();
6953
6954     // Promote the operand if needed.  Do this before checking for
6955     // ppcf128 so conversions of i16 and i8 work.
6956     if (getTypeAction(SrcVT) == Promote) {
6957       SDValue Tmp = PromoteOp(Node->getOperand(0));
6958       Tmp = isSigned
6959         ? DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Tmp.getValueType(), Tmp,
6960                       DAG.getValueType(SrcVT))
6961         : DAG.getZeroExtendInReg(Tmp, dl, SrcVT);
6962       Node = DAG.UpdateNodeOperands(Op, Tmp).getNode();
6963       SrcVT = Node->getOperand(0).getValueType();
6964     }
6965
6966     if (VT == MVT::ppcf128 && SrcVT == MVT::i32) {
6967       static const uint64_t zero = 0;
6968       if (isSigned) {
6969         Hi = LegalizeOp(DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f64,
6970                                     Node->getOperand(0)));
6971         Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &zero)), MVT::f64);
6972       } else {
6973         static const uint64_t TwoE32[] = { 0x41f0000000000000LL, 0 };
6974         Hi = LegalizeOp(DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f64,
6975                                     Node->getOperand(0)));
6976         Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &zero)), MVT::f64);
6977         Hi = DAG.getNode(ISD::BUILD_PAIR, dl, VT, Lo, Hi);
6978         // X>=0 ? {(f64)x, 0} : {(f64)x, 0} + 2^32
6979         ExpandOp(DAG.getNode(ISD::SELECT_CC, dl,
6980                              MVT::ppcf128, Node->getOperand(0),
6981                              DAG.getConstant(0, MVT::i32),
6982                              DAG.getNode(ISD::FADD, dl, MVT::ppcf128, Hi,
6983                                          DAG.getConstantFP
6984                                          (APFloat(APInt(128, 2, TwoE32)),
6985                                           MVT::ppcf128)),
6986                              Hi,
6987                              DAG.getCondCode(ISD::SETLT)),
6988                  Lo, Hi);
6989       }
6990       break;
6991     }
6992     if (VT == MVT::ppcf128 && SrcVT == MVT::i64 && !isSigned) {
6993       // si64->ppcf128 done by libcall, below
6994       static const uint64_t TwoE64[] = { 0x43f0000000000000LL, 0 };
6995       ExpandOp(DAG.getNode(ISD::SINT_TO_FP, dl, MVT::ppcf128,
6996                Node->getOperand(0)), Lo, Hi);
6997       Hi = DAG.getNode(ISD::BUILD_PAIR, dl, VT, Lo, Hi);
6998       // x>=0 ? (ppcf128)(i64)x : (ppcf128)(i64)x + 2^64
6999       ExpandOp(DAG.getNode(ISD::SELECT_CC, dl, MVT::ppcf128,
7000                            Node->getOperand(0),
7001                            DAG.getConstant(0, MVT::i64),
7002                            DAG.getNode(ISD::FADD, dl, MVT::ppcf128, Hi,
7003                                        DAG.getConstantFP
7004                                        (APFloat(APInt(128, 2, TwoE64)),
7005                                         MVT::ppcf128)),
7006                            Hi,
7007                            DAG.getCondCode(ISD::SETLT)),
7008                Lo, Hi);
7009       break;
7010     }
7011
7012     Lo = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, VT,
7013                        Node->getOperand(0), dl);
7014     if (getTypeAction(Lo.getValueType()) == Expand)
7015       // float to i32 etc. can be 'expanded' to a single node.
7016       ExpandOp(Lo, Lo, Hi);
7017     break;
7018   }
7019   }
7020
7021   // Make sure the resultant values have been legalized themselves, unless this
7022   // is a type that requires multi-step expansion.
7023   if (getTypeAction(NVT) != Expand && NVT != MVT::isVoid) {
7024     Lo = LegalizeOp(Lo);
7025     if (Hi.getNode())
7026       // Don't legalize the high part if it is expanded to a single node.
7027       Hi = LegalizeOp(Hi);
7028   }
7029
7030   // Remember in a map if the values will be reused later.
7031   bool isNew =
7032     ExpandedNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
7033   assert(isNew && "Value already expanded?!?");
7034   isNew = isNew;
7035 }
7036
7037 /// SplitVectorOp - Given an operand of vector type, break it down into
7038 /// two smaller values, still of vector type.
7039 void SelectionDAGLegalize::SplitVectorOp(SDValue Op, SDValue &Lo,
7040                                          SDValue &Hi) {
7041   assert(0 && "This should be dead!");
7042   assert(Op.getValueType().isVector() && "Cannot split non-vector type!");
7043   SDNode *Node = Op.getNode();
7044   DebugLoc dl = Node->getDebugLoc();
7045   unsigned NumElements = Op.getValueType().getVectorNumElements();
7046   assert(NumElements > 1 && "Cannot split a single element vector!");
7047
7048   MVT NewEltVT = Op.getValueType().getVectorElementType();
7049
7050   unsigned NewNumElts_Lo = 1 << Log2_32(NumElements-1);
7051   unsigned NewNumElts_Hi = NumElements - NewNumElts_Lo;
7052
7053   MVT NewVT_Lo = MVT::getVectorVT(NewEltVT, NewNumElts_Lo);
7054   MVT NewVT_Hi = MVT::getVectorVT(NewEltVT, NewNumElts_Hi);
7055
7056   // See if we already split it.
7057   std::map<SDValue, std::pair<SDValue, SDValue> >::iterator I
7058     = SplitNodes.find(Op);
7059   if (I != SplitNodes.end()) {
7060     Lo = I->second.first;
7061     Hi = I->second.second;
7062     return;
7063   }
7064
7065   switch (Node->getOpcode()) {
7066   default:
7067 #ifndef NDEBUG
7068     Node->dump(&DAG);
7069 #endif
7070     assert(0 && "Unhandled operation in SplitVectorOp!");
7071   case ISD::UNDEF:
7072     Lo = DAG.getUNDEF(NewVT_Lo);
7073     Hi = DAG.getUNDEF(NewVT_Hi);
7074     break;
7075   case ISD::BUILD_PAIR:
7076     Lo = Node->getOperand(0);
7077     Hi = Node->getOperand(1);
7078     break;
7079   case ISD::INSERT_VECTOR_ELT: {
7080     if (ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Node->getOperand(2))) {
7081       SplitVectorOp(Node->getOperand(0), Lo, Hi);
7082       unsigned Index = Idx->getZExtValue();
7083       SDValue ScalarOp = Node->getOperand(1);
7084       if (Index < NewNumElts_Lo)
7085         Lo = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, NewVT_Lo, Lo, ScalarOp,
7086                          DAG.getIntPtrConstant(Index));
7087       else
7088         Hi = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, NewVT_Hi, Hi, ScalarOp,
7089                          DAG.getIntPtrConstant(Index - NewNumElts_Lo));
7090       break;
7091     }
7092     SDValue Tmp = PerformInsertVectorEltInMemory(Node->getOperand(0),
7093                                                  Node->getOperand(1),
7094                                                  Node->getOperand(2), dl);
7095     SplitVectorOp(Tmp, Lo, Hi);
7096     break;
7097   }
7098   case ISD::VECTOR_SHUFFLE: {
7099     // Build the low part.
7100     SDValue Mask = Node->getOperand(2);
7101     SmallVector<SDValue, 8> Ops;
7102     MVT PtrVT = TLI.getPointerTy();
7103
7104     // Insert all of the elements from the input that are needed.  We use
7105     // buildvector of extractelement here because the input vectors will have
7106     // to be legalized, so this makes the code simpler.
7107     for (unsigned i = 0; i != NewNumElts_Lo; ++i) {
7108       SDValue IdxNode = Mask.getOperand(i);
7109       if (IdxNode.getOpcode() == ISD::UNDEF) {
7110         Ops.push_back(DAG.getUNDEF(NewEltVT));
7111         continue;
7112       }
7113       unsigned Idx = cast<ConstantSDNode>(IdxNode)->getZExtValue();
7114       SDValue InVec = Node->getOperand(0);
7115       if (Idx >= NumElements) {
7116         InVec = Node->getOperand(1);
7117         Idx -= NumElements;
7118       }
7119       Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, NewEltVT, InVec,
7120                                 DAG.getConstant(Idx, PtrVT)));
7121     }
7122     Lo = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT_Lo, &Ops[0], Ops.size());
7123     Ops.clear();
7124
7125     for (unsigned i = NewNumElts_Lo; i != NumElements; ++i) {
7126       SDValue IdxNode = Mask.getOperand(i);
7127       if (IdxNode.getOpcode() == ISD::UNDEF) {
7128         Ops.push_back(DAG.getUNDEF(NewEltVT));
7129         continue;
7130       }
7131       unsigned Idx = cast<ConstantSDNode>(IdxNode)->getZExtValue();
7132       SDValue InVec = Node->getOperand(0);
7133       if (Idx >= NumElements) {
7134         InVec = Node->getOperand(1);
7135         Idx -= NumElements;
7136       }
7137       Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, NewEltVT, InVec,
7138                                 DAG.getConstant(Idx, PtrVT)));
7139     }
7140     Hi = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT_Hi, &Ops[0], Ops.size());
7141     break;
7142   }
7143   case ISD::BUILD_VECTOR: {
7144     SmallVector<SDValue, 8> LoOps(Node->op_begin(),
7145                                   Node->op_begin()+NewNumElts_Lo);
7146     Lo = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT_Lo, &LoOps[0], LoOps.size());
7147
7148     SmallVector<SDValue, 8> HiOps(Node->op_begin()+NewNumElts_Lo,
7149                                   Node->op_end());
7150     Hi = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT_Hi, &HiOps[0], HiOps.size());
7151     break;
7152   }
7153   case ISD::CONCAT_VECTORS: {
7154     // FIXME: Handle non-power-of-two vectors?
7155     unsigned NewNumSubvectors = Node->getNumOperands() / 2;
7156     if (NewNumSubvectors == 1) {
7157       Lo = Node->getOperand(0);
7158       Hi = Node->getOperand(1);
7159     } else {
7160       SmallVector<SDValue, 8> LoOps(Node->op_begin(),
7161                                     Node->op_begin()+NewNumSubvectors);
7162       Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewVT_Lo,
7163                        &LoOps[0], LoOps.size());
7164
7165       SmallVector<SDValue, 8> HiOps(Node->op_begin()+NewNumSubvectors,
7166                                     Node->op_end());
7167       Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewVT_Hi,
7168                        &HiOps[0], HiOps.size());
7169     }
7170     break;
7171   }
7172   case ISD::EXTRACT_SUBVECTOR: {
7173     SDValue Vec = Op.getOperand(0);
7174     SDValue Idx = Op.getOperand(1);
7175     MVT     IdxVT = Idx.getValueType();
7176
7177     Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NewVT_Lo, Vec, Idx);
7178     ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx);
7179     if (CIdx) {
7180       Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NewVT_Hi, Vec,
7181                        DAG.getConstant(CIdx->getZExtValue() + NewNumElts_Lo,
7182                                        IdxVT));
7183     } else {
7184       Idx = DAG.getNode(ISD::ADD, dl, IdxVT, Idx,
7185                         DAG.getConstant(NewNumElts_Lo, IdxVT));
7186       Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NewVT_Hi, Vec, Idx);
7187     }
7188     break;
7189   }
7190   case ISD::SELECT: {
7191     SDValue Cond = Node->getOperand(0);
7192
7193     SDValue LL, LH, RL, RH;
7194     SplitVectorOp(Node->getOperand(1), LL, LH);
7195     SplitVectorOp(Node->getOperand(2), RL, RH);
7196
7197     if (Cond.getValueType().isVector()) {
7198       // Handle a vector merge.
7199       SDValue CL, CH;
7200       SplitVectorOp(Cond, CL, CH);
7201       Lo = DAG.getNode(Node->getOpcode(), dl, NewVT_Lo, CL, LL, RL);
7202       Hi = DAG.getNode(Node->getOpcode(), dl, NewVT_Hi, CH, LH, RH);
7203     } else {
7204       // Handle a simple select with vector operands.
7205       Lo = DAG.getNode(Node->getOpcode(), dl, NewVT_Lo, Cond, LL, RL);
7206       Hi = DAG.getNode(Node->getOpcode(), dl, NewVT_Hi, Cond, LH, RH);
7207     }
7208     break;
7209   }
7210   case ISD::SELECT_CC: {
7211     SDValue CondLHS = Node->getOperand(0);
7212     SDValue CondRHS = Node->getOperand(1);
7213     SDValue CondCode = Node->getOperand(4);
7214
7215     SDValue LL, LH, RL, RH;
7216     SplitVectorOp(Node->getOperand(2), LL, LH);
7217     SplitVectorOp(Node->getOperand(3), RL, RH);
7218
7219     // Handle a simple select with vector operands.
7220     Lo = DAG.getNode(ISD::SELECT_CC, dl, NewVT_Lo, CondLHS, CondRHS,
7221                      LL, RL, CondCode);
7222     Hi = DAG.getNode(ISD::SELECT_CC, dl, NewVT_Hi, CondLHS, CondRHS,
7223                      LH, RH, CondCode);
7224     break;
7225   }
7226   case ISD::VSETCC: {
7227     SDValue LL, LH, RL, RH;
7228     SplitVectorOp(Node->getOperand(0), LL, LH);
7229     SplitVectorOp(Node->getOperand(1), RL, RH);
7230     Lo = DAG.getNode(ISD::VSETCC, dl, NewVT_Lo, LL, RL, Node->getOperand(2));
7231     Hi = DAG.getNode(ISD::VSETCC, dl, NewVT_Hi, LH, RH, Node->getOperand(2));
7232     break;
7233   }
7234   case ISD::ADD:
7235   case ISD::SUB:
7236   case ISD::MUL:
7237   case ISD::FADD:
7238   case ISD::FSUB:
7239   case ISD::FMUL:
7240   case ISD::SDIV:
7241   case ISD::UDIV:
7242   case ISD::FDIV:
7243   case ISD::FPOW:
7244   case ISD::AND:
7245   case ISD::OR:
7246   case ISD::XOR:
7247   case ISD::UREM:
7248   case ISD::SREM:
7249   case ISD::FREM:
7250   case ISD::SHL:
7251   case ISD::SRA:
7252   case ISD::SRL: {
7253     SDValue LL, LH, RL, RH;
7254     SplitVectorOp(Node->getOperand(0), LL, LH);
7255     SplitVectorOp(Node->getOperand(1), RL, RH);
7256
7257     Lo = DAG.getNode(Node->getOpcode(), dl, NewVT_Lo, LL, RL);
7258     Hi = DAG.getNode(Node->getOpcode(), dl, NewVT_Hi, LH, RH);
7259     break;
7260   }
7261   case ISD::FP_ROUND:
7262   case ISD::FPOWI: {
7263     SDValue L, H;
7264     SplitVectorOp(Node->getOperand(0), L, H);
7265
7266     Lo = DAG.getNode(Node->getOpcode(), dl, NewVT_Lo, L, Node->getOperand(1));
7267     Hi = DAG.getNode(Node->getOpcode(), dl, NewVT_Hi, H, Node->getOperand(1));
7268     break;
7269   }
7270   case ISD::CTTZ:
7271   case ISD::CTLZ:
7272   case ISD::CTPOP:
7273   case ISD::FNEG:
7274   case ISD::FABS:
7275   case ISD::FSQRT:
7276   case ISD::FSIN:
7277   case ISD::FCOS:
7278   case ISD::FLOG:
7279   case ISD::FLOG2:
7280   case ISD::FLOG10:
7281   case ISD::FEXP:
7282   case ISD::FEXP2:
7283   case ISD::FP_TO_SINT:
7284   case ISD::FP_TO_UINT:
7285   case ISD::SINT_TO_FP:
7286   case ISD::UINT_TO_FP:
7287   case ISD::TRUNCATE:
7288   case ISD::ANY_EXTEND:
7289   case ISD::SIGN_EXTEND:
7290   case ISD::ZERO_EXTEND:
7291   case ISD::FP_EXTEND: {
7292     SDValue L, H;
7293     SplitVectorOp(Node->getOperand(0), L, H);
7294
7295     Lo = DAG.getNode(Node->getOpcode(), dl, NewVT_Lo, L);
7296     Hi = DAG.getNode(Node->getOpcode(), dl, NewVT_Hi, H);
7297     break;
7298   }
7299   case ISD::CONVERT_RNDSAT: {
7300     ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(Node)->getCvtCode();
7301     SDValue L, H;
7302     SplitVectorOp(Node->getOperand(0), L, H);
7303     SDValue DTyOpL = DAG.getValueType(NewVT_Lo);
7304     SDValue DTyOpH = DAG.getValueType(NewVT_Hi);
7305     SDValue STyOpL = DAG.getValueType(L.getValueType());
7306     SDValue STyOpH = DAG.getValueType(H.getValueType());
7307
7308     SDValue RndOp = Node->getOperand(3);
7309     SDValue SatOp = Node->getOperand(4);
7310
7311     Lo = DAG.getConvertRndSat(NewVT_Lo, dl, L, DTyOpL, STyOpL,
7312                               RndOp, SatOp, CvtCode);
7313     Hi = DAG.getConvertRndSat(NewVT_Hi, dl, H, DTyOpH, STyOpH,
7314                               RndOp, SatOp, CvtCode);
7315     break;
7316   }
7317   case ISD::LOAD: {
7318     LoadSDNode *LD = cast<LoadSDNode>(Node);
7319     SDValue Ch = LD->getChain();
7320     SDValue Ptr = LD->getBasePtr();
7321     ISD::LoadExtType ExtType = LD->getExtensionType();
7322     const Value *SV = LD->getSrcValue();
7323     int SVOffset = LD->getSrcValueOffset();
7324     MVT MemoryVT = LD->getMemoryVT();
7325     unsigned Alignment = LD->getAlignment();
7326     bool isVolatile = LD->isVolatile();
7327
7328     assert(LD->isUnindexed() && "Indexed vector loads are not supported yet!");
7329     SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7330
7331     MVT MemNewEltVT = MemoryVT.getVectorElementType();
7332     MVT MemNewVT_Lo = MVT::getVectorVT(MemNewEltVT, NewNumElts_Lo);
7333     MVT MemNewVT_Hi = MVT::getVectorVT(MemNewEltVT, NewNumElts_Hi);
7334
7335     Lo = DAG.getLoad(ISD::UNINDEXED, dl, ExtType,
7336                      NewVT_Lo, Ch, Ptr, Offset,
7337                      SV, SVOffset, MemNewVT_Lo, isVolatile, Alignment);
7338     unsigned IncrementSize = NewNumElts_Lo * MemNewEltVT.getSizeInBits()/8;
7339     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
7340                       DAG.getIntPtrConstant(IncrementSize));
7341     SVOffset += IncrementSize;
7342     Alignment = MinAlign(Alignment, IncrementSize);
7343     Hi = DAG.getLoad(ISD::UNINDEXED, dl, ExtType,
7344                      NewVT_Hi, Ch, Ptr, Offset,
7345                      SV, SVOffset, MemNewVT_Hi, isVolatile, Alignment);
7346
7347     // Build a factor node to remember that this load is independent of the
7348     // other one.
7349     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
7350                              Hi.getValue(1));
7351
7352     // Remember that we legalized the chain.
7353     AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
7354     break;
7355   }
7356   case ISD::BIT_CONVERT: {
7357     // We know the result is a vector.  The input may be either a vector or a
7358     // scalar value.
7359     SDValue InOp = Node->getOperand(0);
7360     if (!InOp.getValueType().isVector() ||
7361         InOp.getValueType().getVectorNumElements() == 1) {
7362       // The input is a scalar or single-element vector.
7363       // Lower to a store/load so that it can be split.
7364       // FIXME: this could be improved probably.
7365       unsigned LdAlign = TLI.getTargetData()->
7366         getPrefTypeAlignment(Op.getValueType().getTypeForMVT());
7367       SDValue Ptr = DAG.CreateStackTemporary(InOp.getValueType(), LdAlign);
7368       int FI = cast<FrameIndexSDNode>(Ptr.getNode())->getIndex();
7369
7370       SDValue St = DAG.getStore(DAG.getEntryNode(), dl,
7371                                 InOp, Ptr,
7372                                 PseudoSourceValue::getFixedStack(FI), 0);
7373       InOp = DAG.getLoad(Op.getValueType(), dl, St, Ptr,
7374                          PseudoSourceValue::getFixedStack(FI), 0);
7375     }
7376     // Split the vector and convert each of the pieces now.
7377     SplitVectorOp(InOp, Lo, Hi);
7378     Lo = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT_Lo, Lo);
7379     Hi = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT_Hi, Hi);
7380     break;
7381   }
7382   }
7383
7384   // Remember in a map if the values will be reused later.
7385   bool isNew =
7386     SplitNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
7387   assert(isNew && "Value already split?!?");
7388   isNew = isNew;
7389 }
7390
7391
7392 /// ScalarizeVectorOp - Given an operand of single-element vector type
7393 /// (e.g. v1f32), convert it into the equivalent operation that returns a
7394 /// scalar (e.g. f32) value.
7395 SDValue SelectionDAGLegalize::ScalarizeVectorOp(SDValue Op) {
7396   assert(0 && "This should be dead!");
7397   assert(Op.getValueType().isVector() && "Bad ScalarizeVectorOp invocation!");
7398   SDNode *Node = Op.getNode();
7399   DebugLoc dl = Node->getDebugLoc();
7400   MVT NewVT = Op.getValueType().getVectorElementType();
7401   assert(Op.getValueType().getVectorNumElements() == 1);
7402
7403   // See if we already scalarized it.
7404   std::map<SDValue, SDValue>::iterator I = ScalarizedNodes.find(Op);
7405   if (I != ScalarizedNodes.end()) return I->second;
7406
7407   SDValue Result;
7408   switch (Node->getOpcode()) {
7409   default:
7410 #ifndef NDEBUG
7411     Node->dump(&DAG); cerr << "\n";
7412 #endif
7413     assert(0 && "Unknown vector operation in ScalarizeVectorOp!");
7414   case ISD::ADD:
7415   case ISD::FADD:
7416   case ISD::SUB:
7417   case ISD::FSUB:
7418   case ISD::MUL:
7419   case ISD::FMUL:
7420   case ISD::SDIV:
7421   case ISD::UDIV:
7422   case ISD::FDIV:
7423   case ISD::SREM:
7424   case ISD::UREM:
7425   case ISD::FREM:
7426   case ISD::FPOW:
7427   case ISD::AND:
7428   case ISD::OR:
7429   case ISD::XOR:
7430     Result = DAG.getNode(Node->getOpcode(), dl,
7431                          NewVT,
7432                          ScalarizeVectorOp(Node->getOperand(0)),
7433                          ScalarizeVectorOp(Node->getOperand(1)));
7434     break;
7435   case ISD::FNEG:
7436   case ISD::FABS:
7437   case ISD::FSQRT:
7438   case ISD::FSIN:
7439   case ISD::FCOS:
7440   case ISD::FLOG:
7441   case ISD::FLOG2:
7442   case ISD::FLOG10:
7443   case ISD::FEXP:
7444   case ISD::FEXP2:
7445   case ISD::FP_TO_SINT:
7446   case ISD::FP_TO_UINT:
7447   case ISD::SINT_TO_FP:
7448   case ISD::UINT_TO_FP:
7449   case ISD::SIGN_EXTEND:
7450   case ISD::ZERO_EXTEND:
7451   case ISD::ANY_EXTEND:
7452   case ISD::TRUNCATE:
7453   case ISD::FP_EXTEND:
7454     Result = DAG.getNode(Node->getOpcode(), dl,
7455                          NewVT,
7456                          ScalarizeVectorOp(Node->getOperand(0)));
7457     break;
7458   case ISD::CONVERT_RNDSAT: {
7459     SDValue Op0 = ScalarizeVectorOp(Node->getOperand(0));
7460     Result = DAG.getConvertRndSat(NewVT, dl, Op0,
7461                                   DAG.getValueType(NewVT),
7462                                   DAG.getValueType(Op0.getValueType()),
7463                                   Node->getOperand(3),
7464                                   Node->getOperand(4),
7465                                   cast<CvtRndSatSDNode>(Node)->getCvtCode());
7466     break;
7467   }
7468   case ISD::FPOWI:
7469   case ISD::FP_ROUND:
7470     Result = DAG.getNode(Node->getOpcode(), dl,
7471                          NewVT,
7472                          ScalarizeVectorOp(Node->getOperand(0)),
7473                          Node->getOperand(1));
7474     break;
7475   case ISD::LOAD: {
7476     LoadSDNode *LD = cast<LoadSDNode>(Node);
7477     SDValue Ch = LegalizeOp(LD->getChain());     // Legalize the chain.
7478     SDValue Ptr = LegalizeOp(LD->getBasePtr());  // Legalize the pointer.
7479     ISD::LoadExtType ExtType = LD->getExtensionType();
7480     const Value *SV = LD->getSrcValue();
7481     int SVOffset = LD->getSrcValueOffset();
7482     MVT MemoryVT = LD->getMemoryVT();
7483     unsigned Alignment = LD->getAlignment();
7484     bool isVolatile = LD->isVolatile();
7485
7486     assert(LD->isUnindexed() && "Indexed vector loads are not supported yet!");
7487     SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7488
7489     Result = DAG.getLoad(ISD::UNINDEXED, dl, ExtType,
7490                          NewVT, Ch, Ptr, Offset, SV, SVOffset,
7491                          MemoryVT.getVectorElementType(),
7492                          isVolatile, Alignment);
7493
7494     // Remember that we legalized the chain.
7495     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
7496     break;
7497   }
7498   case ISD::BUILD_VECTOR:
7499     Result = Node->getOperand(0);
7500     break;
7501   case ISD::INSERT_VECTOR_ELT:
7502     // Returning the inserted scalar element.
7503     Result = Node->getOperand(1);
7504     break;
7505   case ISD::CONCAT_VECTORS:
7506     assert(Node->getOperand(0).getValueType() == NewVT &&
7507            "Concat of non-legal vectors not yet supported!");
7508     Result = Node->getOperand(0);
7509     break;
7510   case ISD::VECTOR_SHUFFLE: {
7511     // Figure out if the scalar is the LHS or RHS and return it.
7512     SDValue EltNum = Node->getOperand(2).getOperand(0);
7513     if (cast<ConstantSDNode>(EltNum)->getZExtValue())
7514       Result = ScalarizeVectorOp(Node->getOperand(1));
7515     else
7516       Result = ScalarizeVectorOp(Node->getOperand(0));
7517     break;
7518   }
7519   case ISD::EXTRACT_SUBVECTOR:
7520     Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, NewVT,
7521                          Node->getOperand(0), Node->getOperand(1));
7522     break;
7523   case ISD::BIT_CONVERT: {
7524     SDValue Op0 = Op.getOperand(0);
7525     if (Op0.getValueType().isVector() &&
7526         Op0.getValueType().getVectorNumElements() == 1)
7527       Op0 = ScalarizeVectorOp(Op0);
7528     Result = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, Op0);
7529     break;
7530   }
7531   case ISD::SELECT:
7532     Result = DAG.getNode(ISD::SELECT, dl, NewVT, Op.getOperand(0),
7533                          ScalarizeVectorOp(Op.getOperand(1)),
7534                          ScalarizeVectorOp(Op.getOperand(2)));
7535     break;
7536   case ISD::SELECT_CC:
7537     Result = DAG.getNode(ISD::SELECT_CC, dl, NewVT, Node->getOperand(0),
7538                          Node->getOperand(1),
7539                          ScalarizeVectorOp(Op.getOperand(2)),
7540                          ScalarizeVectorOp(Op.getOperand(3)),
7541                          Node->getOperand(4));
7542     break;
7543   case ISD::VSETCC: {
7544     SDValue Op0 = ScalarizeVectorOp(Op.getOperand(0));
7545     SDValue Op1 = ScalarizeVectorOp(Op.getOperand(1));
7546     Result = DAG.getNode(ISD::SETCC, dl,
7547                          TLI.getSetCCResultType(Op0.getValueType()),
7548                          Op0, Op1, Op.getOperand(2));
7549     Result = DAG.getNode(ISD::SELECT, dl, NewVT, Result,
7550                          DAG.getConstant(-1ULL, NewVT),
7551                          DAG.getConstant(0ULL, NewVT));
7552     break;
7553   }
7554   }
7555
7556   if (TLI.isTypeLegal(NewVT))
7557     Result = LegalizeOp(Result);
7558   bool isNew = ScalarizedNodes.insert(std::make_pair(Op, Result)).second;
7559   assert(isNew && "Value already scalarized?");
7560   isNew = isNew;
7561   return Result;
7562 }
7563
7564
7565 SDValue SelectionDAGLegalize::WidenVectorOp(SDValue Op, MVT WidenVT) {
7566   assert(0 && "This should be dead!");
7567   std::map<SDValue, SDValue>::iterator I = WidenNodes.find(Op);
7568   if (I != WidenNodes.end()) return I->second;
7569
7570   MVT VT = Op.getValueType();
7571   assert(VT.isVector() && "Cannot widen non-vector type!");
7572
7573   SDValue Result;
7574   SDNode *Node = Op.getNode();
7575   DebugLoc dl = Node->getDebugLoc();
7576   MVT EVT = VT.getVectorElementType();
7577
7578   unsigned NumElts = VT.getVectorNumElements();
7579   unsigned NewNumElts = WidenVT.getVectorNumElements();
7580   assert(NewNumElts > NumElts  && "Cannot widen to smaller type!");
7581   assert(NewNumElts < 17);
7582
7583   // When widen is called, it is assumed that it is more efficient to use a
7584   // wide type.  The default action is to widen to operation to a wider legal
7585   // vector type and then do the operation if it is legal by calling LegalizeOp
7586   // again.  If there is no vector equivalent, we will unroll the operation, do
7587   // it, and rebuild the vector.  If most of the operations are vectorizible to
7588   // the legal type, the resulting code will be more efficient.  If this is not
7589   // the case, the resulting code will preform badly as we end up generating
7590   // code to pack/unpack the results. It is the function that calls widen
7591   // that is responsible for seeing this doesn't happen.
7592   switch (Node->getOpcode()) {
7593   default:
7594 #ifndef NDEBUG
7595       Node->dump(&DAG);
7596 #endif
7597       assert(0 && "Unexpected operation in WidenVectorOp!");
7598       break;
7599   case ISD::CopyFromReg:
7600     assert(0 && "CopyFromReg doesn't need widening!");
7601   case ISD::Constant:
7602   case ISD::ConstantFP:
7603     // To build a vector of these elements, clients should call BuildVector
7604     // and with each element instead of creating a node with a vector type
7605     assert(0 && "Unexpected operation in WidenVectorOp!");
7606   case ISD::VAARG:
7607     // Variable Arguments with vector types doesn't make any sense to me
7608     assert(0 && "Unexpected operation in WidenVectorOp!");
7609     break;
7610   case ISD::UNDEF:
7611     Result = DAG.getUNDEF(WidenVT);
7612     break;
7613   case ISD::BUILD_VECTOR: {
7614     // Build a vector with undefined for the new nodes
7615     SDValueVector NewOps(Node->op_begin(), Node->op_end());
7616     for (unsigned i = NumElts; i < NewNumElts; ++i) {
7617       NewOps.push_back(DAG.getUNDEF(EVT));
7618     }
7619     Result = DAG.getNode(ISD::BUILD_VECTOR, dl, WidenVT,
7620                          &NewOps[0], NewOps.size());
7621     break;
7622   }
7623   case ISD::INSERT_VECTOR_ELT: {
7624     SDValue Tmp1 = WidenVectorOp(Node->getOperand(0), WidenVT);
7625     Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, WidenVT, Tmp1,
7626                          Node->getOperand(1), Node->getOperand(2));
7627     break;
7628   }
7629   case ISD::VECTOR_SHUFFLE: {
7630     SDValue Tmp1 = WidenVectorOp(Node->getOperand(0), WidenVT);
7631     SDValue Tmp2 = WidenVectorOp(Node->getOperand(1), WidenVT);
7632     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Node);
7633     SmallVector<int, 8> NewMask;
7634     for (unsigned i = 0; i < NumElts; ++i) {
7635       int Idx = SVOp->getMaskElt(i);
7636       if (Idx < (int)NumElts)
7637         NewMask.push_back(Idx);
7638       else
7639         NewMask.push_back(Idx + NewNumElts - NumElts);
7640     }
7641     for (unsigned i = NumElts; i < NewNumElts; ++i)
7642       NewMask.push_back(-1);
7643     
7644     Result = DAG.getVectorShuffle(WidenVT, dl, Tmp1, Tmp2, &NewMask[0]);
7645     break;
7646   }
7647   case ISD::LOAD: {
7648     // If the load widen returns true, we can use a single load for the
7649     // vector.  Otherwise, it is returning a token factor for multiple
7650     // loads.
7651     SDValue TFOp;
7652     if (LoadWidenVectorOp(Result, TFOp, Op, WidenVT))
7653       AddLegalizedOperand(Op.getValue(1), LegalizeOp(TFOp.getValue(1)));
7654     else
7655       AddLegalizedOperand(Op.getValue(1), LegalizeOp(TFOp.getValue(0)));
7656     break;
7657   }
7658
7659   case ISD::BIT_CONVERT: {
7660     SDValue Tmp1 = Node->getOperand(0);
7661     // Converts between two different types so we need to determine
7662     // the correct widen type for the input operand.
7663     MVT InVT = Tmp1.getValueType();
7664     unsigned WidenSize = WidenVT.getSizeInBits();
7665     if (InVT.isVector()) {
7666       MVT InEltVT = InVT.getVectorElementType();
7667       unsigned InEltSize = InEltVT.getSizeInBits();
7668       assert(WidenSize % InEltSize == 0 &&
7669              "can not widen bit convert that are not multiple of element type");
7670       MVT NewInWidenVT = MVT::getVectorVT(InEltVT, WidenSize / InEltSize);
7671       Tmp1 = WidenVectorOp(Tmp1, NewInWidenVT);
7672       assert(Tmp1.getValueType().getSizeInBits() == WidenVT.getSizeInBits());
7673       Result = DAG.getNode(ISD::BIT_CONVERT, dl, WidenVT, Tmp1);
7674     } else {
7675       // If the result size is a multiple of the input size, widen the input
7676       // and then convert.
7677       unsigned InSize = InVT.getSizeInBits();
7678       assert(WidenSize % InSize == 0 &&
7679              "can not widen bit convert that are not multiple of element type");
7680       unsigned NewNumElts = WidenSize / InSize;
7681       SmallVector<SDValue, 16> Ops(NewNumElts);
7682       SDValue UndefVal = DAG.getUNDEF(InVT);
7683       Ops[0] = Tmp1;
7684       for (unsigned i = 1; i < NewNumElts; ++i)
7685         Ops[i] = UndefVal;
7686
7687       MVT NewInVT = MVT::getVectorVT(InVT, NewNumElts);
7688       Result = DAG.getNode(ISD::BUILD_VECTOR, dl, NewInVT, &Ops[0], NewNumElts);
7689       Result = DAG.getNode(ISD::BIT_CONVERT, dl, WidenVT, Result);
7690     }
7691     break;
7692   }
7693
7694   case ISD::SINT_TO_FP:
7695   case ISD::UINT_TO_FP:
7696   case ISD::FP_TO_SINT:
7697   case ISD::FP_TO_UINT:
7698   case ISD::FP_ROUND: {
7699     SDValue Tmp1 = Node->getOperand(0);
7700     // Converts between two different types so we need to determine
7701     // the correct widen type for the input operand.
7702     MVT TVT = Tmp1.getValueType();
7703     assert(TVT.isVector() && "can not widen non vector type");
7704     MVT TEVT = TVT.getVectorElementType();
7705     MVT TWidenVT =  MVT::getVectorVT(TEVT, NewNumElts);
7706     Tmp1 = WidenVectorOp(Tmp1, TWidenVT);
7707     assert(Tmp1.getValueType().getVectorNumElements() == NewNumElts);
7708     Result = DAG.getNode(Node->getOpcode(), dl, WidenVT, Tmp1);
7709     break;
7710   }
7711
7712   case ISD::FP_EXTEND:
7713     assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
7714   case ISD::TRUNCATE:
7715   case ISD::SIGN_EXTEND:
7716   case ISD::ZERO_EXTEND:
7717   case ISD::ANY_EXTEND:
7718   case ISD::SIGN_EXTEND_INREG:
7719   case ISD::FABS:
7720   case ISD::FNEG:
7721   case ISD::FSQRT:
7722   case ISD::FSIN:
7723   case ISD::FCOS:
7724   case ISD::CTPOP:
7725   case ISD::CTTZ:
7726   case ISD::CTLZ: {
7727     // Unary op widening
7728     SDValue Tmp1;
7729     Tmp1 = WidenVectorOp(Node->getOperand(0), WidenVT);
7730     assert(Tmp1.getValueType() == WidenVT);
7731     Result = DAG.getNode(Node->getOpcode(), dl, WidenVT, Tmp1);
7732     break;
7733   }
7734   case ISD::CONVERT_RNDSAT: {
7735     SDValue RndOp = Node->getOperand(3);
7736     SDValue SatOp = Node->getOperand(4);
7737     SDValue SrcOp = Node->getOperand(0);
7738
7739     // Converts between two different types so we need to determine
7740     // the correct widen type for the input operand.
7741     MVT SVT = SrcOp.getValueType();
7742     assert(SVT.isVector() && "can not widen non vector type");
7743     MVT SEVT = SVT.getVectorElementType();
7744     MVT SWidenVT =  MVT::getVectorVT(SEVT, NewNumElts);
7745
7746     SrcOp = WidenVectorOp(SrcOp, SWidenVT);
7747     assert(SrcOp.getValueType() == WidenVT);
7748     SDValue DTyOp = DAG.getValueType(WidenVT);
7749     SDValue STyOp = DAG.getValueType(SrcOp.getValueType());
7750     ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(Node)->getCvtCode();
7751
7752     Result = DAG.getConvertRndSat(WidenVT, dl, SrcOp, DTyOp, STyOp,
7753                                   RndOp, SatOp, CvtCode);
7754     break;
7755   }
7756   case ISD::FPOW:
7757   case ISD::FPOWI:
7758   case ISD::ADD:
7759   case ISD::SUB:
7760   case ISD::MUL:
7761   case ISD::MULHS:
7762   case ISD::MULHU:
7763   case ISD::AND:
7764   case ISD::OR:
7765   case ISD::XOR:
7766   case ISD::FADD:
7767   case ISD::FSUB:
7768   case ISD::FMUL:
7769   case ISD::SDIV:
7770   case ISD::SREM:
7771   case ISD::FDIV:
7772   case ISD::FREM:
7773   case ISD::FCOPYSIGN:
7774   case ISD::UDIV:
7775   case ISD::UREM:
7776   case ISD::BSWAP: {
7777     // Binary op widening
7778     SDValue Tmp1 = WidenVectorOp(Node->getOperand(0), WidenVT);
7779     SDValue Tmp2 = WidenVectorOp(Node->getOperand(1), WidenVT);
7780     assert(Tmp1.getValueType() == WidenVT && Tmp2.getValueType() == WidenVT);
7781     Result = DAG.getNode(Node->getOpcode(), dl, WidenVT, Tmp1, Tmp2);
7782     break;
7783   }
7784
7785   case ISD::SHL:
7786   case ISD::SRA:
7787   case ISD::SRL: {
7788     SDValue Tmp1 = WidenVectorOp(Node->getOperand(0), WidenVT);
7789     assert(Tmp1.getValueType() == WidenVT);
7790     SDValue ShOp = Node->getOperand(1);
7791     MVT ShVT = ShOp.getValueType();
7792     MVT NewShVT = MVT::getVectorVT(ShVT.getVectorElementType(),
7793                                    WidenVT.getVectorNumElements());
7794     ShOp = WidenVectorOp(ShOp, NewShVT);
7795     assert(ShOp.getValueType() == NewShVT);
7796     Result = DAG.getNode(Node->getOpcode(), dl, WidenVT, Tmp1, ShOp);
7797     break;
7798   }
7799
7800   case ISD::EXTRACT_VECTOR_ELT: {
7801     SDValue Tmp1 = WidenVectorOp(Node->getOperand(0), WidenVT);
7802     assert(Tmp1.getValueType() == WidenVT);
7803     Result = DAG.getNode(Node->getOpcode(), dl, EVT, Tmp1, Node->getOperand(1));
7804     break;
7805   }
7806   case ISD::CONCAT_VECTORS: {
7807     // We concurrently support only widen on a multiple of the incoming vector.
7808     // We could widen on a multiple of the incoming operand if necessary.
7809     unsigned NumConcat = NewNumElts / NumElts;
7810     assert(NewNumElts % NumElts == 0 && "Can widen only a multiple of vector");
7811     SDValue UndefVal = DAG.getUNDEF(VT);
7812     SmallVector<SDValue, 8> MOps;
7813     MOps.push_back(Op);
7814     for (unsigned i = 1; i != NumConcat; ++i) {
7815       MOps.push_back(UndefVal);
7816     }
7817     Result = LegalizeOp(DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT,
7818                                     &MOps[0], MOps.size()));
7819     break;
7820   }
7821   case ISD::EXTRACT_SUBVECTOR: {
7822     SDValue Tmp1 = Node->getOperand(0);
7823     SDValue Idx = Node->getOperand(1);
7824     ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx);
7825     if (CIdx && CIdx->getZExtValue() == 0) {
7826       // Since we are access the start of the vector, the incoming
7827       // vector type might be the proper.
7828       MVT Tmp1VT = Tmp1.getValueType();
7829       if (Tmp1VT == WidenVT)
7830         return Tmp1;
7831       else {
7832         unsigned Tmp1VTNumElts = Tmp1VT.getVectorNumElements();
7833         if (Tmp1VTNumElts < NewNumElts)
7834           Result = WidenVectorOp(Tmp1, WidenVT);
7835         else
7836           Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, WidenVT, Tmp1, Idx);
7837       }
7838     } else if (NewNumElts % NumElts == 0) {
7839       // Widen the extracted subvector.
7840       unsigned NumConcat = NewNumElts / NumElts;
7841       SDValue UndefVal = DAG.getUNDEF(VT);
7842       SmallVector<SDValue, 8> MOps;
7843       MOps.push_back(Op);
7844       for (unsigned i = 1; i != NumConcat; ++i) {
7845         MOps.push_back(UndefVal);
7846       }
7847       Result = LegalizeOp(DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT,
7848                                       &MOps[0], MOps.size()));
7849     } else {
7850       assert(0 && "can not widen extract subvector");
7851      // This could be implemented using insert and build vector but I would
7852      // like to see when this happens.
7853     }
7854     break;
7855   }
7856
7857   case ISD::SELECT: {
7858     // Determine new condition widen type and widen
7859     SDValue Cond1 = Node->getOperand(0);
7860     MVT CondVT = Cond1.getValueType();
7861     assert(CondVT.isVector() && "can not widen non vector type");
7862     MVT CondEVT = CondVT.getVectorElementType();
7863     MVT CondWidenVT =  MVT::getVectorVT(CondEVT, NewNumElts);
7864     Cond1 = WidenVectorOp(Cond1, CondWidenVT);
7865     assert(Cond1.getValueType() == CondWidenVT && "Condition not widen");
7866
7867     SDValue Tmp1 = WidenVectorOp(Node->getOperand(1), WidenVT);
7868     SDValue Tmp2 = WidenVectorOp(Node->getOperand(2), WidenVT);
7869     assert(Tmp1.getValueType() == WidenVT && Tmp2.getValueType() == WidenVT);
7870     Result = DAG.getNode(Node->getOpcode(), dl, WidenVT, Cond1, Tmp1, Tmp2);
7871     break;
7872   }
7873
7874   case ISD::SELECT_CC: {
7875     // Determine new condition widen type and widen
7876     SDValue Cond1 = Node->getOperand(0);
7877     SDValue Cond2 = Node->getOperand(1);
7878     MVT CondVT = Cond1.getValueType();
7879     assert(CondVT.isVector() && "can not widen non vector type");
7880     assert(CondVT == Cond2.getValueType() && "mismatch lhs/rhs");
7881     MVT CondEVT = CondVT.getVectorElementType();
7882     MVT CondWidenVT =  MVT::getVectorVT(CondEVT, NewNumElts);
7883     Cond1 = WidenVectorOp(Cond1, CondWidenVT);
7884     Cond2 = WidenVectorOp(Cond2, CondWidenVT);
7885     assert(Cond1.getValueType() == CondWidenVT &&
7886            Cond2.getValueType() == CondWidenVT && "condition not widen");
7887
7888     SDValue Tmp1 = WidenVectorOp(Node->getOperand(2), WidenVT);
7889     SDValue Tmp2 = WidenVectorOp(Node->getOperand(3), WidenVT);
7890     assert(Tmp1.getValueType() == WidenVT && Tmp2.getValueType() == WidenVT &&
7891            "operands not widen");
7892     Result = DAG.getNode(Node->getOpcode(), dl, WidenVT, Cond1, Cond2, Tmp1,
7893                          Tmp2, Node->getOperand(4));
7894     break;
7895   }
7896   case ISD::VSETCC: {
7897     // Determine widen for the operand
7898     SDValue Tmp1 = Node->getOperand(0);
7899     MVT TmpVT = Tmp1.getValueType();
7900     assert(TmpVT.isVector() && "can not widen non vector type");
7901     MVT TmpEVT = TmpVT.getVectorElementType();
7902     MVT TmpWidenVT =  MVT::getVectorVT(TmpEVT, NewNumElts);
7903     Tmp1 = WidenVectorOp(Tmp1, TmpWidenVT);
7904     SDValue Tmp2 = WidenVectorOp(Node->getOperand(1), TmpWidenVT);
7905     Result = DAG.getNode(Node->getOpcode(), dl, WidenVT, Tmp1, Tmp2,
7906                          Node->getOperand(2));
7907     break;
7908   }
7909   case ISD::ATOMIC_CMP_SWAP:
7910   case ISD::ATOMIC_LOAD_ADD:
7911   case ISD::ATOMIC_LOAD_SUB:
7912   case ISD::ATOMIC_LOAD_AND:
7913   case ISD::ATOMIC_LOAD_OR:
7914   case ISD::ATOMIC_LOAD_XOR:
7915   case ISD::ATOMIC_LOAD_NAND:
7916   case ISD::ATOMIC_LOAD_MIN:
7917   case ISD::ATOMIC_LOAD_MAX:
7918   case ISD::ATOMIC_LOAD_UMIN:
7919   case ISD::ATOMIC_LOAD_UMAX:
7920   case ISD::ATOMIC_SWAP: {
7921     // For now, we assume that using vectors for these operations don't make
7922     // much sense so we just split it.  We return an empty result
7923     SDValue X, Y;
7924     SplitVectorOp(Op, X, Y);
7925     return Result;
7926     break;
7927   }
7928
7929   } // end switch (Node->getOpcode())
7930
7931   assert(Result.getNode() && "Didn't set a result!");
7932   if (Result != Op)
7933     Result = LegalizeOp(Result);
7934
7935   AddWidenedOperand(Op, Result);
7936   return Result;
7937 }
7938
7939 // Utility function to find a legal vector type and its associated element
7940 // type from a preferred width and whose vector type must be the same size
7941 // as the VVT.
7942 //  TLI:   Target lowering used to determine legal types
7943 //  Width: Preferred width of element type
7944 //  VVT:   Vector value type whose size we must match.
7945 // Returns VecEVT and EVT - the vector type and its associated element type
7946 static void FindWidenVecType(const TargetLowering &TLI, unsigned Width, MVT VVT,
7947                              MVT& EVT, MVT& VecEVT) {
7948   // We start with the preferred width, make it a power of 2 and see if
7949   // we can find a vector type of that width. If not, we reduce it by
7950   // another power of 2.  If we have widen the type, a vector of bytes should
7951   // always be legal.
7952   assert(TLI.isTypeLegal(VVT));
7953   unsigned EWidth = Width + 1;
7954   do {
7955     assert(EWidth > 0);
7956     EWidth =  (1 << Log2_32(EWidth-1));
7957     EVT = MVT::getIntegerVT(EWidth);
7958     unsigned NumEVT = VVT.getSizeInBits()/EWidth;
7959     VecEVT = MVT::getVectorVT(EVT, NumEVT);
7960   } while (!TLI.isTypeLegal(VecEVT) ||
7961            VVT.getSizeInBits() != VecEVT.getSizeInBits());
7962 }
7963
7964 SDValue SelectionDAGLegalize::genWidenVectorLoads(SDValueVector& LdChain,
7965                                                     SDValue   Chain,
7966                                                     SDValue   BasePtr,
7967                                                     const Value *SV,
7968                                                     int         SVOffset,
7969                                                     unsigned    Alignment,
7970                                                     bool        isVolatile,
7971                                                     unsigned    LdWidth,
7972                                                     MVT         ResType,
7973                                                     DebugLoc    dl) {
7974   // We assume that we have good rules to handle loading power of two loads so
7975   // we break down the operations to power of 2 loads.  The strategy is to
7976   // load the largest power of 2 that we can easily transform to a legal vector
7977   // and then insert into that vector, and the cast the result into the legal
7978   // vector that we want.  This avoids unnecessary stack converts.
7979   // TODO: If the Ldwidth is legal, alignment is the same as the LdWidth, and
7980   //       the load is nonvolatile, we an use a wider load for the value.
7981   // Find a vector length we can load a large chunk
7982   MVT EVT, VecEVT;
7983   unsigned EVTWidth;
7984   FindWidenVecType(TLI, LdWidth, ResType, EVT, VecEVT);
7985   EVTWidth = EVT.getSizeInBits();
7986
7987   SDValue LdOp = DAG.getLoad(EVT, dl, Chain, BasePtr, SV, SVOffset,
7988                              isVolatile, Alignment);
7989   SDValue VecOp = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecEVT, LdOp);
7990   LdChain.push_back(LdOp.getValue(1));
7991
7992   // Check if we can load the element with one instruction
7993   if (LdWidth == EVTWidth) {
7994     return DAG.getNode(ISD::BIT_CONVERT, dl, ResType, VecOp);
7995   }
7996
7997   // The vector element order is endianness dependent.
7998   unsigned Idx = 1;
7999   LdWidth -= EVTWidth;
8000   unsigned Offset = 0;
8001
8002   while (LdWidth > 0) {
8003     unsigned Increment = EVTWidth / 8;
8004     Offset += Increment;
8005     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8006                           DAG.getIntPtrConstant(Increment));
8007
8008     if (LdWidth < EVTWidth) {
8009       // Our current type we are using is too large, use a smaller size by
8010       // using a smaller power of 2
8011       unsigned oEVTWidth = EVTWidth;
8012       FindWidenVecType(TLI, LdWidth, ResType, EVT, VecEVT);
8013       EVTWidth = EVT.getSizeInBits();
8014       // Readjust position and vector position based on new load type
8015       Idx = Idx * (oEVTWidth/EVTWidth);
8016       VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, VecEVT, VecOp);
8017     }
8018
8019     SDValue LdOp = DAG.getLoad(EVT, dl, Chain, BasePtr, SV,
8020                                SVOffset+Offset, isVolatile,
8021                                MinAlign(Alignment, Offset));
8022     LdChain.push_back(LdOp.getValue(1));
8023     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecEVT, VecOp, LdOp,
8024                         DAG.getIntPtrConstant(Idx++));
8025
8026     LdWidth -= EVTWidth;
8027   }
8028
8029   return DAG.getNode(ISD::BIT_CONVERT, dl, ResType, VecOp);
8030 }
8031
8032 bool SelectionDAGLegalize::LoadWidenVectorOp(SDValue& Result,
8033                                              SDValue& TFOp,
8034                                              SDValue Op,
8035                                              MVT NVT) {
8036   // TODO: Add support for ConcatVec and the ability to load many vector
8037   //       types (e.g., v4i8).  This will not work when a vector register
8038   //       to memory mapping is strange (e.g., vector elements are not
8039   //       stored in some sequential order).
8040
8041   // It must be true that the widen vector type is bigger than where
8042   // we need to load from.
8043   LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
8044   MVT LdVT = LD->getMemoryVT();
8045   DebugLoc dl = LD->getDebugLoc();
8046   assert(LdVT.isVector() && NVT.isVector());
8047   assert(LdVT.getVectorElementType() == NVT.getVectorElementType());
8048
8049   // Load information
8050   SDValue Chain = LD->getChain();
8051   SDValue BasePtr = LD->getBasePtr();
8052   int       SVOffset = LD->getSrcValueOffset();
8053   unsigned  Alignment = LD->getAlignment();
8054   bool      isVolatile = LD->isVolatile();
8055   const Value *SV = LD->getSrcValue();
8056   unsigned int LdWidth = LdVT.getSizeInBits();
8057
8058   // Load value as a large register
8059   SDValueVector LdChain;
8060   Result = genWidenVectorLoads(LdChain, Chain, BasePtr, SV, SVOffset,
8061                                Alignment, isVolatile, LdWidth, NVT, dl);
8062
8063   if (LdChain.size() == 1) {
8064     TFOp = LdChain[0];
8065     return true;
8066   }
8067   else {
8068     TFOp=DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8069                      &LdChain[0], LdChain.size());
8070     return false;
8071   }
8072 }
8073
8074
8075 void SelectionDAGLegalize::genWidenVectorStores(SDValueVector& StChain,
8076                                                 SDValue   Chain,
8077                                                 SDValue   BasePtr,
8078                                                 const Value *SV,
8079                                                 int         SVOffset,
8080                                                 unsigned    Alignment,
8081                                                 bool        isVolatile,
8082                                                 SDValue     ValOp,
8083                                                 unsigned    StWidth,
8084                                                 DebugLoc    dl) {
8085   // Breaks the stores into a series of power of 2 width stores.  For any
8086   // width, we convert the vector to the vector of element size that we
8087   // want to store.  This avoids requiring a stack convert.
8088
8089   // Find a width of the element type we can store with
8090   MVT VVT = ValOp.getValueType();
8091   MVT EVT, VecEVT;
8092   unsigned EVTWidth;
8093   FindWidenVecType(TLI, StWidth, VVT, EVT, VecEVT);
8094   EVTWidth = EVT.getSizeInBits();
8095
8096   SDValue VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, VecEVT, ValOp);
8097   SDValue EOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EVT, VecOp,
8098                             DAG.getIntPtrConstant(0));
8099   SDValue StOp = DAG.getStore(Chain, dl, EOp, BasePtr, SV, SVOffset,
8100                               isVolatile, Alignment);
8101   StChain.push_back(StOp);
8102
8103   // Check if we are done
8104   if (StWidth == EVTWidth) {
8105     return;
8106   }
8107
8108   unsigned Idx = 1;
8109   StWidth -= EVTWidth;
8110   unsigned Offset = 0;
8111
8112   while (StWidth > 0) {
8113     unsigned Increment = EVTWidth / 8;
8114     Offset += Increment;
8115     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8116                           DAG.getIntPtrConstant(Increment));
8117
8118     if (StWidth < EVTWidth) {
8119       // Our current type we are using is too large, use a smaller size by
8120       // using a smaller power of 2
8121       unsigned oEVTWidth = EVTWidth;
8122       FindWidenVecType(TLI, StWidth, VVT, EVT, VecEVT);
8123       EVTWidth = EVT.getSizeInBits();
8124       // Readjust position and vector position based on new load type
8125       Idx = Idx * (oEVTWidth/EVTWidth);
8126       VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, VecEVT, VecOp);
8127     }
8128
8129     EOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EVT, VecOp,
8130                       DAG.getIntPtrConstant(Idx++));
8131     StChain.push_back(DAG.getStore(Chain, dl, EOp, BasePtr, SV,
8132                                    SVOffset + Offset, isVolatile,
8133                                    MinAlign(Alignment, Offset)));
8134     StWidth -= EVTWidth;
8135   }
8136 }
8137
8138
8139 SDValue SelectionDAGLegalize::StoreWidenVectorOp(StoreSDNode *ST,
8140                                                  SDValue Chain,
8141                                                  SDValue BasePtr) {
8142   // TODO: It might be cleaner if we can use SplitVector and have more legal
8143   //        vector types that can be stored into memory (e.g., v4xi8 can
8144   //        be stored as a word). This will not work when a vector register
8145   //        to memory mapping is strange (e.g., vector elements are not
8146   //        stored in some sequential order).
8147
8148   MVT StVT = ST->getMemoryVT();
8149   SDValue ValOp = ST->getValue();
8150   DebugLoc dl = ST->getDebugLoc();
8151
8152   // Check if we have widen this node with another value
8153   std::map<SDValue, SDValue>::iterator I = WidenNodes.find(ValOp);
8154   if (I != WidenNodes.end())
8155     ValOp = I->second;
8156
8157   MVT VVT = ValOp.getValueType();
8158
8159   // It must be true that we the widen vector type is bigger than where
8160   // we need to store.
8161   assert(StVT.isVector() && VVT.isVector());
8162   assert(StVT.bitsLT(VVT));
8163   assert(StVT.getVectorElementType() == VVT.getVectorElementType());
8164
8165   // Store value
8166   SDValueVector StChain;
8167   genWidenVectorStores(StChain, Chain, BasePtr, ST->getSrcValue(),
8168                        ST->getSrcValueOffset(), ST->getAlignment(),
8169                        ST->isVolatile(), ValOp, StVT.getSizeInBits(), dl);
8170   if (StChain.size() == 1)
8171     return StChain[0];
8172   else
8173     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8174                        &StChain[0], StChain.size());
8175 }
8176
8177
8178 // SelectionDAG::Legalize - This is the entry point for the file.
8179 //
8180 void SelectionDAG::Legalize(bool TypesNeedLegalizing,
8181                             CodeGenOpt::Level OptLevel) {
8182   /// run - This is the main entry point to this class.
8183   ///
8184   SelectionDAGLegalize(*this, OptLevel).LegalizeDAG();
8185 }
8186