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