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