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