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