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