LegalizeDAG.cpp revision 80edfb3af5ed214c5cd7797b37cb3bb024e98cc6
1//===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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/Target/TargetLowering.h"
18#include "llvm/Target/TargetData.h"
19#include "llvm/Target/TargetOptions.h"
20#include "llvm/CallingConv.h"
21#include "llvm/Constants.h"
22#include "llvm/Support/MathExtras.h"
23#include "llvm/Support/CommandLine.h"
24#include <iostream>
25#include <map>
26using namespace llvm;
27
28#ifndef NDEBUG
29static cl::opt<bool>
30ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
31                 cl::desc("Pop up a window to show dags before legalize"));
32#else
33static const bool ViewLegalizeDAGs = 0;
34#endif
35
36//===----------------------------------------------------------------------===//
37/// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
38/// hacks on it until the target machine can handle it.  This involves
39/// eliminating value sizes the machine cannot handle (promoting small sizes to
40/// large sizes or splitting up large values into small values) as well as
41/// eliminating operations the machine cannot handle.
42///
43/// This code also does a small amount of optimization and recognition of idioms
44/// as part of its processing.  For example, if a target does not support a
45/// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
46/// will attempt merge setcc and brc instructions into brcc's.
47///
48namespace {
49class SelectionDAGLegalize {
50  TargetLowering &TLI;
51  SelectionDAG &DAG;
52
53  // Libcall insertion helpers.
54
55  /// LastCALLSEQ_END - This keeps track of the CALLSEQ_END node that has been
56  /// legalized.  We use this to ensure that calls are properly serialized
57  /// against each other, including inserted libcalls.
58  SDOperand LastCALLSEQ_END;
59
60  /// IsLegalizingCall - This member is used *only* for purposes of providing
61  /// helpful assertions that a libcall isn't created while another call is
62  /// being legalized (which could lead to non-serialized call sequences).
63  bool IsLegalizingCall;
64
65  enum LegalizeAction {
66    Legal,      // The target natively supports this operation.
67    Promote,    // This operation should be executed in a larger type.
68    Expand,     // Try to expand this to other ops, otherwise use a libcall.
69  };
70
71  /// ValueTypeActions - This is a bitvector that contains two bits for each
72  /// value type, where the two bits correspond to the LegalizeAction enum.
73  /// This can be queried with "getTypeAction(VT)".
74  TargetLowering::ValueTypeActionImpl ValueTypeActions;
75
76  /// LegalizedNodes - For nodes that are of legal width, and that have more
77  /// than one use, this map indicates what regularized operand to use.  This
78  /// allows us to avoid legalizing the same thing more than once.
79  std::map<SDOperand, SDOperand> LegalizedNodes;
80
81  /// PromotedNodes - For nodes that are below legal width, and that have more
82  /// than one use, this map indicates what promoted value to use.  This allows
83  /// us to avoid promoting the same thing more than once.
84  std::map<SDOperand, SDOperand> PromotedNodes;
85
86  /// ExpandedNodes - For nodes that need to be expanded this map indicates
87  /// which which operands are the expanded version of the input.  This allows
88  /// us to avoid expanding the same node more than once.
89  std::map<SDOperand, std::pair<SDOperand, SDOperand> > ExpandedNodes;
90
91  /// SplitNodes - For vector nodes that need to be split, this map indicates
92  /// which which operands are the split version of the input.  This allows us
93  /// to avoid splitting the same node more than once.
94  std::map<SDOperand, std::pair<SDOperand, SDOperand> > SplitNodes;
95
96  /// PackedNodes - For nodes that need to be packed from MVT::Vector types to
97  /// concrete packed types, this contains the mapping of ones we have already
98  /// processed to the result.
99  std::map<SDOperand, SDOperand> PackedNodes;
100
101  void AddLegalizedOperand(SDOperand From, SDOperand To) {
102    LegalizedNodes.insert(std::make_pair(From, To));
103    // If someone requests legalization of the new node, return itself.
104    if (From != To)
105      LegalizedNodes.insert(std::make_pair(To, To));
106  }
107  void AddPromotedOperand(SDOperand From, SDOperand To) {
108    bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
109    assert(isNew && "Got into the map somehow?");
110    // If someone requests legalization of the new node, return itself.
111    LegalizedNodes.insert(std::make_pair(To, To));
112  }
113
114public:
115
116  SelectionDAGLegalize(SelectionDAG &DAG);
117
118  /// getTypeAction - Return how we should legalize values of this type, either
119  /// it is already legal or we need to expand it into multiple registers of
120  /// smaller integer type, or we need to promote it to a larger type.
121  LegalizeAction getTypeAction(MVT::ValueType VT) const {
122    return (LegalizeAction)ValueTypeActions.getTypeAction(VT);
123  }
124
125  /// isTypeLegal - Return true if this type is legal on this target.
126  ///
127  bool isTypeLegal(MVT::ValueType VT) const {
128    return getTypeAction(VT) == Legal;
129  }
130
131  void LegalizeDAG();
132
133private:
134  /// HandleOp - Legalize, Promote, Expand or Pack the specified operand as
135  /// appropriate for its type.
136  void HandleOp(SDOperand Op);
137
138  /// LegalizeOp - We know that the specified value has a legal type.
139  /// Recursively ensure that the operands have legal types, then return the
140  /// result.
141  SDOperand LegalizeOp(SDOperand O);
142
143  /// PromoteOp - Given an operation that produces a value in an invalid type,
144  /// promote it to compute the value into a larger type.  The produced value
145  /// will have the correct bits for the low portion of the register, but no
146  /// guarantee is made about the top bits: it may be zero, sign-extended, or
147  /// garbage.
148  SDOperand PromoteOp(SDOperand O);
149
150  /// ExpandOp - Expand the specified SDOperand into its two component pieces
151  /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this,
152  /// the LegalizeNodes map is filled in for any results that are not expanded,
153  /// the ExpandedNodes map is filled in for any results that are expanded, and
154  /// the Lo/Hi values are returned.   This applies to integer types and Vector
155  /// types.
156  void ExpandOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
157
158  /// SplitVectorOp - Given an operand of MVT::Vector type, break it down into
159  /// two smaller values of MVT::Vector type.
160  void SplitVectorOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
161
162  /// PackVectorOp - Given an operand of MVT::Vector type, convert it into the
163  /// equivalent operation that returns a packed value (e.g. MVT::V4F32).  When
164  /// this is called, we know that PackedVT is the right type for the result and
165  /// we know that this type is legal for the target.
166  SDOperand PackVectorOp(SDOperand O, MVT::ValueType PackedVT);
167
168  /// isShuffleLegal - Return true if a vector shuffle is legal with the
169  /// specified mask and type.  Targets can specify exactly which masks they
170  /// support and the code generator is tasked with not creating illegal masks.
171  ///
172  /// Note that this will also return true for shuffles that are promoted to a
173  /// different type.
174  ///
175  /// If this is a legal shuffle, this method returns the (possibly promoted)
176  /// build_vector Mask.  If it's not a legal shuffle, it returns null.
177  SDNode *isShuffleLegal(MVT::ValueType VT, SDOperand Mask) const;
178
179  bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest);
180
181  void LegalizeSetCCOperands(SDOperand &LHS, SDOperand &RHS, SDOperand &CC);
182
183  SDOperand CreateStackTemporary(MVT::ValueType VT);
184
185  SDOperand ExpandLibCall(const char *Name, SDNode *Node,
186                          SDOperand &Hi);
187  SDOperand ExpandIntToFP(bool isSigned, MVT::ValueType DestTy,
188                          SDOperand Source);
189
190  SDOperand ExpandBIT_CONVERT(MVT::ValueType DestVT, SDOperand SrcOp);
191  SDOperand ExpandBUILD_VECTOR(SDNode *Node);
192  SDOperand ExpandSCALAR_TO_VECTOR(SDNode *Node);
193  SDOperand ExpandLegalINT_TO_FP(bool isSigned,
194                                 SDOperand LegalOp,
195                                 MVT::ValueType DestVT);
196  SDOperand PromoteLegalINT_TO_FP(SDOperand LegalOp, MVT::ValueType DestVT,
197                                  bool isSigned);
198  SDOperand PromoteLegalFP_TO_INT(SDOperand LegalOp, MVT::ValueType DestVT,
199                                  bool isSigned);
200
201  SDOperand ExpandBSWAP(SDOperand Op);
202  SDOperand ExpandBitCount(unsigned Opc, SDOperand Op);
203  bool ExpandShift(unsigned Opc, SDOperand Op, SDOperand Amt,
204                   SDOperand &Lo, SDOperand &Hi);
205  void ExpandShiftParts(unsigned NodeOp, SDOperand Op, SDOperand Amt,
206                        SDOperand &Lo, SDOperand &Hi);
207
208  SDOperand LowerVEXTRACT_VECTOR_ELT(SDOperand Op);
209  SDOperand ExpandEXTRACT_VECTOR_ELT(SDOperand Op);
210
211  SDOperand getIntPtrConstant(uint64_t Val) {
212    return DAG.getConstant(Val, TLI.getPointerTy());
213  }
214};
215}
216
217/// isVectorShuffleLegal - Return true if a vector shuffle is legal with the
218/// specified mask and type.  Targets can specify exactly which masks they
219/// support and the code generator is tasked with not creating illegal masks.
220///
221/// Note that this will also return true for shuffles that are promoted to a
222/// different type.
223SDNode *SelectionDAGLegalize::isShuffleLegal(MVT::ValueType VT,
224                                             SDOperand Mask) const {
225  switch (TLI.getOperationAction(ISD::VECTOR_SHUFFLE, VT)) {
226  default: return 0;
227  case TargetLowering::Legal:
228  case TargetLowering::Custom:
229    break;
230  case TargetLowering::Promote: {
231    // If this is promoted to a different type, convert the shuffle mask and
232    // ask if it is legal in the promoted type!
233    MVT::ValueType NVT = TLI.getTypeToPromoteTo(ISD::VECTOR_SHUFFLE, VT);
234
235    // If we changed # elements, change the shuffle mask.
236    unsigned NumEltsGrowth =
237      MVT::getVectorNumElements(NVT) / MVT::getVectorNumElements(VT);
238    assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
239    if (NumEltsGrowth > 1) {
240      // Renumber the elements.
241      std::vector<SDOperand> Ops;
242      for (unsigned i = 0, e = Mask.getNumOperands(); i != e; ++i) {
243        SDOperand InOp = Mask.getOperand(i);
244        for (unsigned j = 0; j != NumEltsGrowth; ++j) {
245          if (InOp.getOpcode() == ISD::UNDEF)
246            Ops.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
247          else {
248            unsigned InEltNo = cast<ConstantSDNode>(InOp)->getValue();
249            Ops.push_back(DAG.getConstant(InEltNo*NumEltsGrowth+j, MVT::i32));
250          }
251        }
252      }
253      Mask = DAG.getNode(ISD::BUILD_VECTOR, NVT, Ops);
254    }
255    VT = NVT;
256    break;
257  }
258  }
259  return TLI.isShuffleMaskLegal(Mask, VT) ? Mask.Val : 0;
260}
261
262/// getScalarizedOpcode - Return the scalar opcode that corresponds to the
263/// specified vector opcode.
264static unsigned getScalarizedOpcode(unsigned VecOp, MVT::ValueType VT) {
265  switch (VecOp) {
266  default: assert(0 && "Don't know how to scalarize this opcode!");
267  case ISD::VADD:  return MVT::isInteger(VT) ? ISD::ADD : ISD::FADD;
268  case ISD::VSUB:  return MVT::isInteger(VT) ? ISD::SUB : ISD::FSUB;
269  case ISD::VMUL:  return MVT::isInteger(VT) ? ISD::MUL : ISD::FMUL;
270  case ISD::VSDIV: return MVT::isInteger(VT) ? ISD::SDIV: ISD::FDIV;
271  case ISD::VUDIV: return MVT::isInteger(VT) ? ISD::UDIV: ISD::FDIV;
272  case ISD::VAND:  return MVT::isInteger(VT) ? ISD::AND : 0;
273  case ISD::VOR:   return MVT::isInteger(VT) ? ISD::OR  : 0;
274  case ISD::VXOR:  return MVT::isInteger(VT) ? ISD::XOR : 0;
275  }
276}
277
278SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag)
279  : TLI(dag.getTargetLoweringInfo()), DAG(dag),
280    ValueTypeActions(TLI.getValueTypeActions()) {
281  assert(MVT::LAST_VALUETYPE <= 32 &&
282         "Too many value types for ValueTypeActions to hold!");
283}
284
285/// ComputeTopDownOrdering - Add the specified node to the Order list if it has
286/// not been visited yet and if all of its operands have already been visited.
287static void ComputeTopDownOrdering(SDNode *N, std::vector<SDNode*> &Order,
288                                   std::map<SDNode*, unsigned> &Visited) {
289  if (++Visited[N] != N->getNumOperands())
290    return;  // Haven't visited all operands yet
291
292  Order.push_back(N);
293
294  if (N->hasOneUse()) { // Tail recurse in common case.
295    ComputeTopDownOrdering(*N->use_begin(), Order, Visited);
296    return;
297  }
298
299  // Now that we have N in, add anything that uses it if all of their operands
300  // are now done.
301  for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); UI != E;++UI)
302    ComputeTopDownOrdering(*UI, Order, Visited);
303}
304
305
306void SelectionDAGLegalize::LegalizeDAG() {
307  LastCALLSEQ_END = DAG.getEntryNode();
308  IsLegalizingCall = false;
309
310  // The legalize process is inherently a bottom-up recursive process (users
311  // legalize their uses before themselves).  Given infinite stack space, we
312  // could just start legalizing on the root and traverse the whole graph.  In
313  // practice however, this causes us to run out of stack space on large basic
314  // blocks.  To avoid this problem, compute an ordering of the nodes where each
315  // node is only legalized after all of its operands are legalized.
316  std::map<SDNode*, unsigned> Visited;
317  std::vector<SDNode*> Order;
318
319  // Compute ordering from all of the leaves in the graphs, those (like the
320  // entry node) that have no operands.
321  for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
322       E = DAG.allnodes_end(); I != E; ++I) {
323    if (I->getNumOperands() == 0) {
324      Visited[I] = 0 - 1U;
325      ComputeTopDownOrdering(I, Order, Visited);
326    }
327  }
328
329  assert(Order.size() == Visited.size() &&
330         Order.size() ==
331            (unsigned)std::distance(DAG.allnodes_begin(), DAG.allnodes_end()) &&
332         "Error: DAG is cyclic!");
333  Visited.clear();
334
335  for (unsigned i = 0, e = Order.size(); i != e; ++i)
336    HandleOp(SDOperand(Order[i], 0));
337
338  // Finally, it's possible the root changed.  Get the new root.
339  SDOperand OldRoot = DAG.getRoot();
340  assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
341  DAG.setRoot(LegalizedNodes[OldRoot]);
342
343  ExpandedNodes.clear();
344  LegalizedNodes.clear();
345  PromotedNodes.clear();
346  SplitNodes.clear();
347  PackedNodes.clear();
348
349  // Remove dead nodes now.
350  DAG.RemoveDeadNodes(OldRoot.Val);
351}
352
353
354/// FindCallEndFromCallStart - Given a chained node that is part of a call
355/// sequence, find the CALLSEQ_END node that terminates the call sequence.
356static SDNode *FindCallEndFromCallStart(SDNode *Node) {
357  if (Node->getOpcode() == ISD::CALLSEQ_END)
358    return Node;
359  if (Node->use_empty())
360    return 0;   // No CallSeqEnd
361
362  // The chain is usually at the end.
363  SDOperand TheChain(Node, Node->getNumValues()-1);
364  if (TheChain.getValueType() != MVT::Other) {
365    // Sometimes it's at the beginning.
366    TheChain = SDOperand(Node, 0);
367    if (TheChain.getValueType() != MVT::Other) {
368      // Otherwise, hunt for it.
369      for (unsigned i = 1, e = Node->getNumValues(); i != e; ++i)
370        if (Node->getValueType(i) == MVT::Other) {
371          TheChain = SDOperand(Node, i);
372          break;
373        }
374
375      // Otherwise, we walked into a node without a chain.
376      if (TheChain.getValueType() != MVT::Other)
377        return 0;
378    }
379  }
380
381  for (SDNode::use_iterator UI = Node->use_begin(),
382       E = Node->use_end(); UI != E; ++UI) {
383
384    // Make sure to only follow users of our token chain.
385    SDNode *User = *UI;
386    for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
387      if (User->getOperand(i) == TheChain)
388        if (SDNode *Result = FindCallEndFromCallStart(User))
389          return Result;
390  }
391  return 0;
392}
393
394/// FindCallStartFromCallEnd - Given a chained node that is part of a call
395/// sequence, find the CALLSEQ_START node that initiates the call sequence.
396static SDNode *FindCallStartFromCallEnd(SDNode *Node) {
397  assert(Node && "Didn't find callseq_start for a call??");
398  if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
399
400  assert(Node->getOperand(0).getValueType() == MVT::Other &&
401         "Node doesn't have a token chain argument!");
402  return FindCallStartFromCallEnd(Node->getOperand(0).Val);
403}
404
405/// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking to
406/// see if any uses can reach Dest.  If no dest operands can get to dest,
407/// legalize them, legalize ourself, and return false, otherwise, return true.
408bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N,
409                                                        SDNode *Dest) {
410  if (N == Dest) return true;  // N certainly leads to Dest :)
411
412  // If the first result of this node has been already legalized, then it cannot
413  // reach N.
414  switch (getTypeAction(N->getValueType(0))) {
415  case Legal:
416    if (LegalizedNodes.count(SDOperand(N, 0))) return false;
417    break;
418  case Promote:
419    if (PromotedNodes.count(SDOperand(N, 0))) return false;
420    break;
421  case Expand:
422    if (ExpandedNodes.count(SDOperand(N, 0))) return false;
423    break;
424  }
425
426  // Okay, this node has not already been legalized.  Check and legalize all
427  // operands.  If none lead to Dest, then we can legalize this node.
428  bool OperandsLeadToDest = false;
429  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
430    OperandsLeadToDest |=     // If an operand leads to Dest, so do we.
431      LegalizeAllNodesNotLeadingTo(N->getOperand(i).Val, Dest);
432
433  if (OperandsLeadToDest) return true;
434
435  // Okay, this node looks safe, legalize it and return false.
436  HandleOp(SDOperand(N, 0));
437  return false;
438}
439
440/// HandleOp - Legalize, Promote, Expand or Pack the specified operand as
441/// appropriate for its type.
442void SelectionDAGLegalize::HandleOp(SDOperand Op) {
443  switch (getTypeAction(Op.getValueType())) {
444  default: assert(0 && "Bad type action!");
445  case Legal:   LegalizeOp(Op); break;
446  case Promote: PromoteOp(Op);  break;
447  case Expand:
448    if (Op.getValueType() != MVT::Vector) {
449      SDOperand X, Y;
450      ExpandOp(Op, X, Y);
451    } else {
452      SDNode *N = Op.Val;
453      unsigned NumOps = N->getNumOperands();
454      unsigned NumElements =
455        cast<ConstantSDNode>(N->getOperand(NumOps-2))->getValue();
456      MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(NumOps-1))->getVT();
457      MVT::ValueType PackedVT = getVectorType(EVT, NumElements);
458      if (PackedVT != MVT::Other && TLI.isTypeLegal(PackedVT)) {
459        // In the common case, this is a legal vector type, convert it to the
460        // packed operation and type now.
461        PackVectorOp(Op, PackedVT);
462      } else if (NumElements == 1) {
463        // Otherwise, if this is a single element vector, convert it to a
464        // scalar operation.
465        PackVectorOp(Op, EVT);
466      } else {
467        // Otherwise, this is a multiple element vector that isn't supported.
468        // Split it in half and legalize both parts.
469        SDOperand X, Y;
470        SplitVectorOp(Op, X, Y);
471      }
472    }
473    break;
474  }
475}
476
477
478/// LegalizeOp - We know that the specified value has a legal type.
479/// Recursively ensure that the operands have legal types, then return the
480/// result.
481SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
482  assert(isTypeLegal(Op.getValueType()) &&
483         "Caller should expand or promote operands that are not legal!");
484  SDNode *Node = Op.Val;
485
486  // If this operation defines any values that cannot be represented in a
487  // register on this target, make sure to expand or promote them.
488  if (Node->getNumValues() > 1) {
489    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
490      if (getTypeAction(Node->getValueType(i)) != Legal) {
491        HandleOp(Op.getValue(i));
492        assert(LegalizedNodes.count(Op) &&
493               "Handling didn't add legal operands!");
494        return LegalizedNodes[Op];
495      }
496  }
497
498  // Note that LegalizeOp may be reentered even from single-use nodes, which
499  // means that we always must cache transformed nodes.
500  std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
501  if (I != LegalizedNodes.end()) return I->second;
502
503  SDOperand Tmp1, Tmp2, Tmp3, Tmp4;
504  SDOperand Result = Op;
505  bool isCustom = false;
506
507  switch (Node->getOpcode()) {
508  case ISD::FrameIndex:
509  case ISD::EntryToken:
510  case ISD::Register:
511  case ISD::BasicBlock:
512  case ISD::TargetFrameIndex:
513  case ISD::TargetConstant:
514  case ISD::TargetConstantFP:
515  case ISD::TargetConstantPool:
516  case ISD::TargetGlobalAddress:
517  case ISD::TargetExternalSymbol:
518  case ISD::VALUETYPE:
519  case ISD::SRCVALUE:
520  case ISD::STRING:
521  case ISD::CONDCODE:
522    // Primitives must all be legal.
523    assert(TLI.isOperationLegal(Node->getValueType(0), Node->getValueType(0)) &&
524           "This must be legal!");
525    break;
526  default:
527    if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
528      // If this is a target node, legalize it by legalizing the operands then
529      // passing it through.
530      std::vector<SDOperand> Ops;
531      bool Changed = false;
532      for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
533        Ops.push_back(LegalizeOp(Node->getOperand(i)));
534        Changed = Changed || Node->getOperand(i) != Ops.back();
535      }
536      if (Changed)
537        if (Node->getNumValues() == 1)
538          Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Ops);
539        else {
540          std::vector<MVT::ValueType> VTs(Node->value_begin(),
541                                          Node->value_end());
542          Result = DAG.getNode(Node->getOpcode(), VTs, Ops);
543        }
544
545      for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
546        AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
547      return Result.getValue(Op.ResNo);
548    }
549    // Otherwise this is an unhandled builtin node.  splat.
550    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
551    assert(0 && "Do not know how to legalize this operator!");
552    abort();
553  case ISD::GlobalAddress:
554  case ISD::ExternalSymbol:
555  case ISD::ConstantPool:           // Nothing to do.
556    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
557    default: assert(0 && "This action is not supported yet!");
558    case TargetLowering::Custom:
559      Tmp1 = TLI.LowerOperation(Op, DAG);
560      if (Tmp1.Val) Result = Tmp1;
561      // FALLTHROUGH if the target doesn't want to lower this op after all.
562    case TargetLowering::Legal:
563      break;
564    }
565    break;
566  case ISD::AssertSext:
567  case ISD::AssertZext:
568    Tmp1 = LegalizeOp(Node->getOperand(0));
569    Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
570    break;
571  case ISD::MERGE_VALUES:
572    // Legalize eliminates MERGE_VALUES nodes.
573    Result = Node->getOperand(Op.ResNo);
574    break;
575  case ISD::CopyFromReg:
576    Tmp1 = LegalizeOp(Node->getOperand(0));
577    Result = Op.getValue(0);
578    if (Node->getNumValues() == 2) {
579      Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
580    } else {
581      assert(Node->getNumValues() == 3 && "Invalid copyfromreg!");
582      if (Node->getNumOperands() == 3) {
583        Tmp2 = LegalizeOp(Node->getOperand(2));
584        Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
585      } else {
586        Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
587      }
588      AddLegalizedOperand(Op.getValue(2), Result.getValue(2));
589    }
590    // Since CopyFromReg produces two values, make sure to remember that we
591    // legalized both of them.
592    AddLegalizedOperand(Op.getValue(0), Result);
593    AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
594    return Result.getValue(Op.ResNo);
595  case ISD::UNDEF: {
596    MVT::ValueType VT = Op.getValueType();
597    switch (TLI.getOperationAction(ISD::UNDEF, VT)) {
598    default: assert(0 && "This action is not supported yet!");
599    case TargetLowering::Expand:
600      if (MVT::isInteger(VT))
601        Result = DAG.getConstant(0, VT);
602      else if (MVT::isFloatingPoint(VT))
603        Result = DAG.getConstantFP(0, VT);
604      else
605        assert(0 && "Unknown value type!");
606      break;
607    case TargetLowering::Legal:
608      break;
609    }
610    break;
611  }
612
613  case ISD::INTRINSIC_W_CHAIN:
614  case ISD::INTRINSIC_WO_CHAIN:
615  case ISD::INTRINSIC_VOID: {
616    std::vector<SDOperand> Ops;
617    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
618      Ops.push_back(LegalizeOp(Node->getOperand(i)));
619    Result = DAG.UpdateNodeOperands(Result, Ops);
620
621    // Allow the target to custom lower its intrinsics if it wants to.
622    if (TLI.getOperationAction(Node->getOpcode(), MVT::Other) ==
623        TargetLowering::Custom) {
624      Tmp3 = TLI.LowerOperation(Result, DAG);
625      if (Tmp3.Val) Result = Tmp3;
626    }
627
628    if (Result.Val->getNumValues() == 1) break;
629
630    // Must have return value and chain result.
631    assert(Result.Val->getNumValues() == 2 &&
632           "Cannot return more than two values!");
633
634    // Since loads produce two values, make sure to remember that we
635    // legalized both of them.
636    AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
637    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
638    return Result.getValue(Op.ResNo);
639  }
640
641  case ISD::LOCATION:
642    assert(Node->getNumOperands() == 5 && "Invalid LOCATION node!");
643    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the input chain.
644
645    switch (TLI.getOperationAction(ISD::LOCATION, MVT::Other)) {
646    case TargetLowering::Promote:
647    default: assert(0 && "This action is not supported yet!");
648    case TargetLowering::Expand: {
649      MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
650      bool useDEBUG_LOC = TLI.isOperationLegal(ISD::DEBUG_LOC, MVT::Other);
651      bool useDEBUG_LABEL = TLI.isOperationLegal(ISD::DEBUG_LABEL, MVT::Other);
652
653      if (DebugInfo && (useDEBUG_LOC || useDEBUG_LABEL)) {
654        const std::string &FName =
655          cast<StringSDNode>(Node->getOperand(3))->getValue();
656        const std::string &DirName =
657          cast<StringSDNode>(Node->getOperand(4))->getValue();
658        unsigned SrcFile = DebugInfo->RecordSource(DirName, FName);
659
660        std::vector<SDOperand> Ops;
661        Ops.push_back(Tmp1);  // chain
662        SDOperand LineOp = Node->getOperand(1);
663        SDOperand ColOp = Node->getOperand(2);
664
665        if (useDEBUG_LOC) {
666          Ops.push_back(LineOp);  // line #
667          Ops.push_back(ColOp);  // col #
668          Ops.push_back(DAG.getConstant(SrcFile, MVT::i32));  // source file id
669          Result = DAG.getNode(ISD::DEBUG_LOC, MVT::Other, Ops);
670        } else {
671          unsigned Line = cast<ConstantSDNode>(LineOp)->getValue();
672          unsigned Col = cast<ConstantSDNode>(ColOp)->getValue();
673          unsigned ID = DebugInfo->RecordLabel(Line, Col, SrcFile);
674          Ops.push_back(DAG.getConstant(ID, MVT::i32));
675          Result = DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops);
676        }
677      } else {
678        Result = Tmp1;  // chain
679      }
680      break;
681    }
682    case TargetLowering::Legal:
683      if (Tmp1 != Node->getOperand(0) ||
684          getTypeAction(Node->getOperand(1).getValueType()) == Promote) {
685        std::vector<SDOperand> Ops;
686        Ops.push_back(Tmp1);
687        if (getTypeAction(Node->getOperand(1).getValueType()) == Legal) {
688          Ops.push_back(Node->getOperand(1));  // line # must be legal.
689          Ops.push_back(Node->getOperand(2));  // col # must be legal.
690        } else {
691          // Otherwise promote them.
692          Ops.push_back(PromoteOp(Node->getOperand(1)));
693          Ops.push_back(PromoteOp(Node->getOperand(2)));
694        }
695        Ops.push_back(Node->getOperand(3));  // filename must be legal.
696        Ops.push_back(Node->getOperand(4));  // working dir # must be legal.
697        Result = DAG.UpdateNodeOperands(Result, Ops);
698      }
699      break;
700    }
701    break;
702
703  case ISD::DEBUG_LOC:
704    assert(Node->getNumOperands() == 4 && "Invalid DEBUG_LOC node!");
705    switch (TLI.getOperationAction(ISD::DEBUG_LOC, MVT::Other)) {
706    default: assert(0 && "This action is not supported yet!");
707    case TargetLowering::Legal:
708      Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
709      Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the line #.
710      Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the col #.
711      Tmp4 = LegalizeOp(Node->getOperand(3));  // Legalize the source file id.
712      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4);
713      break;
714    }
715    break;
716
717  case ISD::DEBUG_LABEL:
718    assert(Node->getNumOperands() == 2 && "Invalid DEBUG_LABEL node!");
719    switch (TLI.getOperationAction(ISD::DEBUG_LABEL, MVT::Other)) {
720    default: assert(0 && "This action is not supported yet!");
721    case TargetLowering::Legal:
722      Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
723      Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the label id.
724      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
725      break;
726    }
727    break;
728
729  case ISD::Constant:
730    // We know we don't need to expand constants here, constants only have one
731    // value and we check that it is fine above.
732
733    // FIXME: Maybe we should handle things like targets that don't support full
734    // 32-bit immediates?
735    break;
736  case ISD::ConstantFP: {
737    // Spill FP immediates to the constant pool if the target cannot directly
738    // codegen them.  Targets often have some immediate values that can be
739    // efficiently generated into an FP register without a load.  We explicitly
740    // leave these constants as ConstantFP nodes for the target to deal with.
741    ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
742
743    // Check to see if this FP immediate is already legal.
744    bool isLegal = false;
745    for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
746           E = TLI.legal_fpimm_end(); I != E; ++I)
747      if (CFP->isExactlyValue(*I)) {
748        isLegal = true;
749        break;
750      }
751
752    // If this is a legal constant, turn it into a TargetConstantFP node.
753    if (isLegal) {
754      Result = DAG.getTargetConstantFP(CFP->getValue(), CFP->getValueType(0));
755      break;
756    }
757
758    switch (TLI.getOperationAction(ISD::ConstantFP, CFP->getValueType(0))) {
759    default: assert(0 && "This action is not supported yet!");
760    case TargetLowering::Custom:
761      Tmp3 = TLI.LowerOperation(Result, DAG);
762      if (Tmp3.Val) {
763        Result = Tmp3;
764        break;
765      }
766      // FALLTHROUGH
767    case TargetLowering::Expand:
768      // Otherwise we need to spill the constant to memory.
769      bool Extend = false;
770
771      // If a FP immediate is precise when represented as a float and if the
772      // target can do an extending load from float to double, we put it into
773      // the constant pool as a float, even if it's is statically typed as a
774      // double.
775      MVT::ValueType VT = CFP->getValueType(0);
776      bool isDouble = VT == MVT::f64;
777      ConstantFP *LLVMC = ConstantFP::get(isDouble ? Type::DoubleTy :
778                                             Type::FloatTy, CFP->getValue());
779      if (isDouble && CFP->isExactlyValue((float)CFP->getValue()) &&
780          // Only do this if the target has a native EXTLOAD instruction from
781          // f32.
782          TLI.isOperationLegal(ISD::EXTLOAD, MVT::f32)) {
783        LLVMC = cast<ConstantFP>(ConstantExpr::getCast(LLVMC, Type::FloatTy));
784        VT = MVT::f32;
785        Extend = true;
786      }
787
788      SDOperand CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
789      if (Extend) {
790        Result = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
791                                CPIdx, DAG.getSrcValue(NULL), MVT::f32);
792      } else {
793        Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
794                             DAG.getSrcValue(NULL));
795      }
796    }
797    break;
798  }
799  case ISD::TokenFactor:
800    if (Node->getNumOperands() == 2) {
801      Tmp1 = LegalizeOp(Node->getOperand(0));
802      Tmp2 = LegalizeOp(Node->getOperand(1));
803      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
804    } else if (Node->getNumOperands() == 3) {
805      Tmp1 = LegalizeOp(Node->getOperand(0));
806      Tmp2 = LegalizeOp(Node->getOperand(1));
807      Tmp3 = LegalizeOp(Node->getOperand(2));
808      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
809    } else {
810      std::vector<SDOperand> Ops;
811      // Legalize the operands.
812      for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
813        Ops.push_back(LegalizeOp(Node->getOperand(i)));
814      Result = DAG.UpdateNodeOperands(Result, Ops);
815    }
816    break;
817
818  case ISD::FORMAL_ARGUMENTS:
819    // The only option for this is to custom lower it.
820    Result = TLI.LowerOperation(Result, DAG);
821    assert(Result.Val && "Target didn't custom lower ISD::FORMAL_ARGUMENTS!");
822    break;
823
824  case ISD::BUILD_VECTOR:
825    switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
826    default: assert(0 && "This action is not supported yet!");
827    case TargetLowering::Custom:
828      Tmp3 = TLI.LowerOperation(Result, DAG);
829      if (Tmp3.Val) {
830        Result = Tmp3;
831        break;
832      }
833      // FALLTHROUGH
834    case TargetLowering::Expand:
835      Result = ExpandBUILD_VECTOR(Result.Val);
836      break;
837    }
838    break;
839  case ISD::INSERT_VECTOR_ELT:
840    Tmp1 = LegalizeOp(Node->getOperand(0));  // InVec
841    Tmp2 = LegalizeOp(Node->getOperand(1));  // InVal
842    Tmp3 = LegalizeOp(Node->getOperand(2));  // InEltNo
843    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
844
845    switch (TLI.getOperationAction(ISD::INSERT_VECTOR_ELT,
846                                   Node->getValueType(0))) {
847    default: assert(0 && "This action is not supported yet!");
848    case TargetLowering::Legal:
849      break;
850    case TargetLowering::Custom:
851      Tmp3 = TLI.LowerOperation(Result, DAG);
852      if (Tmp3.Val) {
853        Result = Tmp3;
854        break;
855      }
856      // FALLTHROUGH
857    case TargetLowering::Expand: {
858      // If the insert index is a constant, codegen this as a scalar_to_vector,
859      // then a shuffle that inserts it into the right position in the vector.
860      if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Tmp3)) {
861        SDOperand ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR,
862                                      Tmp1.getValueType(), Tmp2);
863
864        unsigned NumElts = MVT::getVectorNumElements(Tmp1.getValueType());
865        MVT::ValueType ShufMaskVT = MVT::getIntVectorWithNumElements(NumElts);
866        MVT::ValueType ShufMaskEltVT = MVT::getVectorBaseType(ShufMaskVT);
867
868        // We generate a shuffle of InVec and ScVec, so the shuffle mask should
869        // be 0,1,2,3,4,5... with the appropriate element replaced with elt 0 of
870        // the RHS.
871        std::vector<SDOperand> ShufOps;
872        for (unsigned i = 0; i != NumElts; ++i) {
873          if (i != InsertPos->getValue())
874            ShufOps.push_back(DAG.getConstant(i, ShufMaskEltVT));
875          else
876            ShufOps.push_back(DAG.getConstant(NumElts, ShufMaskEltVT));
877        }
878        SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMaskVT,ShufOps);
879
880        Result = DAG.getNode(ISD::VECTOR_SHUFFLE, Tmp1.getValueType(),
881                             Tmp1, ScVec, ShufMask);
882        Result = LegalizeOp(Result);
883        break;
884      }
885
886      // If the target doesn't support this, we have to spill the input vector
887      // to a temporary stack slot, update the element, then reload it.  This is
888      // badness.  We could also load the value into a vector register (either
889      // with a "move to register" or "extload into register" instruction, then
890      // permute it into place, if the idx is a constant and if the idx is
891      // supported by the target.
892      MVT::ValueType VT    = Tmp1.getValueType();
893      MVT::ValueType EltVT = Tmp2.getValueType();
894      MVT::ValueType IdxVT = Tmp3.getValueType();
895      MVT::ValueType PtrVT = TLI.getPointerTy();
896      SDOperand StackPtr = CreateStackTemporary(VT);
897      // Store the vector.
898      SDOperand Ch = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
899                                 Tmp1, StackPtr, DAG.getSrcValue(NULL));
900
901      // Truncate or zero extend offset to target pointer type.
902      unsigned CastOpc = (IdxVT > PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
903      Tmp3 = DAG.getNode(CastOpc, PtrVT, Tmp3);
904      // Add the offset to the index.
905      unsigned EltSize = MVT::getSizeInBits(EltVT)/8;
906      Tmp3 = DAG.getNode(ISD::MUL, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
907      SDOperand StackPtr2 = DAG.getNode(ISD::ADD, IdxVT, Tmp3, StackPtr);
908      // Store the scalar value.
909      Ch = DAG.getNode(ISD::STORE, MVT::Other, Ch,
910                       Tmp2, StackPtr2, DAG.getSrcValue(NULL));
911      // Load the updated vector.
912      Result = DAG.getLoad(VT, Ch, StackPtr, DAG.getSrcValue(NULL));
913      break;
914    }
915    }
916    break;
917  case ISD::SCALAR_TO_VECTOR:
918    if (!TLI.isTypeLegal(Node->getOperand(0).getValueType())) {
919      Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
920      break;
921    }
922
923    Tmp1 = LegalizeOp(Node->getOperand(0));  // InVal
924    Result = DAG.UpdateNodeOperands(Result, Tmp1);
925    switch (TLI.getOperationAction(ISD::SCALAR_TO_VECTOR,
926                                   Node->getValueType(0))) {
927    default: assert(0 && "This action is not supported yet!");
928    case TargetLowering::Legal:
929      break;
930    case TargetLowering::Custom:
931      Tmp3 = TLI.LowerOperation(Result, DAG);
932      if (Tmp3.Val) {
933        Result = Tmp3;
934        break;
935      }
936      // FALLTHROUGH
937    case TargetLowering::Expand:
938      Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
939      break;
940    }
941    break;
942  case ISD::VECTOR_SHUFFLE:
943    Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the input vectors,
944    Tmp2 = LegalizeOp(Node->getOperand(1));   // but not the shuffle mask.
945    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
946
947    // Allow targets to custom lower the SHUFFLEs they support.
948    switch (TLI.getOperationAction(ISD::VECTOR_SHUFFLE,Result.getValueType())) {
949    default: assert(0 && "Unknown operation action!");
950    case TargetLowering::Legal:
951      assert(isShuffleLegal(Result.getValueType(), Node->getOperand(2)) &&
952             "vector shuffle should not be created if not legal!");
953      break;
954    case TargetLowering::Custom:
955      Tmp3 = TLI.LowerOperation(Result, DAG);
956      if (Tmp3.Val) {
957        Result = Tmp3;
958        break;
959      }
960      // FALLTHROUGH
961    case TargetLowering::Expand: {
962      MVT::ValueType VT = Node->getValueType(0);
963      MVT::ValueType EltVT = MVT::getVectorBaseType(VT);
964      MVT::ValueType PtrVT = TLI.getPointerTy();
965      SDOperand Mask = Node->getOperand(2);
966      unsigned NumElems = Mask.getNumOperands();
967      std::vector<SDOperand> Ops;
968      for (unsigned i = 0; i != NumElems; ++i) {
969        SDOperand Arg = Mask.getOperand(i);
970        if (Arg.getOpcode() == ISD::UNDEF) {
971          Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
972        } else {
973          assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
974          unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
975          if (Idx < NumElems)
976            Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp1,
977                                      DAG.getConstant(Idx, PtrVT)));
978          else
979            Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp2,
980                                      DAG.getConstant(Idx - NumElems, PtrVT)));
981        }
982      }
983      Result = DAG.getNode(ISD::BUILD_VECTOR, VT, Ops);
984      break;
985    }
986    case TargetLowering::Promote: {
987      // Change base type to a different vector type.
988      MVT::ValueType OVT = Node->getValueType(0);
989      MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
990
991      // Cast the two input vectors.
992      Tmp1 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp1);
993      Tmp2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp2);
994
995      // Convert the shuffle mask to the right # elements.
996      Tmp3 = SDOperand(isShuffleLegal(OVT, Node->getOperand(2)), 0);
997      assert(Tmp3.Val && "Shuffle not legal?");
998      Result = DAG.getNode(ISD::VECTOR_SHUFFLE, NVT, Tmp1, Tmp2, Tmp3);
999      Result = DAG.getNode(ISD::BIT_CONVERT, OVT, Result);
1000      break;
1001    }
1002    }
1003    break;
1004
1005  case ISD::EXTRACT_VECTOR_ELT:
1006    Tmp1 = LegalizeOp(Node->getOperand(0));
1007    Tmp2 = LegalizeOp(Node->getOperand(1));
1008    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1009
1010    switch (TLI.getOperationAction(ISD::EXTRACT_VECTOR_ELT,
1011                                   Tmp1.getValueType())) {
1012    default: assert(0 && "This action is not supported yet!");
1013    case TargetLowering::Legal:
1014      break;
1015    case TargetLowering::Custom:
1016      Tmp3 = TLI.LowerOperation(Result, DAG);
1017      if (Tmp3.Val) {
1018        Result = Tmp3;
1019        break;
1020      }
1021      // FALLTHROUGH
1022    case TargetLowering::Expand:
1023      Result = ExpandEXTRACT_VECTOR_ELT(Result);
1024      break;
1025    }
1026    break;
1027
1028  case ISD::VEXTRACT_VECTOR_ELT:
1029    Result = LegalizeOp(LowerVEXTRACT_VECTOR_ELT(Op));
1030    break;
1031
1032  case ISD::CALLSEQ_START: {
1033    SDNode *CallEnd = FindCallEndFromCallStart(Node);
1034
1035    // Recursively Legalize all of the inputs of the call end that do not lead
1036    // to this call start.  This ensures that any libcalls that need be inserted
1037    // are inserted *before* the CALLSEQ_START.
1038    for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
1039      LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).Val, Node);
1040
1041    // Now that we legalized all of the inputs (which may have inserted
1042    // libcalls) create the new CALLSEQ_START node.
1043    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1044
1045    // Merge in the last call, to ensure that this call start after the last
1046    // call ended.
1047    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1048    Tmp1 = LegalizeOp(Tmp1);
1049
1050    // Do not try to legalize the target-specific arguments (#1+).
1051    if (Tmp1 != Node->getOperand(0)) {
1052      std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
1053      Ops[0] = Tmp1;
1054      Result = DAG.UpdateNodeOperands(Result, Ops);
1055    }
1056
1057    // Remember that the CALLSEQ_START is legalized.
1058    AddLegalizedOperand(Op.getValue(0), Result);
1059    if (Node->getNumValues() == 2)    // If this has a flag result, remember it.
1060      AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1061
1062    // Now that the callseq_start and all of the non-call nodes above this call
1063    // sequence have been legalized, legalize the call itself.  During this
1064    // process, no libcalls can/will be inserted, guaranteeing that no calls
1065    // can overlap.
1066    assert(!IsLegalizingCall && "Inconsistent sequentialization of calls!");
1067    SDOperand InCallSEQ = LastCALLSEQ_END;
1068    // Note that we are selecting this call!
1069    LastCALLSEQ_END = SDOperand(CallEnd, 0);
1070    IsLegalizingCall = true;
1071
1072    // Legalize the call, starting from the CALLSEQ_END.
1073    LegalizeOp(LastCALLSEQ_END);
1074    assert(!IsLegalizingCall && "CALLSEQ_END should have cleared this!");
1075    return Result;
1076  }
1077  case ISD::CALLSEQ_END:
1078    // If the CALLSEQ_START node hasn't been legalized first, legalize it.  This
1079    // will cause this node to be legalized as well as handling libcalls right.
1080    if (LastCALLSEQ_END.Val != Node) {
1081      LegalizeOp(SDOperand(FindCallStartFromCallEnd(Node), 0));
1082      std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
1083      assert(I != LegalizedNodes.end() &&
1084             "Legalizing the call start should have legalized this node!");
1085      return I->second;
1086    }
1087
1088    // Otherwise, the call start has been legalized and everything is going
1089    // according to plan.  Just legalize ourselves normally here.
1090    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1091    // Do not try to legalize the target-specific arguments (#1+), except for
1092    // an optional flag input.
1093    if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Flag){
1094      if (Tmp1 != Node->getOperand(0)) {
1095        std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
1096        Ops[0] = Tmp1;
1097        Result = DAG.UpdateNodeOperands(Result, Ops);
1098      }
1099    } else {
1100      Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
1101      if (Tmp1 != Node->getOperand(0) ||
1102          Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
1103        std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
1104        Ops[0] = Tmp1;
1105        Ops.back() = Tmp2;
1106        Result = DAG.UpdateNodeOperands(Result, Ops);
1107      }
1108    }
1109    assert(IsLegalizingCall && "Call sequence imbalance between start/end?");
1110    // This finishes up call legalization.
1111    IsLegalizingCall = false;
1112
1113    // If the CALLSEQ_END node has a flag, remember that we legalized it.
1114    AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1115    if (Node->getNumValues() == 2)
1116      AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1117    return Result.getValue(Op.ResNo);
1118  case ISD::DYNAMIC_STACKALLOC: {
1119    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1120    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
1121    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
1122    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1123
1124    Tmp1 = Result.getValue(0);
1125    Tmp2 = Result.getValue(1);
1126    switch (TLI.getOperationAction(Node->getOpcode(),
1127                                   Node->getValueType(0))) {
1128    default: assert(0 && "This action is not supported yet!");
1129    case TargetLowering::Expand: {
1130      unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1131      assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1132             " not tell us which reg is the stack pointer!");
1133      SDOperand Chain = Tmp1.getOperand(0);
1134      SDOperand Size  = Tmp2.getOperand(1);
1135      SDOperand SP = DAG.getCopyFromReg(Chain, SPReg, Node->getValueType(0));
1136      Tmp1 = DAG.getNode(ISD::SUB, Node->getValueType(0), SP, Size);    // Value
1137      Tmp2 = DAG.getCopyToReg(SP.getValue(1), SPReg, Tmp1);      // Output chain
1138      Tmp1 = LegalizeOp(Tmp1);
1139      Tmp2 = LegalizeOp(Tmp2);
1140      break;
1141    }
1142    case TargetLowering::Custom:
1143      Tmp3 = TLI.LowerOperation(Tmp1, DAG);
1144      if (Tmp3.Val) {
1145        Tmp1 = LegalizeOp(Tmp3);
1146        Tmp2 = LegalizeOp(Tmp3.getValue(1));
1147      }
1148      break;
1149    case TargetLowering::Legal:
1150      break;
1151    }
1152    // Since this op produce two values, make sure to remember that we
1153    // legalized both of them.
1154    AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1155    AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1156    return Op.ResNo ? Tmp2 : Tmp1;
1157  }
1158  case ISD::INLINEASM:
1159    Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize Chain.
1160    Tmp2 = Node->getOperand(Node->getNumOperands()-1);
1161    if (Tmp2.getValueType() == MVT::Flag)     // Legalize Flag if it exists.
1162      Tmp2 = Tmp3 = SDOperand(0, 0);
1163    else
1164      Tmp3 = LegalizeOp(Tmp2);
1165
1166    if (Tmp1 != Node->getOperand(0) || Tmp2 != Tmp3) {
1167      std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
1168      Ops[0] = Tmp1;
1169      if (Tmp3.Val) Ops.back() = Tmp3;
1170      Result = DAG.UpdateNodeOperands(Result, Ops);
1171    }
1172
1173    // INLINE asm returns a chain and flag, make sure to add both to the map.
1174    AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1175    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1176    return Result.getValue(Op.ResNo);
1177  case ISD::BR:
1178    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1179    // Ensure that libcalls are emitted before a branch.
1180    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1181    Tmp1 = LegalizeOp(Tmp1);
1182    LastCALLSEQ_END = DAG.getEntryNode();
1183
1184    Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1185    break;
1186
1187  case ISD::BRCOND:
1188    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1189    // Ensure that libcalls are emitted before a return.
1190    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1191    Tmp1 = LegalizeOp(Tmp1);
1192    LastCALLSEQ_END = DAG.getEntryNode();
1193
1194    switch (getTypeAction(Node->getOperand(1).getValueType())) {
1195    case Expand: assert(0 && "It's impossible to expand bools");
1196    case Legal:
1197      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
1198      break;
1199    case Promote:
1200      Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
1201      break;
1202    }
1203
1204    // Basic block destination (Op#2) is always legal.
1205    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1206
1207    switch (TLI.getOperationAction(ISD::BRCOND, MVT::Other)) {
1208    default: assert(0 && "This action is not supported yet!");
1209    case TargetLowering::Legal: break;
1210    case TargetLowering::Custom:
1211      Tmp1 = TLI.LowerOperation(Result, DAG);
1212      if (Tmp1.Val) Result = Tmp1;
1213      break;
1214    case TargetLowering::Expand:
1215      // Expand brcond's setcc into its constituent parts and create a BR_CC
1216      // Node.
1217      if (Tmp2.getOpcode() == ISD::SETCC) {
1218        Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Tmp2.getOperand(2),
1219                             Tmp2.getOperand(0), Tmp2.getOperand(1),
1220                             Node->getOperand(2));
1221      } else {
1222        // Make sure the condition is either zero or one.  It may have been
1223        // promoted from something else.
1224        unsigned NumBits = MVT::getSizeInBits(Tmp2.getValueType());
1225        if (!TLI.MaskedValueIsZero(Tmp2, (~0ULL >> (64-NumBits))^1))
1226          Tmp2 = DAG.getZeroExtendInReg(Tmp2, MVT::i1);
1227
1228        Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1,
1229                             DAG.getCondCode(ISD::SETNE), Tmp2,
1230                             DAG.getConstant(0, Tmp2.getValueType()),
1231                             Node->getOperand(2));
1232      }
1233      break;
1234    }
1235    break;
1236  case ISD::BR_CC:
1237    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1238    // Ensure that libcalls are emitted before a branch.
1239    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1240    Tmp1 = LegalizeOp(Tmp1);
1241    LastCALLSEQ_END = DAG.getEntryNode();
1242
1243    Tmp2 = Node->getOperand(2);              // LHS
1244    Tmp3 = Node->getOperand(3);              // RHS
1245    Tmp4 = Node->getOperand(1);              // CC
1246
1247    LegalizeSetCCOperands(Tmp2, Tmp3, Tmp4);
1248
1249    // If we didn't get both a LHS and RHS back from LegalizeSetCCOperands,
1250    // the LHS is a legal SETCC itself.  In this case, we need to compare
1251    // the result against zero to select between true and false values.
1252    if (Tmp3.Val == 0) {
1253      Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
1254      Tmp4 = DAG.getCondCode(ISD::SETNE);
1255    }
1256
1257    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp4, Tmp2, Tmp3,
1258                                    Node->getOperand(4));
1259
1260    switch (TLI.getOperationAction(ISD::BR_CC, Tmp3.getValueType())) {
1261    default: assert(0 && "Unexpected action for BR_CC!");
1262    case TargetLowering::Legal: break;
1263    case TargetLowering::Custom:
1264      Tmp4 = TLI.LowerOperation(Result, DAG);
1265      if (Tmp4.Val) Result = Tmp4;
1266      break;
1267    }
1268    break;
1269  case ISD::LOAD: {
1270    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1271    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1272
1273    MVT::ValueType VT = Node->getValueType(0);
1274    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1275    Tmp3 = Result.getValue(0);
1276    Tmp4 = Result.getValue(1);
1277
1278    switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1279    default: assert(0 && "This action is not supported yet!");
1280    case TargetLowering::Legal: break;
1281    case TargetLowering::Custom:
1282      Tmp1 = TLI.LowerOperation(Tmp3, DAG);
1283      if (Tmp1.Val) {
1284        Tmp3 = LegalizeOp(Tmp1);
1285        Tmp4 = LegalizeOp(Tmp1.getValue(1));
1286      }
1287      break;
1288    case TargetLowering::Promote: {
1289      // Only promote a load of vector type to another.
1290      assert(MVT::isVector(VT) && "Cannot promote this load!");
1291      // Change base type to a different vector type.
1292      MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
1293
1294      Tmp1 = DAG.getLoad(NVT, Tmp1, Tmp2, Node->getOperand(2));
1295      Tmp3 = LegalizeOp(DAG.getNode(ISD::BIT_CONVERT, VT, Tmp1));
1296      Tmp4 = LegalizeOp(Tmp1.getValue(1));
1297      break;
1298    }
1299    }
1300    // Since loads produce two values, make sure to remember that we
1301    // legalized both of them.
1302    AddLegalizedOperand(SDOperand(Node, 0), Tmp3);
1303    AddLegalizedOperand(SDOperand(Node, 1), Tmp4);
1304    return Op.ResNo ? Tmp4 : Tmp3;
1305  }
1306  case ISD::EXTLOAD:
1307  case ISD::SEXTLOAD:
1308  case ISD::ZEXTLOAD: {
1309    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1310    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1311
1312    MVT::ValueType SrcVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
1313    switch (TLI.getOperationAction(Node->getOpcode(), SrcVT)) {
1314    default: assert(0 && "This action is not supported yet!");
1315    case TargetLowering::Promote:
1316      assert(SrcVT == MVT::i1 && "Can only promote EXTLOAD from i1 -> i8!");
1317      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2),
1318                                      DAG.getValueType(MVT::i8));
1319      Tmp1 = Result.getValue(0);
1320      Tmp2 = Result.getValue(1);
1321      break;
1322    case TargetLowering::Custom:
1323      isCustom = true;
1324      // FALLTHROUGH
1325    case TargetLowering::Legal:
1326      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2),
1327                                      Node->getOperand(3));
1328      Tmp1 = Result.getValue(0);
1329      Tmp2 = Result.getValue(1);
1330
1331      if (isCustom) {
1332        Tmp3 = TLI.LowerOperation(Tmp3, DAG);
1333        if (Tmp3.Val) {
1334          Tmp1 = LegalizeOp(Tmp3);
1335          Tmp2 = LegalizeOp(Tmp3.getValue(1));
1336        }
1337      }
1338      break;
1339    case TargetLowering::Expand:
1340      // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
1341      if (SrcVT == MVT::f32 && Node->getValueType(0) == MVT::f64) {
1342        SDOperand Load = DAG.getLoad(SrcVT, Tmp1, Tmp2, Node->getOperand(2));
1343        Result = DAG.getNode(ISD::FP_EXTEND, Node->getValueType(0), Load);
1344        Tmp1 = LegalizeOp(Result);  // Relegalize new nodes.
1345        Tmp2 = LegalizeOp(Load.getValue(1));
1346        break;
1347      }
1348      assert(Node->getOpcode() != ISD::EXTLOAD &&
1349             "EXTLOAD should always be supported!");
1350      // Turn the unsupported load into an EXTLOAD followed by an explicit
1351      // zero/sign extend inreg.
1352      Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
1353                              Tmp1, Tmp2, Node->getOperand(2), SrcVT);
1354      SDOperand ValRes;
1355      if (Node->getOpcode() == ISD::SEXTLOAD)
1356        ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1357                             Result, DAG.getValueType(SrcVT));
1358      else
1359        ValRes = DAG.getZeroExtendInReg(Result, SrcVT);
1360      Tmp1 = LegalizeOp(ValRes);  // Relegalize new nodes.
1361      Tmp2 = LegalizeOp(Result.getValue(1));  // Relegalize new nodes.
1362      break;
1363    }
1364    // Since loads produce two values, make sure to remember that we legalized
1365    // both of them.
1366    AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1367    AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1368    return Op.ResNo ? Tmp2 : Tmp1;
1369  }
1370  case ISD::EXTRACT_ELEMENT: {
1371    MVT::ValueType OpTy = Node->getOperand(0).getValueType();
1372    switch (getTypeAction(OpTy)) {
1373    default: assert(0 && "EXTRACT_ELEMENT action for type unimplemented!");
1374    case Legal:
1375      if (cast<ConstantSDNode>(Node->getOperand(1))->getValue()) {
1376        // 1 -> Hi
1377        Result = DAG.getNode(ISD::SRL, OpTy, Node->getOperand(0),
1378                             DAG.getConstant(MVT::getSizeInBits(OpTy)/2,
1379                                             TLI.getShiftAmountTy()));
1380        Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Result);
1381      } else {
1382        // 0 -> Lo
1383        Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0),
1384                             Node->getOperand(0));
1385      }
1386      break;
1387    case Expand:
1388      // Get both the low and high parts.
1389      ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
1390      if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
1391        Result = Tmp2;  // 1 -> Hi
1392      else
1393        Result = Tmp1;  // 0 -> Lo
1394      break;
1395    }
1396    break;
1397  }
1398
1399  case ISD::CopyToReg:
1400    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1401
1402    assert(isTypeLegal(Node->getOperand(2).getValueType()) &&
1403           "Register type must be legal!");
1404    // Legalize the incoming value (must be a legal type).
1405    Tmp2 = LegalizeOp(Node->getOperand(2));
1406    if (Node->getNumValues() == 1) {
1407      Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2);
1408    } else {
1409      assert(Node->getNumValues() == 2 && "Unknown CopyToReg");
1410      if (Node->getNumOperands() == 4) {
1411        Tmp3 = LegalizeOp(Node->getOperand(3));
1412        Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2,
1413                                        Tmp3);
1414      } else {
1415        Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
1416      }
1417
1418      // Since this produces two values, make sure to remember that we legalized
1419      // both of them.
1420      AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1421      AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1422      return Result;
1423    }
1424    break;
1425
1426  case ISD::RET:
1427    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1428
1429    // Ensure that libcalls are emitted before a return.
1430    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1431    Tmp1 = LegalizeOp(Tmp1);
1432    LastCALLSEQ_END = DAG.getEntryNode();
1433
1434    switch (Node->getNumOperands()) {
1435    case 2:  // ret val
1436      Tmp2 = Node->getOperand(1);
1437      switch (getTypeAction(Tmp2.getValueType())) {
1438      case Legal:
1439        Result = DAG.UpdateNodeOperands(Result, Tmp1, LegalizeOp(Tmp2));
1440        break;
1441      case Expand:
1442        if (Tmp2.getValueType() != MVT::Vector) {
1443          SDOperand Lo, Hi;
1444          ExpandOp(Tmp2, Lo, Hi);
1445          Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
1446        } else {
1447          SDNode *InVal = Tmp2.Val;
1448          unsigned NumElems =
1449            cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
1450          MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
1451
1452          // Figure out if there is a Packed type corresponding to this Vector
1453          // type.  If so, convert to the packed type.
1454          MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
1455          if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
1456            // Turn this into a return of the packed type.
1457            Tmp2 = PackVectorOp(Tmp2, TVT);
1458            Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1459          } else if (NumElems == 1) {
1460            // Turn this into a return of the scalar type.
1461            Tmp2 = PackVectorOp(Tmp2, EVT);
1462            Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1463
1464            // FIXME: Returns of gcc generic vectors smaller than a legal type
1465            // should be returned in integer registers!
1466
1467            // The scalarized value type may not be legal, e.g. it might require
1468            // promotion or expansion.  Relegalize the return.
1469            Result = LegalizeOp(Result);
1470          } else {
1471            // FIXME: Returns of gcc generic vectors larger than a legal vector
1472            // type should be returned by reference!
1473            SDOperand Lo, Hi;
1474            SplitVectorOp(Tmp2, Lo, Hi);
1475            Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
1476            Result = LegalizeOp(Result);
1477          }
1478        }
1479        break;
1480      case Promote:
1481        Tmp2 = PromoteOp(Node->getOperand(1));
1482        Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1483        Result = LegalizeOp(Result);
1484        break;
1485      }
1486      break;
1487    case 1:  // ret void
1488      Result = DAG.UpdateNodeOperands(Result, Tmp1);
1489      break;
1490    default: { // ret <values>
1491      std::vector<SDOperand> NewValues;
1492      NewValues.push_back(Tmp1);
1493      for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1494        switch (getTypeAction(Node->getOperand(i).getValueType())) {
1495        case Legal:
1496          NewValues.push_back(LegalizeOp(Node->getOperand(i)));
1497          break;
1498        case Expand: {
1499          SDOperand Lo, Hi;
1500          assert(Node->getOperand(i).getValueType() != MVT::Vector &&
1501                 "FIXME: TODO: implement returning non-legal vector types!");
1502          ExpandOp(Node->getOperand(i), Lo, Hi);
1503          NewValues.push_back(Lo);
1504          NewValues.push_back(Hi);
1505          break;
1506        }
1507        case Promote:
1508          assert(0 && "Can't promote multiple return value yet!");
1509        }
1510
1511      if (NewValues.size() == Node->getNumOperands())
1512        Result = DAG.UpdateNodeOperands(Result, NewValues);
1513      else
1514        Result = DAG.getNode(ISD::RET, MVT::Other, NewValues);
1515      break;
1516    }
1517    }
1518
1519    if (Result.getOpcode() == ISD::RET) {
1520      switch (TLI.getOperationAction(Result.getOpcode(), MVT::Other)) {
1521      default: assert(0 && "This action is not supported yet!");
1522      case TargetLowering::Legal: break;
1523      case TargetLowering::Custom:
1524        Tmp1 = TLI.LowerOperation(Result, DAG);
1525        if (Tmp1.Val) Result = Tmp1;
1526        break;
1527      }
1528    }
1529    break;
1530  case ISD::STORE: {
1531    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1532    Tmp2 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
1533
1534    // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
1535    // FIXME: We shouldn't do this for TargetConstantFP's.
1536    // FIXME: move this to the DAG Combiner!
1537    if (ConstantFPSDNode *CFP =dyn_cast<ConstantFPSDNode>(Node->getOperand(1))){
1538      if (CFP->getValueType(0) == MVT::f32) {
1539        Tmp3 = DAG.getConstant(FloatToBits(CFP->getValue()), MVT::i32);
1540      } else {
1541        assert(CFP->getValueType(0) == MVT::f64 && "Unknown FP type!");
1542        Tmp3 = DAG.getConstant(DoubleToBits(CFP->getValue()), MVT::i64);
1543      }
1544      Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Tmp3, Tmp2,
1545                           Node->getOperand(3));
1546      break;
1547    }
1548
1549    switch (getTypeAction(Node->getOperand(1).getValueType())) {
1550    case Legal: {
1551      Tmp3 = LegalizeOp(Node->getOperand(1));
1552      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
1553                                      Node->getOperand(3));
1554
1555      MVT::ValueType VT = Tmp3.getValueType();
1556      switch (TLI.getOperationAction(ISD::STORE, VT)) {
1557      default: assert(0 && "This action is not supported yet!");
1558      case TargetLowering::Legal:  break;
1559      case TargetLowering::Custom:
1560        Tmp1 = TLI.LowerOperation(Result, DAG);
1561        if (Tmp1.Val) Result = Tmp1;
1562        break;
1563      case TargetLowering::Promote:
1564        assert(MVT::isVector(VT) && "Unknown legal promote case!");
1565        Tmp3 = DAG.getNode(ISD::BIT_CONVERT,
1566                           TLI.getTypeToPromoteTo(ISD::STORE, VT), Tmp3);
1567        Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
1568                                        Node->getOperand(3));
1569        break;
1570      }
1571      break;
1572    }
1573    case Promote:
1574      // Truncate the value and store the result.
1575      Tmp3 = PromoteOp(Node->getOperand(1));
1576      Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp3, Tmp2,
1577                           Node->getOperand(3),
1578                          DAG.getValueType(Node->getOperand(1).getValueType()));
1579      break;
1580
1581    case Expand:
1582      unsigned IncrementSize = 0;
1583      SDOperand Lo, Hi;
1584
1585      // If this is a vector type, then we have to calculate the increment as
1586      // the product of the element size in bytes, and the number of elements
1587      // in the high half of the vector.
1588      if (Node->getOperand(1).getValueType() == MVT::Vector) {
1589        SDNode *InVal = Node->getOperand(1).Val;
1590        unsigned NumElems =
1591          cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
1592        MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
1593
1594        // Figure out if there is a Packed type corresponding to this Vector
1595        // type.  If so, convert to the packed type.
1596        MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
1597        if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
1598          // Turn this into a normal store of the packed type.
1599          Tmp3 = PackVectorOp(Node->getOperand(1), TVT);
1600          Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
1601                                          Node->getOperand(3));
1602          Result = LegalizeOp(Result);
1603          break;
1604        } else if (NumElems == 1) {
1605          // Turn this into a normal store of the scalar type.
1606          Tmp3 = PackVectorOp(Node->getOperand(1), EVT);
1607          Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
1608                                          Node->getOperand(3));
1609          // The scalarized value type may not be legal, e.g. it might require
1610          // promotion or expansion.  Relegalize the scalar store.
1611          Result = LegalizeOp(Result);
1612          break;
1613        } else {
1614          SplitVectorOp(Node->getOperand(1), Lo, Hi);
1615          IncrementSize = NumElems/2 * MVT::getSizeInBits(EVT)/8;
1616        }
1617      } else {
1618        ExpandOp(Node->getOperand(1), Lo, Hi);
1619        IncrementSize = MVT::getSizeInBits(Hi.getValueType())/8;
1620
1621        if (!TLI.isLittleEndian())
1622          std::swap(Lo, Hi);
1623      }
1624
1625      Lo = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Lo, Tmp2,
1626                       Node->getOperand(3));
1627      Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
1628                         getIntPtrConstant(IncrementSize));
1629      assert(isTypeLegal(Tmp2.getValueType()) &&
1630             "Pointers must be legal!");
1631      // FIXME: This sets the srcvalue of both halves to be the same, which is
1632      // wrong.
1633      Hi = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Hi, Tmp2,
1634                       Node->getOperand(3));
1635      Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
1636      break;
1637    }
1638    break;
1639  }
1640  case ISD::PCMARKER:
1641    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1642    Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1643    break;
1644  case ISD::STACKSAVE:
1645    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1646    Result = DAG.UpdateNodeOperands(Result, Tmp1);
1647    Tmp1 = Result.getValue(0);
1648    Tmp2 = Result.getValue(1);
1649
1650    switch (TLI.getOperationAction(ISD::STACKSAVE, MVT::Other)) {
1651    default: assert(0 && "This action is not supported yet!");
1652    case TargetLowering::Legal: break;
1653    case TargetLowering::Custom:
1654      Tmp3 = TLI.LowerOperation(Result, DAG);
1655      if (Tmp3.Val) {
1656        Tmp1 = LegalizeOp(Tmp3);
1657        Tmp2 = LegalizeOp(Tmp3.getValue(1));
1658      }
1659      break;
1660    case TargetLowering::Expand:
1661      // Expand to CopyFromReg if the target set
1662      // StackPointerRegisterToSaveRestore.
1663      if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
1664        Tmp1 = DAG.getCopyFromReg(Result.getOperand(0), SP,
1665                                  Node->getValueType(0));
1666        Tmp2 = Tmp1.getValue(1);
1667      } else {
1668        Tmp1 = DAG.getNode(ISD::UNDEF, Node->getValueType(0));
1669        Tmp2 = Node->getOperand(0);
1670      }
1671      break;
1672    }
1673
1674    // Since stacksave produce two values, make sure to remember that we
1675    // legalized both of them.
1676    AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1677    AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1678    return Op.ResNo ? Tmp2 : Tmp1;
1679
1680  case ISD::STACKRESTORE:
1681    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1682    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1683    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1684
1685    switch (TLI.getOperationAction(ISD::STACKRESTORE, MVT::Other)) {
1686    default: assert(0 && "This action is not supported yet!");
1687    case TargetLowering::Legal: break;
1688    case TargetLowering::Custom:
1689      Tmp1 = TLI.LowerOperation(Result, DAG);
1690      if (Tmp1.Val) Result = Tmp1;
1691      break;
1692    case TargetLowering::Expand:
1693      // Expand to CopyToReg if the target set
1694      // StackPointerRegisterToSaveRestore.
1695      if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
1696        Result = DAG.getCopyToReg(Tmp1, SP, Tmp2);
1697      } else {
1698        Result = Tmp1;
1699      }
1700      break;
1701    }
1702    break;
1703
1704  case ISD::READCYCLECOUNTER:
1705    Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain
1706    Result = DAG.UpdateNodeOperands(Result, Tmp1);
1707
1708    // Since rdcc produce two values, make sure to remember that we legalized
1709    // both of them.
1710    AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1711    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1712    return Result;
1713
1714  case ISD::TRUNCSTORE: {
1715    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1716    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
1717
1718    assert(isTypeLegal(Node->getOperand(1).getValueType()) &&
1719           "Cannot handle illegal TRUNCSTORE yet!");
1720    Tmp2 = LegalizeOp(Node->getOperand(1));
1721
1722    // The only promote case we handle is TRUNCSTORE:i1 X into
1723    //   -> TRUNCSTORE:i8 (and X, 1)
1724    if (cast<VTSDNode>(Node->getOperand(4))->getVT() == MVT::i1 &&
1725        TLI.getOperationAction(ISD::TRUNCSTORE, MVT::i1) ==
1726              TargetLowering::Promote) {
1727      // Promote the bool to a mask then store.
1728      Tmp2 = DAG.getNode(ISD::AND, Tmp2.getValueType(), Tmp2,
1729                         DAG.getConstant(1, Tmp2.getValueType()));
1730      Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
1731                           Node->getOperand(3), DAG.getValueType(MVT::i8));
1732
1733    } else if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1734               Tmp3 != Node->getOperand(2)) {
1735      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3,
1736                                      Node->getOperand(3), Node->getOperand(4));
1737    }
1738
1739    MVT::ValueType StVT = cast<VTSDNode>(Result.Val->getOperand(4))->getVT();
1740    switch (TLI.getOperationAction(Result.Val->getOpcode(), StVT)) {
1741    default: assert(0 && "This action is not supported yet!");
1742    case TargetLowering::Legal: break;
1743    case TargetLowering::Custom:
1744      Tmp1 = TLI.LowerOperation(Result, DAG);
1745      if (Tmp1.Val) Result = Tmp1;
1746      break;
1747    }
1748    break;
1749  }
1750  case ISD::SELECT:
1751    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1752    case Expand: assert(0 && "It's impossible to expand bools");
1753    case Legal:
1754      Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
1755      break;
1756    case Promote:
1757      Tmp1 = PromoteOp(Node->getOperand(0));  // Promote the condition.
1758      break;
1759    }
1760    Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
1761    Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
1762
1763    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1764
1765    switch (TLI.getOperationAction(ISD::SELECT, Tmp2.getValueType())) {
1766    default: assert(0 && "This action is not supported yet!");
1767    case TargetLowering::Legal: break;
1768    case TargetLowering::Custom: {
1769      Tmp1 = TLI.LowerOperation(Result, DAG);
1770      if (Tmp1.Val) Result = Tmp1;
1771      break;
1772    }
1773    case TargetLowering::Expand:
1774      if (Tmp1.getOpcode() == ISD::SETCC) {
1775        Result = DAG.getSelectCC(Tmp1.getOperand(0), Tmp1.getOperand(1),
1776                              Tmp2, Tmp3,
1777                              cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
1778      } else {
1779        // Make sure the condition is either zero or one.  It may have been
1780        // promoted from something else.
1781        unsigned NumBits = MVT::getSizeInBits(Tmp1.getValueType());
1782        if (!TLI.MaskedValueIsZero(Tmp1, (~0ULL >> (64-NumBits))^1))
1783          Tmp1 = DAG.getZeroExtendInReg(Tmp1, MVT::i1);
1784        Result = DAG.getSelectCC(Tmp1,
1785                                 DAG.getConstant(0, Tmp1.getValueType()),
1786                                 Tmp2, Tmp3, ISD::SETNE);
1787      }
1788      break;
1789    case TargetLowering::Promote: {
1790      MVT::ValueType NVT =
1791        TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
1792      unsigned ExtOp, TruncOp;
1793      if (MVT::isVector(Tmp2.getValueType())) {
1794        ExtOp   = ISD::BIT_CONVERT;
1795        TruncOp = ISD::BIT_CONVERT;
1796      } else if (MVT::isInteger(Tmp2.getValueType())) {
1797        ExtOp   = ISD::ANY_EXTEND;
1798        TruncOp = ISD::TRUNCATE;
1799      } else {
1800        ExtOp   = ISD::FP_EXTEND;
1801        TruncOp = ISD::FP_ROUND;
1802      }
1803      // Promote each of the values to the new type.
1804      Tmp2 = DAG.getNode(ExtOp, NVT, Tmp2);
1805      Tmp3 = DAG.getNode(ExtOp, NVT, Tmp3);
1806      // Perform the larger operation, then round down.
1807      Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2,Tmp3);
1808      Result = DAG.getNode(TruncOp, Node->getValueType(0), Result);
1809      break;
1810    }
1811    }
1812    break;
1813  case ISD::SELECT_CC: {
1814    Tmp1 = Node->getOperand(0);               // LHS
1815    Tmp2 = Node->getOperand(1);               // RHS
1816    Tmp3 = LegalizeOp(Node->getOperand(2));   // True
1817    Tmp4 = LegalizeOp(Node->getOperand(3));   // False
1818    SDOperand CC = Node->getOperand(4);
1819
1820    LegalizeSetCCOperands(Tmp1, Tmp2, CC);
1821
1822    // If we didn't get both a LHS and RHS back from LegalizeSetCCOperands,
1823    // the LHS is a legal SETCC itself.  In this case, we need to compare
1824    // the result against zero to select between true and false values.
1825    if (Tmp2.Val == 0) {
1826      Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
1827      CC = DAG.getCondCode(ISD::SETNE);
1828    }
1829    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4, CC);
1830
1831    // Everything is legal, see if we should expand this op or something.
1832    switch (TLI.getOperationAction(ISD::SELECT_CC, Tmp3.getValueType())) {
1833    default: assert(0 && "This action is not supported yet!");
1834    case TargetLowering::Legal: break;
1835    case TargetLowering::Custom:
1836      Tmp1 = TLI.LowerOperation(Result, DAG);
1837      if (Tmp1.Val) Result = Tmp1;
1838      break;
1839    }
1840    break;
1841  }
1842  case ISD::SETCC:
1843    Tmp1 = Node->getOperand(0);
1844    Tmp2 = Node->getOperand(1);
1845    Tmp3 = Node->getOperand(2);
1846    LegalizeSetCCOperands(Tmp1, Tmp2, Tmp3);
1847
1848    // If we had to Expand the SetCC operands into a SELECT node, then it may
1849    // not always be possible to return a true LHS & RHS.  In this case, just
1850    // return the value we legalized, returned in the LHS
1851    if (Tmp2.Val == 0) {
1852      Result = Tmp1;
1853      break;
1854    }
1855
1856    switch (TLI.getOperationAction(ISD::SETCC, Tmp1.getValueType())) {
1857    default: assert(0 && "Cannot handle this action for SETCC yet!");
1858    case TargetLowering::Custom:
1859      isCustom = true;
1860      // FALLTHROUGH.
1861    case TargetLowering::Legal:
1862      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1863      if (isCustom) {
1864        Tmp3 = TLI.LowerOperation(Result, DAG);
1865        if (Tmp3.Val) Result = Tmp3;
1866      }
1867      break;
1868    case TargetLowering::Promote: {
1869      // First step, figure out the appropriate operation to use.
1870      // Allow SETCC to not be supported for all legal data types
1871      // Mostly this targets FP
1872      MVT::ValueType NewInTy = Node->getOperand(0).getValueType();
1873      MVT::ValueType OldVT = NewInTy;
1874
1875      // Scan for the appropriate larger type to use.
1876      while (1) {
1877        NewInTy = (MVT::ValueType)(NewInTy+1);
1878
1879        assert(MVT::isInteger(NewInTy) == MVT::isInteger(OldVT) &&
1880               "Fell off of the edge of the integer world");
1881        assert(MVT::isFloatingPoint(NewInTy) == MVT::isFloatingPoint(OldVT) &&
1882               "Fell off of the edge of the floating point world");
1883
1884        // If the target supports SETCC of this type, use it.
1885        if (TLI.isOperationLegal(ISD::SETCC, NewInTy))
1886          break;
1887      }
1888      if (MVT::isInteger(NewInTy))
1889        assert(0 && "Cannot promote Legal Integer SETCC yet");
1890      else {
1891        Tmp1 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp1);
1892        Tmp2 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp2);
1893      }
1894      Tmp1 = LegalizeOp(Tmp1);
1895      Tmp2 = LegalizeOp(Tmp2);
1896      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1897      Result = LegalizeOp(Result);
1898      break;
1899    }
1900    case TargetLowering::Expand:
1901      // Expand a setcc node into a select_cc of the same condition, lhs, and
1902      // rhs that selects between const 1 (true) and const 0 (false).
1903      MVT::ValueType VT = Node->getValueType(0);
1904      Result = DAG.getNode(ISD::SELECT_CC, VT, Tmp1, Tmp2,
1905                           DAG.getConstant(1, VT), DAG.getConstant(0, VT),
1906                           Node->getOperand(2));
1907      break;
1908    }
1909    break;
1910  case ISD::MEMSET:
1911  case ISD::MEMCPY:
1912  case ISD::MEMMOVE: {
1913    Tmp1 = LegalizeOp(Node->getOperand(0));      // Chain
1914    Tmp2 = LegalizeOp(Node->getOperand(1));      // Pointer
1915
1916    if (Node->getOpcode() == ISD::MEMSET) {      // memset = ubyte
1917      switch (getTypeAction(Node->getOperand(2).getValueType())) {
1918      case Expand: assert(0 && "Cannot expand a byte!");
1919      case Legal:
1920        Tmp3 = LegalizeOp(Node->getOperand(2));
1921        break;
1922      case Promote:
1923        Tmp3 = PromoteOp(Node->getOperand(2));
1924        break;
1925      }
1926    } else {
1927      Tmp3 = LegalizeOp(Node->getOperand(2));    // memcpy/move = pointer,
1928    }
1929
1930    SDOperand Tmp4;
1931    switch (getTypeAction(Node->getOperand(3).getValueType())) {
1932    case Expand: {
1933      // Length is too big, just take the lo-part of the length.
1934      SDOperand HiPart;
1935      ExpandOp(Node->getOperand(3), HiPart, Tmp4);
1936      break;
1937    }
1938    case Legal:
1939      Tmp4 = LegalizeOp(Node->getOperand(3));
1940      break;
1941    case Promote:
1942      Tmp4 = PromoteOp(Node->getOperand(3));
1943      break;
1944    }
1945
1946    SDOperand Tmp5;
1947    switch (getTypeAction(Node->getOperand(4).getValueType())) {  // uint
1948    case Expand: assert(0 && "Cannot expand this yet!");
1949    case Legal:
1950      Tmp5 = LegalizeOp(Node->getOperand(4));
1951      break;
1952    case Promote:
1953      Tmp5 = PromoteOp(Node->getOperand(4));
1954      break;
1955    }
1956
1957    switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
1958    default: assert(0 && "This action not implemented for this operation!");
1959    case TargetLowering::Custom:
1960      isCustom = true;
1961      // FALLTHROUGH
1962    case TargetLowering::Legal:
1963      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4, Tmp5);
1964      if (isCustom) {
1965        Tmp1 = TLI.LowerOperation(Result, DAG);
1966        if (Tmp1.Val) Result = Tmp1;
1967      }
1968      break;
1969    case TargetLowering::Expand: {
1970      // Otherwise, the target does not support this operation.  Lower the
1971      // operation to an explicit libcall as appropriate.
1972      MVT::ValueType IntPtr = TLI.getPointerTy();
1973      const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
1974      std::vector<std::pair<SDOperand, const Type*> > Args;
1975
1976      const char *FnName = 0;
1977      if (Node->getOpcode() == ISD::MEMSET) {
1978        Args.push_back(std::make_pair(Tmp2, IntPtrTy));
1979        // Extend the (previously legalized) ubyte argument to be an int value
1980        // for the call.
1981        if (Tmp3.getValueType() > MVT::i32)
1982          Tmp3 = DAG.getNode(ISD::TRUNCATE, MVT::i32, Tmp3);
1983        else
1984          Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Tmp3);
1985        Args.push_back(std::make_pair(Tmp3, Type::IntTy));
1986        Args.push_back(std::make_pair(Tmp4, IntPtrTy));
1987
1988        FnName = "memset";
1989      } else if (Node->getOpcode() == ISD::MEMCPY ||
1990                 Node->getOpcode() == ISD::MEMMOVE) {
1991        Args.push_back(std::make_pair(Tmp2, IntPtrTy));
1992        Args.push_back(std::make_pair(Tmp3, IntPtrTy));
1993        Args.push_back(std::make_pair(Tmp4, IntPtrTy));
1994        FnName = Node->getOpcode() == ISD::MEMMOVE ? "memmove" : "memcpy";
1995      } else {
1996        assert(0 && "Unknown op!");
1997      }
1998
1999      std::pair<SDOperand,SDOperand> CallResult =
2000        TLI.LowerCallTo(Tmp1, Type::VoidTy, false, CallingConv::C, false,
2001                        DAG.getExternalSymbol(FnName, IntPtr), Args, DAG);
2002      Result = CallResult.second;
2003      break;
2004    }
2005    }
2006    break;
2007  }
2008
2009  case ISD::SHL_PARTS:
2010  case ISD::SRA_PARTS:
2011  case ISD::SRL_PARTS: {
2012    std::vector<SDOperand> Ops;
2013    bool Changed = false;
2014    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
2015      Ops.push_back(LegalizeOp(Node->getOperand(i)));
2016      Changed |= Ops.back() != Node->getOperand(i);
2017    }
2018    if (Changed)
2019      Result = DAG.UpdateNodeOperands(Result, Ops);
2020
2021    switch (TLI.getOperationAction(Node->getOpcode(),
2022                                   Node->getValueType(0))) {
2023    default: assert(0 && "This action is not supported yet!");
2024    case TargetLowering::Legal: break;
2025    case TargetLowering::Custom:
2026      Tmp1 = TLI.LowerOperation(Result, DAG);
2027      if (Tmp1.Val) {
2028        SDOperand Tmp2, RetVal(0, 0);
2029        for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
2030          Tmp2 = LegalizeOp(Tmp1.getValue(i));
2031          AddLegalizedOperand(SDOperand(Node, i), Tmp2);
2032          if (i == Op.ResNo)
2033            RetVal = Tmp2;
2034        }
2035        assert(RetVal.Val && "Illegal result number");
2036        return RetVal;
2037      }
2038      break;
2039    }
2040
2041    // Since these produce multiple values, make sure to remember that we
2042    // legalized all of them.
2043    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
2044      AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
2045    return Result.getValue(Op.ResNo);
2046  }
2047
2048    // Binary operators
2049  case ISD::ADD:
2050  case ISD::SUB:
2051  case ISD::MUL:
2052  case ISD::MULHS:
2053  case ISD::MULHU:
2054  case ISD::UDIV:
2055  case ISD::SDIV:
2056  case ISD::AND:
2057  case ISD::OR:
2058  case ISD::XOR:
2059  case ISD::SHL:
2060  case ISD::SRL:
2061  case ISD::SRA:
2062  case ISD::FADD:
2063  case ISD::FSUB:
2064  case ISD::FMUL:
2065  case ISD::FDIV:
2066    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2067    switch (getTypeAction(Node->getOperand(1).getValueType())) {
2068    case Expand: assert(0 && "Not possible");
2069    case Legal:
2070      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
2071      break;
2072    case Promote:
2073      Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
2074      break;
2075    }
2076
2077    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2078
2079    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2080    default: assert(0 && "BinOp legalize operation not supported");
2081    case TargetLowering::Legal: break;
2082    case TargetLowering::Custom:
2083      Tmp1 = TLI.LowerOperation(Result, DAG);
2084      if (Tmp1.Val) Result = Tmp1;
2085      break;
2086    case TargetLowering::Expand: {
2087      assert(MVT::isVector(Node->getValueType(0)) &&
2088             "Cannot expand this binary operator!");
2089      // Expand the operation into a bunch of nasty scalar code.
2090      std::vector<SDOperand> Ops;
2091      MVT::ValueType EltVT = MVT::getVectorBaseType(Node->getValueType(0));
2092      MVT::ValueType PtrVT = TLI.getPointerTy();
2093      for (unsigned i = 0, e = MVT::getVectorNumElements(Node->getValueType(0));
2094           i != e; ++i) {
2095        SDOperand Idx = DAG.getConstant(i, PtrVT);
2096        SDOperand LHS = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp1, Idx);
2097        SDOperand RHS = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp2, Idx);
2098        Ops.push_back(DAG.getNode(Node->getOpcode(), EltVT, LHS, RHS));
2099      }
2100      Result = DAG.getNode(ISD::BUILD_VECTOR, Node->getValueType(0), Ops);
2101      break;
2102    }
2103    case TargetLowering::Promote: {
2104      switch (Node->getOpcode()) {
2105      default:  assert(0 && "Do not know how to promote this BinOp!");
2106      case ISD::AND:
2107      case ISD::OR:
2108      case ISD::XOR: {
2109        MVT::ValueType OVT = Node->getValueType(0);
2110        MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
2111        assert(MVT::isVector(OVT) && "Cannot promote this BinOp!");
2112        // Bit convert each of the values to the new type.
2113        Tmp1 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp1);
2114        Tmp2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp2);
2115        Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2116        // Bit convert the result back the original type.
2117        Result = DAG.getNode(ISD::BIT_CONVERT, OVT, Result);
2118        break;
2119      }
2120      }
2121    }
2122    }
2123    break;
2124
2125  case ISD::FCOPYSIGN:  // FCOPYSIGN does not require LHS/RHS to match type!
2126    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2127    switch (getTypeAction(Node->getOperand(1).getValueType())) {
2128      case Expand: assert(0 && "Not possible");
2129      case Legal:
2130        Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
2131        break;
2132      case Promote:
2133        Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
2134        break;
2135    }
2136
2137    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2138
2139    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2140    default: assert(0 && "Operation not supported");
2141    case TargetLowering::Custom:
2142      Tmp1 = TLI.LowerOperation(Result, DAG);
2143      if (Tmp1.Val) Result = Tmp1;
2144      break;
2145    case TargetLowering::Legal: break;
2146    case TargetLowering::Expand:
2147      // If this target supports fabs/fneg natively, do this efficiently.
2148      if (TLI.isOperationLegal(ISD::FABS, Tmp1.getValueType()) &&
2149          TLI.isOperationLegal(ISD::FNEG, Tmp1.getValueType())) {
2150        // Get the sign bit of the RHS.
2151        MVT::ValueType IVT =
2152          Tmp2.getValueType() == MVT::f32 ? MVT::i32 : MVT::i64;
2153        SDOperand SignBit = DAG.getNode(ISD::BIT_CONVERT, IVT, Tmp2);
2154        SignBit = DAG.getSetCC(TLI.getSetCCResultTy(),
2155                               SignBit, DAG.getConstant(0, IVT), ISD::SETLT);
2156        // Get the absolute value of the result.
2157        SDOperand AbsVal = DAG.getNode(ISD::FABS, Tmp1.getValueType(), Tmp1);
2158        // Select between the nabs and abs value based on the sign bit of
2159        // the input.
2160        Result = DAG.getNode(ISD::SELECT, AbsVal.getValueType(), SignBit,
2161                             DAG.getNode(ISD::FNEG, AbsVal.getValueType(),
2162                                         AbsVal),
2163                             AbsVal);
2164        Result = LegalizeOp(Result);
2165        break;
2166      }
2167
2168      // Otherwise, do bitwise ops!
2169
2170      // copysign -> copysignf/copysign libcall.
2171      const char *FnName;
2172      if (Node->getValueType(0) == MVT::f32) {
2173        FnName = "copysignf";
2174        if (Tmp2.getValueType() != MVT::f32)  // Force operands to match type.
2175          Result = DAG.UpdateNodeOperands(Result, Tmp1,
2176                                    DAG.getNode(ISD::FP_ROUND, MVT::f32, Tmp2));
2177      } else {
2178        FnName = "copysign";
2179        if (Tmp2.getValueType() != MVT::f64)  // Force operands to match type.
2180          Result = DAG.UpdateNodeOperands(Result, Tmp1,
2181                                   DAG.getNode(ISD::FP_EXTEND, MVT::f64, Tmp2));
2182      }
2183      SDOperand Dummy;
2184      Result = ExpandLibCall(FnName, Node, Dummy);
2185      break;
2186    }
2187    break;
2188
2189  case ISD::ADDC:
2190  case ISD::SUBC:
2191    Tmp1 = LegalizeOp(Node->getOperand(0));
2192    Tmp2 = LegalizeOp(Node->getOperand(1));
2193    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2194    // Since this produces two values, make sure to remember that we legalized
2195    // both of them.
2196    AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
2197    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
2198    return Result;
2199
2200  case ISD::ADDE:
2201  case ISD::SUBE:
2202    Tmp1 = LegalizeOp(Node->getOperand(0));
2203    Tmp2 = LegalizeOp(Node->getOperand(1));
2204    Tmp3 = LegalizeOp(Node->getOperand(2));
2205    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2206    // Since this produces two values, make sure to remember that we legalized
2207    // both of them.
2208    AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
2209    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
2210    return Result;
2211
2212  case ISD::BUILD_PAIR: {
2213    MVT::ValueType PairTy = Node->getValueType(0);
2214    // TODO: handle the case where the Lo and Hi operands are not of legal type
2215    Tmp1 = LegalizeOp(Node->getOperand(0));   // Lo
2216    Tmp2 = LegalizeOp(Node->getOperand(1));   // Hi
2217    switch (TLI.getOperationAction(ISD::BUILD_PAIR, PairTy)) {
2218    case TargetLowering::Promote:
2219    case TargetLowering::Custom:
2220      assert(0 && "Cannot promote/custom this yet!");
2221    case TargetLowering::Legal:
2222      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
2223        Result = DAG.getNode(ISD::BUILD_PAIR, PairTy, Tmp1, Tmp2);
2224      break;
2225    case TargetLowering::Expand:
2226      Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, PairTy, Tmp1);
2227      Tmp2 = DAG.getNode(ISD::ANY_EXTEND, PairTy, Tmp2);
2228      Tmp2 = DAG.getNode(ISD::SHL, PairTy, Tmp2,
2229                         DAG.getConstant(MVT::getSizeInBits(PairTy)/2,
2230                                         TLI.getShiftAmountTy()));
2231      Result = DAG.getNode(ISD::OR, PairTy, Tmp1, Tmp2);
2232      break;
2233    }
2234    break;
2235  }
2236
2237  case ISD::UREM:
2238  case ISD::SREM:
2239  case ISD::FREM:
2240    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2241    Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
2242
2243    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2244    case TargetLowering::Promote: assert(0 && "Cannot promote this yet!");
2245    case TargetLowering::Custom:
2246      isCustom = true;
2247      // FALLTHROUGH
2248    case TargetLowering::Legal:
2249      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2250      if (isCustom) {
2251        Tmp1 = TLI.LowerOperation(Result, DAG);
2252        if (Tmp1.Val) Result = Tmp1;
2253      }
2254      break;
2255    case TargetLowering::Expand:
2256      if (MVT::isInteger(Node->getValueType(0))) {
2257        // X % Y -> X-X/Y*Y
2258        MVT::ValueType VT = Node->getValueType(0);
2259        unsigned Opc = Node->getOpcode() == ISD::UREM ? ISD::UDIV : ISD::SDIV;
2260        Result = DAG.getNode(Opc, VT, Tmp1, Tmp2);
2261        Result = DAG.getNode(ISD::MUL, VT, Result, Tmp2);
2262        Result = DAG.getNode(ISD::SUB, VT, Tmp1, Result);
2263      } else {
2264        // Floating point mod -> fmod libcall.
2265        const char *FnName = Node->getValueType(0) == MVT::f32 ? "fmodf":"fmod";
2266        SDOperand Dummy;
2267        Result = ExpandLibCall(FnName, Node, Dummy);
2268      }
2269      break;
2270    }
2271    break;
2272  case ISD::VAARG: {
2273    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2274    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2275
2276    MVT::ValueType VT = Node->getValueType(0);
2277    switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
2278    default: assert(0 && "This action is not supported yet!");
2279    case TargetLowering::Custom:
2280      isCustom = true;
2281      // FALLTHROUGH
2282    case TargetLowering::Legal:
2283      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2284      Result = Result.getValue(0);
2285      Tmp1 = Result.getValue(1);
2286
2287      if (isCustom) {
2288        Tmp2 = TLI.LowerOperation(Result, DAG);
2289        if (Tmp2.Val) {
2290          Result = LegalizeOp(Tmp2);
2291          Tmp1 = LegalizeOp(Tmp2.getValue(1));
2292        }
2293      }
2294      break;
2295    case TargetLowering::Expand: {
2296      SDOperand VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2,
2297                                     Node->getOperand(2));
2298      // Increment the pointer, VAList, to the next vaarg
2299      Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList,
2300                         DAG.getConstant(MVT::getSizeInBits(VT)/8,
2301                                         TLI.getPointerTy()));
2302      // Store the incremented VAList to the legalized pointer
2303      Tmp3 = DAG.getNode(ISD::STORE, MVT::Other, VAList.getValue(1), Tmp3, Tmp2,
2304                         Node->getOperand(2));
2305      // Load the actual argument out of the pointer VAList
2306      Result = DAG.getLoad(VT, Tmp3, VAList, DAG.getSrcValue(0));
2307      Tmp1 = LegalizeOp(Result.getValue(1));
2308      Result = LegalizeOp(Result);
2309      break;
2310    }
2311    }
2312    // Since VAARG produces two values, make sure to remember that we
2313    // legalized both of them.
2314    AddLegalizedOperand(SDOperand(Node, 0), Result);
2315    AddLegalizedOperand(SDOperand(Node, 1), Tmp1);
2316    return Op.ResNo ? Tmp1 : Result;
2317  }
2318
2319  case ISD::VACOPY:
2320    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2321    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the dest pointer.
2322    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the source pointer.
2323
2324    switch (TLI.getOperationAction(ISD::VACOPY, MVT::Other)) {
2325    default: assert(0 && "This action is not supported yet!");
2326    case TargetLowering::Custom:
2327      isCustom = true;
2328      // FALLTHROUGH
2329    case TargetLowering::Legal:
2330      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3,
2331                                      Node->getOperand(3), Node->getOperand(4));
2332      if (isCustom) {
2333        Tmp1 = TLI.LowerOperation(Result, DAG);
2334        if (Tmp1.Val) Result = Tmp1;
2335      }
2336      break;
2337    case TargetLowering::Expand:
2338      // This defaults to loading a pointer from the input and storing it to the
2339      // output, returning the chain.
2340      Tmp4 = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp3, Node->getOperand(3));
2341      Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp4.getValue(1), Tmp4, Tmp2,
2342                           Node->getOperand(4));
2343      break;
2344    }
2345    break;
2346
2347  case ISD::VAEND:
2348    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2349    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2350
2351    switch (TLI.getOperationAction(ISD::VAEND, MVT::Other)) {
2352    default: assert(0 && "This action is not supported yet!");
2353    case TargetLowering::Custom:
2354      isCustom = true;
2355      // FALLTHROUGH
2356    case TargetLowering::Legal:
2357      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2358      if (isCustom) {
2359        Tmp1 = TLI.LowerOperation(Tmp1, DAG);
2360        if (Tmp1.Val) Result = Tmp1;
2361      }
2362      break;
2363    case TargetLowering::Expand:
2364      Result = Tmp1; // Default to a no-op, return the chain
2365      break;
2366    }
2367    break;
2368
2369  case ISD::VASTART:
2370    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2371    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2372
2373    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2374
2375    switch (TLI.getOperationAction(ISD::VASTART, MVT::Other)) {
2376    default: assert(0 && "This action is not supported yet!");
2377    case TargetLowering::Legal: break;
2378    case TargetLowering::Custom:
2379      Tmp1 = TLI.LowerOperation(Result, DAG);
2380      if (Tmp1.Val) Result = Tmp1;
2381      break;
2382    }
2383    break;
2384
2385  case ISD::ROTL:
2386  case ISD::ROTR:
2387    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2388    Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
2389
2390    assert(TLI.isOperationLegal(Node->getOpcode(), Node->getValueType(0)) &&
2391           "Cannot handle this yet!");
2392    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2393    break;
2394
2395  case ISD::BSWAP:
2396    Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
2397    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2398    case TargetLowering::Custom:
2399      assert(0 && "Cannot custom legalize this yet!");
2400    case TargetLowering::Legal:
2401      Result = DAG.UpdateNodeOperands(Result, Tmp1);
2402      break;
2403    case TargetLowering::Promote: {
2404      MVT::ValueType OVT = Tmp1.getValueType();
2405      MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
2406      unsigned DiffBits = getSizeInBits(NVT) - getSizeInBits(OVT);
2407
2408      Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
2409      Tmp1 = DAG.getNode(ISD::BSWAP, NVT, Tmp1);
2410      Result = DAG.getNode(ISD::SRL, NVT, Tmp1,
2411                           DAG.getConstant(DiffBits, TLI.getShiftAmountTy()));
2412      break;
2413    }
2414    case TargetLowering::Expand:
2415      Result = ExpandBSWAP(Tmp1);
2416      break;
2417    }
2418    break;
2419
2420  case ISD::CTPOP:
2421  case ISD::CTTZ:
2422  case ISD::CTLZ:
2423    Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
2424    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2425    case TargetLowering::Custom: assert(0 && "Cannot custom handle this yet!");
2426    case TargetLowering::Legal:
2427      Result = DAG.UpdateNodeOperands(Result, Tmp1);
2428      break;
2429    case TargetLowering::Promote: {
2430      MVT::ValueType OVT = Tmp1.getValueType();
2431      MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
2432
2433      // Zero extend the argument.
2434      Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
2435      // Perform the larger operation, then subtract if needed.
2436      Tmp1 = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2437      switch (Node->getOpcode()) {
2438      case ISD::CTPOP:
2439        Result = Tmp1;
2440        break;
2441      case ISD::CTTZ:
2442        //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
2443        Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
2444                            DAG.getConstant(getSizeInBits(NVT), NVT),
2445                            ISD::SETEQ);
2446        Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
2447                           DAG.getConstant(getSizeInBits(OVT),NVT), Tmp1);
2448        break;
2449      case ISD::CTLZ:
2450        // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
2451        Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
2452                             DAG.getConstant(getSizeInBits(NVT) -
2453                                             getSizeInBits(OVT), NVT));
2454        break;
2455      }
2456      break;
2457    }
2458    case TargetLowering::Expand:
2459      Result = ExpandBitCount(Node->getOpcode(), Tmp1);
2460      break;
2461    }
2462    break;
2463
2464    // Unary operators
2465  case ISD::FABS:
2466  case ISD::FNEG:
2467  case ISD::FSQRT:
2468  case ISD::FSIN:
2469  case ISD::FCOS:
2470    Tmp1 = LegalizeOp(Node->getOperand(0));
2471    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2472    case TargetLowering::Promote:
2473    case TargetLowering::Custom:
2474     isCustom = true;
2475     // FALLTHROUGH
2476    case TargetLowering::Legal:
2477      Result = DAG.UpdateNodeOperands(Result, Tmp1);
2478      if (isCustom) {
2479        Tmp1 = TLI.LowerOperation(Result, DAG);
2480        if (Tmp1.Val) Result = Tmp1;
2481      }
2482      break;
2483    case TargetLowering::Expand:
2484      switch (Node->getOpcode()) {
2485      default: assert(0 && "Unreachable!");
2486      case ISD::FNEG:
2487        // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
2488        Tmp2 = DAG.getConstantFP(-0.0, Node->getValueType(0));
2489        Result = DAG.getNode(ISD::FSUB, Node->getValueType(0), Tmp2, Tmp1);
2490        break;
2491      case ISD::FABS: {
2492        // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
2493        MVT::ValueType VT = Node->getValueType(0);
2494        Tmp2 = DAG.getConstantFP(0.0, VT);
2495        Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1, Tmp2, ISD::SETUGT);
2496        Tmp3 = DAG.getNode(ISD::FNEG, VT, Tmp1);
2497        Result = DAG.getNode(ISD::SELECT, VT, Tmp2, Tmp1, Tmp3);
2498        break;
2499      }
2500      case ISD::FSQRT:
2501      case ISD::FSIN:
2502      case ISD::FCOS: {
2503        MVT::ValueType VT = Node->getValueType(0);
2504        const char *FnName = 0;
2505        switch(Node->getOpcode()) {
2506        case ISD::FSQRT: FnName = VT == MVT::f32 ? "sqrtf" : "sqrt"; break;
2507        case ISD::FSIN:  FnName = VT == MVT::f32 ? "sinf"  : "sin"; break;
2508        case ISD::FCOS:  FnName = VT == MVT::f32 ? "cosf"  : "cos"; break;
2509        default: assert(0 && "Unreachable!");
2510        }
2511        SDOperand Dummy;
2512        Result = ExpandLibCall(FnName, Node, Dummy);
2513        break;
2514      }
2515      }
2516      break;
2517    }
2518    break;
2519
2520  case ISD::BIT_CONVERT:
2521    if (!isTypeLegal(Node->getOperand(0).getValueType())) {
2522      Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2523    } else {
2524      switch (TLI.getOperationAction(ISD::BIT_CONVERT,
2525                                     Node->getOperand(0).getValueType())) {
2526      default: assert(0 && "Unknown operation action!");
2527      case TargetLowering::Expand:
2528        Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2529        break;
2530      case TargetLowering::Legal:
2531        Tmp1 = LegalizeOp(Node->getOperand(0));
2532        Result = DAG.UpdateNodeOperands(Result, Tmp1);
2533        break;
2534      }
2535    }
2536    break;
2537  case ISD::VBIT_CONVERT: {
2538    assert(Op.getOperand(0).getValueType() == MVT::Vector &&
2539           "Can only have VBIT_CONVERT where input or output is MVT::Vector!");
2540
2541    // The input has to be a vector type, we have to either scalarize it, pack
2542    // it, or convert it based on whether the input vector type is legal.
2543    SDNode *InVal = Node->getOperand(0).Val;
2544    unsigned NumElems =
2545      cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
2546    MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
2547
2548    // Figure out if there is a Packed type corresponding to this Vector
2549    // type.  If so, convert to the packed type.
2550    MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
2551    if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
2552      // Turn this into a bit convert of the packed input.
2553      Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0),
2554                           PackVectorOp(Node->getOperand(0), TVT));
2555      break;
2556    } else if (NumElems == 1) {
2557      // Turn this into a bit convert of the scalar input.
2558      Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0),
2559                           PackVectorOp(Node->getOperand(0), EVT));
2560      break;
2561    } else {
2562      // FIXME: UNIMP!  Store then reload
2563      assert(0 && "Cast from unsupported vector type not implemented yet!");
2564    }
2565  }
2566
2567    // Conversion operators.  The source and destination have different types.
2568  case ISD::SINT_TO_FP:
2569  case ISD::UINT_TO_FP: {
2570    bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
2571    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2572    case Legal:
2573      switch (TLI.getOperationAction(Node->getOpcode(),
2574                                     Node->getOperand(0).getValueType())) {
2575      default: assert(0 && "Unknown operation action!");
2576      case TargetLowering::Custom:
2577        isCustom = true;
2578        // FALLTHROUGH
2579      case TargetLowering::Legal:
2580        Tmp1 = LegalizeOp(Node->getOperand(0));
2581        Result = DAG.UpdateNodeOperands(Result, Tmp1);
2582        if (isCustom) {
2583          Tmp1 = TLI.LowerOperation(Result, DAG);
2584          if (Tmp1.Val) Result = Tmp1;
2585        }
2586        break;
2587      case TargetLowering::Expand:
2588        Result = ExpandLegalINT_TO_FP(isSigned,
2589                                      LegalizeOp(Node->getOperand(0)),
2590                                      Node->getValueType(0));
2591        break;
2592      case TargetLowering::Promote:
2593        Result = PromoteLegalINT_TO_FP(LegalizeOp(Node->getOperand(0)),
2594                                       Node->getValueType(0),
2595                                       isSigned);
2596        break;
2597      }
2598      break;
2599    case Expand:
2600      Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP,
2601                             Node->getValueType(0), Node->getOperand(0));
2602      break;
2603    case Promote:
2604      Tmp1 = PromoteOp(Node->getOperand(0));
2605      if (isSigned) {
2606        Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, Tmp1.getValueType(),
2607                 Tmp1, DAG.getValueType(Node->getOperand(0).getValueType()));
2608      } else {
2609        Tmp1 = DAG.getZeroExtendInReg(Tmp1,
2610                                      Node->getOperand(0).getValueType());
2611      }
2612      Result = DAG.UpdateNodeOperands(Result, Tmp1);
2613      Result = LegalizeOp(Result);  // The 'op' is not necessarily legal!
2614      break;
2615    }
2616    break;
2617  }
2618  case ISD::TRUNCATE:
2619    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2620    case Legal:
2621      Tmp1 = LegalizeOp(Node->getOperand(0));
2622      Result = DAG.UpdateNodeOperands(Result, Tmp1);
2623      break;
2624    case Expand:
2625      ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
2626
2627      // Since the result is legal, we should just be able to truncate the low
2628      // part of the source.
2629      Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
2630      break;
2631    case Promote:
2632      Result = PromoteOp(Node->getOperand(0));
2633      Result = DAG.getNode(ISD::TRUNCATE, Op.getValueType(), Result);
2634      break;
2635    }
2636    break;
2637
2638  case ISD::FP_TO_SINT:
2639  case ISD::FP_TO_UINT:
2640    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2641    case Legal:
2642      Tmp1 = LegalizeOp(Node->getOperand(0));
2643
2644      switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))){
2645      default: assert(0 && "Unknown operation action!");
2646      case TargetLowering::Custom:
2647        isCustom = true;
2648        // FALLTHROUGH
2649      case TargetLowering::Legal:
2650        Result = DAG.UpdateNodeOperands(Result, Tmp1);
2651        if (isCustom) {
2652          Tmp1 = TLI.LowerOperation(Result, DAG);
2653          if (Tmp1.Val) Result = Tmp1;
2654        }
2655        break;
2656      case TargetLowering::Promote:
2657        Result = PromoteLegalFP_TO_INT(Tmp1, Node->getValueType(0),
2658                                       Node->getOpcode() == ISD::FP_TO_SINT);
2659        break;
2660      case TargetLowering::Expand:
2661        if (Node->getOpcode() == ISD::FP_TO_UINT) {
2662          SDOperand True, False;
2663          MVT::ValueType VT =  Node->getOperand(0).getValueType();
2664          MVT::ValueType NVT = Node->getValueType(0);
2665          unsigned ShiftAmt = MVT::getSizeInBits(Node->getValueType(0))-1;
2666          Tmp2 = DAG.getConstantFP((double)(1ULL << ShiftAmt), VT);
2667          Tmp3 = DAG.getSetCC(TLI.getSetCCResultTy(),
2668                            Node->getOperand(0), Tmp2, ISD::SETLT);
2669          True = DAG.getNode(ISD::FP_TO_SINT, NVT, Node->getOperand(0));
2670          False = DAG.getNode(ISD::FP_TO_SINT, NVT,
2671                              DAG.getNode(ISD::FSUB, VT, Node->getOperand(0),
2672                                          Tmp2));
2673          False = DAG.getNode(ISD::XOR, NVT, False,
2674                              DAG.getConstant(1ULL << ShiftAmt, NVT));
2675          Result = DAG.getNode(ISD::SELECT, NVT, Tmp3, True, False);
2676          break;
2677        } else {
2678          assert(0 && "Do not know how to expand FP_TO_SINT yet!");
2679        }
2680        break;
2681      }
2682      break;
2683    case Expand:
2684      assert(0 && "Shouldn't need to expand other operators here!");
2685    case Promote:
2686      Tmp1 = PromoteOp(Node->getOperand(0));
2687      Result = DAG.UpdateNodeOperands(Result, LegalizeOp(Tmp1));
2688      Result = LegalizeOp(Result);
2689      break;
2690    }
2691    break;
2692
2693  case ISD::ANY_EXTEND:
2694  case ISD::ZERO_EXTEND:
2695  case ISD::SIGN_EXTEND:
2696  case ISD::FP_EXTEND:
2697  case ISD::FP_ROUND:
2698    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2699    case Expand: assert(0 && "Shouldn't need to expand other operators here!");
2700    case Legal:
2701      Tmp1 = LegalizeOp(Node->getOperand(0));
2702      Result = DAG.UpdateNodeOperands(Result, Tmp1);
2703      break;
2704    case Promote:
2705      switch (Node->getOpcode()) {
2706      case ISD::ANY_EXTEND:
2707        Tmp1 = PromoteOp(Node->getOperand(0));
2708        Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Tmp1);
2709        break;
2710      case ISD::ZERO_EXTEND:
2711        Result = PromoteOp(Node->getOperand(0));
2712        Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
2713        Result = DAG.getZeroExtendInReg(Result,
2714                                        Node->getOperand(0).getValueType());
2715        break;
2716      case ISD::SIGN_EXTEND:
2717        Result = PromoteOp(Node->getOperand(0));
2718        Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
2719        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2720                             Result,
2721                          DAG.getValueType(Node->getOperand(0).getValueType()));
2722        break;
2723      case ISD::FP_EXTEND:
2724        Result = PromoteOp(Node->getOperand(0));
2725        if (Result.getValueType() != Op.getValueType())
2726          // Dynamically dead while we have only 2 FP types.
2727          Result = DAG.getNode(ISD::FP_EXTEND, Op.getValueType(), Result);
2728        break;
2729      case ISD::FP_ROUND:
2730        Result = PromoteOp(Node->getOperand(0));
2731        Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
2732        break;
2733      }
2734    }
2735    break;
2736  case ISD::FP_ROUND_INREG:
2737  case ISD::SIGN_EXTEND_INREG: {
2738    Tmp1 = LegalizeOp(Node->getOperand(0));
2739    MVT::ValueType ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2740
2741    // If this operation is not supported, convert it to a shl/shr or load/store
2742    // pair.
2743    switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
2744    default: assert(0 && "This action not supported for this op yet!");
2745    case TargetLowering::Legal:
2746      Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
2747      break;
2748    case TargetLowering::Expand:
2749      // If this is an integer extend and shifts are supported, do that.
2750      if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
2751        // NOTE: we could fall back on load/store here too for targets without
2752        // SAR.  However, it is doubtful that any exist.
2753        unsigned BitsDiff = MVT::getSizeInBits(Node->getValueType(0)) -
2754                            MVT::getSizeInBits(ExtraVT);
2755        SDOperand ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
2756        Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
2757                             Node->getOperand(0), ShiftCst);
2758        Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
2759                             Result, ShiftCst);
2760      } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
2761        // The only way we can lower this is to turn it into a STORETRUNC,
2762        // EXTLOAD pair, targetting a temporary location (a stack slot).
2763
2764        // NOTE: there is a choice here between constantly creating new stack
2765        // slots and always reusing the same one.  We currently always create
2766        // new ones, as reuse may inhibit scheduling.
2767        const Type *Ty = MVT::getTypeForValueType(ExtraVT);
2768        unsigned TySize = (unsigned)TLI.getTargetData().getTypeSize(Ty);
2769        unsigned Align  = TLI.getTargetData().getTypeAlignment(Ty);
2770        MachineFunction &MF = DAG.getMachineFunction();
2771        int SSFI =
2772          MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
2773        SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
2774        Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, DAG.getEntryNode(),
2775                             Node->getOperand(0), StackSlot,
2776                             DAG.getSrcValue(NULL), DAG.getValueType(ExtraVT));
2777        Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
2778                                Result, StackSlot, DAG.getSrcValue(NULL),
2779                                ExtraVT);
2780      } else {
2781        assert(0 && "Unknown op");
2782      }
2783      break;
2784    }
2785    break;
2786  }
2787  }
2788
2789  assert(Result.getValueType() == Op.getValueType() &&
2790         "Bad legalization!");
2791
2792  // Make sure that the generated code is itself legal.
2793  if (Result != Op)
2794    Result = LegalizeOp(Result);
2795
2796  // Note that LegalizeOp may be reentered even from single-use nodes, which
2797  // means that we always must cache transformed nodes.
2798  AddLegalizedOperand(Op, Result);
2799  return Result;
2800}
2801
2802/// PromoteOp - Given an operation that produces a value in an invalid type,
2803/// promote it to compute the value into a larger type.  The produced value will
2804/// have the correct bits for the low portion of the register, but no guarantee
2805/// is made about the top bits: it may be zero, sign-extended, or garbage.
2806SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
2807  MVT::ValueType VT = Op.getValueType();
2808  MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
2809  assert(getTypeAction(VT) == Promote &&
2810         "Caller should expand or legalize operands that are not promotable!");
2811  assert(NVT > VT && MVT::isInteger(NVT) == MVT::isInteger(VT) &&
2812         "Cannot promote to smaller type!");
2813
2814  SDOperand Tmp1, Tmp2, Tmp3;
2815  SDOperand Result;
2816  SDNode *Node = Op.Val;
2817
2818  std::map<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
2819  if (I != PromotedNodes.end()) return I->second;
2820
2821  switch (Node->getOpcode()) {
2822  case ISD::CopyFromReg:
2823    assert(0 && "CopyFromReg must be legal!");
2824  default:
2825    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
2826    assert(0 && "Do not know how to promote this operator!");
2827    abort();
2828  case ISD::UNDEF:
2829    Result = DAG.getNode(ISD::UNDEF, NVT);
2830    break;
2831  case ISD::Constant:
2832    if (VT != MVT::i1)
2833      Result = DAG.getNode(ISD::SIGN_EXTEND, NVT, Op);
2834    else
2835      Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
2836    assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
2837    break;
2838  case ISD::ConstantFP:
2839    Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
2840    assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
2841    break;
2842
2843  case ISD::SETCC:
2844    assert(isTypeLegal(TLI.getSetCCResultTy()) && "SetCC type is not legal??");
2845    Result = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),Node->getOperand(0),
2846                         Node->getOperand(1), Node->getOperand(2));
2847    break;
2848
2849  case ISD::TRUNCATE:
2850    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2851    case Legal:
2852      Result = LegalizeOp(Node->getOperand(0));
2853      assert(Result.getValueType() >= NVT &&
2854             "This truncation doesn't make sense!");
2855      if (Result.getValueType() > NVT)    // Truncate to NVT instead of VT
2856        Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
2857      break;
2858    case Promote:
2859      // The truncation is not required, because we don't guarantee anything
2860      // about high bits anyway.
2861      Result = PromoteOp(Node->getOperand(0));
2862      break;
2863    case Expand:
2864      ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
2865      // Truncate the low part of the expanded value to the result type
2866      Result = DAG.getNode(ISD::TRUNCATE, NVT, Tmp1);
2867    }
2868    break;
2869  case ISD::SIGN_EXTEND:
2870  case ISD::ZERO_EXTEND:
2871  case ISD::ANY_EXTEND:
2872    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2873    case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
2874    case Legal:
2875      // Input is legal?  Just do extend all the way to the larger type.
2876      Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
2877      break;
2878    case Promote:
2879      // Promote the reg if it's smaller.
2880      Result = PromoteOp(Node->getOperand(0));
2881      // The high bits are not guaranteed to be anything.  Insert an extend.
2882      if (Node->getOpcode() == ISD::SIGN_EXTEND)
2883        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
2884                         DAG.getValueType(Node->getOperand(0).getValueType()));
2885      else if (Node->getOpcode() == ISD::ZERO_EXTEND)
2886        Result = DAG.getZeroExtendInReg(Result,
2887                                        Node->getOperand(0).getValueType());
2888      break;
2889    }
2890    break;
2891  case ISD::BIT_CONVERT:
2892    Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2893    Result = PromoteOp(Result);
2894    break;
2895
2896  case ISD::FP_EXTEND:
2897    assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
2898  case ISD::FP_ROUND:
2899    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2900    case Expand: assert(0 && "BUG: Cannot expand FP regs!");
2901    case Promote:  assert(0 && "Unreachable with 2 FP types!");
2902    case Legal:
2903      // Input is legal?  Do an FP_ROUND_INREG.
2904      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Node->getOperand(0),
2905                           DAG.getValueType(VT));
2906      break;
2907    }
2908    break;
2909
2910  case ISD::SINT_TO_FP:
2911  case ISD::UINT_TO_FP:
2912    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2913    case Legal:
2914      // No extra round required here.
2915      Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
2916      break;
2917
2918    case Promote:
2919      Result = PromoteOp(Node->getOperand(0));
2920      if (Node->getOpcode() == ISD::SINT_TO_FP)
2921        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2922                             Result,
2923                         DAG.getValueType(Node->getOperand(0).getValueType()));
2924      else
2925        Result = DAG.getZeroExtendInReg(Result,
2926                                        Node->getOperand(0).getValueType());
2927      // No extra round required here.
2928      Result = DAG.getNode(Node->getOpcode(), NVT, Result);
2929      break;
2930    case Expand:
2931      Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, NVT,
2932                             Node->getOperand(0));
2933      // Round if we cannot tolerate excess precision.
2934      if (NoExcessFPPrecision)
2935        Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2936                             DAG.getValueType(VT));
2937      break;
2938    }
2939    break;
2940
2941  case ISD::SIGN_EXTEND_INREG:
2942    Result = PromoteOp(Node->getOperand(0));
2943    Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
2944                         Node->getOperand(1));
2945    break;
2946  case ISD::FP_TO_SINT:
2947  case ISD::FP_TO_UINT:
2948    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2949    case Legal:
2950      Tmp1 = Node->getOperand(0);
2951      break;
2952    case Promote:
2953      // The input result is prerounded, so we don't have to do anything
2954      // special.
2955      Tmp1 = PromoteOp(Node->getOperand(0));
2956      break;
2957    case Expand:
2958      assert(0 && "not implemented");
2959    }
2960    // If we're promoting a UINT to a larger size, check to see if the new node
2961    // will be legal.  If it isn't, check to see if FP_TO_SINT is legal, since
2962    // we can use that instead.  This allows us to generate better code for
2963    // FP_TO_UINT for small destination sizes on targets where FP_TO_UINT is not
2964    // legal, such as PowerPC.
2965    if (Node->getOpcode() == ISD::FP_TO_UINT &&
2966        !TLI.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
2967        (TLI.isOperationLegal(ISD::FP_TO_SINT, NVT) ||
2968         TLI.getOperationAction(ISD::FP_TO_SINT, NVT)==TargetLowering::Custom)){
2969      Result = DAG.getNode(ISD::FP_TO_SINT, NVT, Tmp1);
2970    } else {
2971      Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2972    }
2973    break;
2974
2975  case ISD::FABS:
2976  case ISD::FNEG:
2977    Tmp1 = PromoteOp(Node->getOperand(0));
2978    assert(Tmp1.getValueType() == NVT);
2979    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2980    // NOTE: we do not have to do any extra rounding here for
2981    // NoExcessFPPrecision, because we know the input will have the appropriate
2982    // precision, and these operations don't modify precision at all.
2983    break;
2984
2985  case ISD::FSQRT:
2986  case ISD::FSIN:
2987  case ISD::FCOS:
2988    Tmp1 = PromoteOp(Node->getOperand(0));
2989    assert(Tmp1.getValueType() == NVT);
2990    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2991    if (NoExcessFPPrecision)
2992      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2993                           DAG.getValueType(VT));
2994    break;
2995
2996  case ISD::AND:
2997  case ISD::OR:
2998  case ISD::XOR:
2999    // The input may have strange things in the top bits of the registers, but
3000    // these operations don't care.  They may have weird bits going out, but
3001    // that too is okay if they are integer operations.
3002    Tmp1 = PromoteOp(Node->getOperand(0));
3003    Tmp2 = PromoteOp(Node->getOperand(1));
3004    assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
3005    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
3006    break;
3007  case ISD::ADD:
3008  case ISD::SUB:
3009  case ISD::MUL:
3010    // The input may have strange things in the top bits of the registers, but
3011    // these operations don't care.  They may have weird bits going out, but
3012    // that too is okay if they are integer operations.
3013    Tmp1 = PromoteOp(Node->getOperand(0));
3014    Tmp2 = PromoteOp(Node->getOperand(1));
3015    assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
3016    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
3017    break;
3018  case ISD::FADD:
3019  case ISD::FSUB:
3020  case ISD::FMUL:
3021    Tmp1 = PromoteOp(Node->getOperand(0));
3022    Tmp2 = PromoteOp(Node->getOperand(1));
3023    assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
3024    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
3025
3026    // Floating point operations will give excess precision that we may not be
3027    // able to tolerate.  If we DO allow excess precision, just leave it,
3028    // otherwise excise it.
3029    // FIXME: Why would we need to round FP ops more than integer ones?
3030    //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
3031    if (NoExcessFPPrecision)
3032      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
3033                           DAG.getValueType(VT));
3034    break;
3035
3036  case ISD::SDIV:
3037  case ISD::SREM:
3038    // These operators require that their input be sign extended.
3039    Tmp1 = PromoteOp(Node->getOperand(0));
3040    Tmp2 = PromoteOp(Node->getOperand(1));
3041    if (MVT::isInteger(NVT)) {
3042      Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
3043                         DAG.getValueType(VT));
3044      Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
3045                         DAG.getValueType(VT));
3046    }
3047    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
3048
3049    // Perform FP_ROUND: this is probably overly pessimistic.
3050    if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
3051      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
3052                           DAG.getValueType(VT));
3053    break;
3054  case ISD::FDIV:
3055  case ISD::FREM:
3056  case ISD::FCOPYSIGN:
3057    // These operators require that their input be fp extended.
3058    Tmp1 = PromoteOp(Node->getOperand(0));
3059    Tmp2 = PromoteOp(Node->getOperand(1));
3060    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
3061
3062    // Perform FP_ROUND: this is probably overly pessimistic.
3063    if (NoExcessFPPrecision && Node->getOpcode() != ISD::FCOPYSIGN)
3064      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
3065                           DAG.getValueType(VT));
3066    break;
3067
3068  case ISD::UDIV:
3069  case ISD::UREM:
3070    // These operators require that their input be zero extended.
3071    Tmp1 = PromoteOp(Node->getOperand(0));
3072    Tmp2 = PromoteOp(Node->getOperand(1));
3073    assert(MVT::isInteger(NVT) && "Operators don't apply to FP!");
3074    Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
3075    Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
3076    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
3077    break;
3078
3079  case ISD::SHL:
3080    Tmp1 = PromoteOp(Node->getOperand(0));
3081    Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Node->getOperand(1));
3082    break;
3083  case ISD::SRA:
3084    // The input value must be properly sign extended.
3085    Tmp1 = PromoteOp(Node->getOperand(0));
3086    Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
3087                       DAG.getValueType(VT));
3088    Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Node->getOperand(1));
3089    break;
3090  case ISD::SRL:
3091    // The input value must be properly zero extended.
3092    Tmp1 = PromoteOp(Node->getOperand(0));
3093    Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
3094    Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Node->getOperand(1));
3095    break;
3096
3097  case ISD::VAARG:
3098    Tmp1 = Node->getOperand(0);   // Get the chain.
3099    Tmp2 = Node->getOperand(1);   // Get the pointer.
3100    if (TLI.getOperationAction(ISD::VAARG, VT) == TargetLowering::Custom) {
3101      Tmp3 = DAG.getVAArg(VT, Tmp1, Tmp2, Node->getOperand(2));
3102      Result = TLI.CustomPromoteOperation(Tmp3, DAG);
3103    } else {
3104      SDOperand VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2,
3105                                     Node->getOperand(2));
3106      // Increment the pointer, VAList, to the next vaarg
3107      Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList,
3108                         DAG.getConstant(MVT::getSizeInBits(VT)/8,
3109                                         TLI.getPointerTy()));
3110      // Store the incremented VAList to the legalized pointer
3111      Tmp3 = DAG.getNode(ISD::STORE, MVT::Other, VAList.getValue(1), Tmp3, Tmp2,
3112                         Node->getOperand(2));
3113      // Load the actual argument out of the pointer VAList
3114      Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Tmp3, VAList,
3115                              DAG.getSrcValue(0), VT);
3116    }
3117    // Remember that we legalized the chain.
3118    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
3119    break;
3120
3121  case ISD::LOAD:
3122    Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Node->getOperand(0),
3123                            Node->getOperand(1), Node->getOperand(2), VT);
3124    // Remember that we legalized the chain.
3125    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
3126    break;
3127  case ISD::SEXTLOAD:
3128  case ISD::ZEXTLOAD:
3129  case ISD::EXTLOAD:
3130    Result = DAG.getExtLoad(Node->getOpcode(), NVT, Node->getOperand(0),
3131                            Node->getOperand(1), Node->getOperand(2),
3132                            cast<VTSDNode>(Node->getOperand(3))->getVT());
3133    // Remember that we legalized the chain.
3134    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
3135    break;
3136  case ISD::SELECT:
3137    Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
3138    Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
3139    Result = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), Tmp2, Tmp3);
3140    break;
3141  case ISD::SELECT_CC:
3142    Tmp2 = PromoteOp(Node->getOperand(2));   // True
3143    Tmp3 = PromoteOp(Node->getOperand(3));   // False
3144    Result = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
3145                         Node->getOperand(1), Tmp2, Tmp3, Node->getOperand(4));
3146    break;
3147  case ISD::BSWAP:
3148    Tmp1 = Node->getOperand(0);
3149    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
3150    Tmp1 = DAG.getNode(ISD::BSWAP, NVT, Tmp1);
3151    Result = DAG.getNode(ISD::SRL, NVT, Tmp1,
3152                         DAG.getConstant(getSizeInBits(NVT) - getSizeInBits(VT),
3153                                         TLI.getShiftAmountTy()));
3154    break;
3155  case ISD::CTPOP:
3156  case ISD::CTTZ:
3157  case ISD::CTLZ:
3158    // Zero extend the argument
3159    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
3160    // Perform the larger operation, then subtract if needed.
3161    Tmp1 = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
3162    switch(Node->getOpcode()) {
3163    case ISD::CTPOP:
3164      Result = Tmp1;
3165      break;
3166    case ISD::CTTZ:
3167      // if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
3168      Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
3169                          DAG.getConstant(getSizeInBits(NVT), NVT), ISD::SETEQ);
3170      Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
3171                           DAG.getConstant(getSizeInBits(VT), NVT), Tmp1);
3172      break;
3173    case ISD::CTLZ:
3174      //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
3175      Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
3176                           DAG.getConstant(getSizeInBits(NVT) -
3177                                           getSizeInBits(VT), NVT));
3178      break;
3179    }
3180    break;
3181  case ISD::VEXTRACT_VECTOR_ELT:
3182    Result = PromoteOp(LowerVEXTRACT_VECTOR_ELT(Op));
3183    break;
3184  case ISD::EXTRACT_VECTOR_ELT:
3185    Result = PromoteOp(ExpandEXTRACT_VECTOR_ELT(Op));
3186    break;
3187  }
3188
3189  assert(Result.Val && "Didn't set a result!");
3190
3191  // Make sure the result is itself legal.
3192  Result = LegalizeOp(Result);
3193
3194  // Remember that we promoted this!
3195  AddPromotedOperand(Op, Result);
3196  return Result;
3197}
3198
3199/// LowerVEXTRACT_VECTOR_ELT - Lower a VEXTRACT_VECTOR_ELT operation into a
3200/// EXTRACT_VECTOR_ELT operation, to memory operations, or to scalar code based
3201/// on the vector type.  The return type of this matches the element type of the
3202/// vector, which may not be legal for the target.
3203SDOperand SelectionDAGLegalize::LowerVEXTRACT_VECTOR_ELT(SDOperand Op) {
3204  // We know that operand #0 is the Vec vector.  If the index is a constant
3205  // or if the invec is a supported hardware type, we can use it.  Otherwise,
3206  // lower to a store then an indexed load.
3207  SDOperand Vec = Op.getOperand(0);
3208  SDOperand Idx = LegalizeOp(Op.getOperand(1));
3209
3210  SDNode *InVal = Vec.Val;
3211  unsigned NumElems = cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
3212  MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
3213
3214  // Figure out if there is a Packed type corresponding to this Vector
3215  // type.  If so, convert to the packed type.
3216  MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
3217  if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
3218    // Turn this into a packed extract_vector_elt operation.
3219    Vec = PackVectorOp(Vec, TVT);
3220    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Op.getValueType(), Vec, Idx);
3221  } else if (NumElems == 1) {
3222    // This must be an access of the only element.  Return it.
3223    return PackVectorOp(Vec, EVT);
3224  } else if (ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
3225    SDOperand Lo, Hi;
3226    SplitVectorOp(Vec, Lo, Hi);
3227    if (CIdx->getValue() < NumElems/2) {
3228      Vec = Lo;
3229    } else {
3230      Vec = Hi;
3231      Idx = DAG.getConstant(CIdx->getValue() - NumElems/2, Idx.getValueType());
3232    }
3233
3234    // It's now an extract from the appropriate high or low part.  Recurse.
3235    Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
3236    return LowerVEXTRACT_VECTOR_ELT(Op);
3237  } else {
3238    // Variable index case for extract element.
3239    // FIXME: IMPLEMENT STORE/LOAD lowering.  Need alignment of stack slot!!
3240    assert(0 && "unimp!");
3241    return SDOperand();
3242  }
3243}
3244
3245/// ExpandEXTRACT_VECTOR_ELT - Expand an EXTRACT_VECTOR_ELT operation into
3246/// memory traffic.
3247SDOperand SelectionDAGLegalize::ExpandEXTRACT_VECTOR_ELT(SDOperand Op) {
3248  SDOperand Vector = Op.getOperand(0);
3249  SDOperand Idx    = Op.getOperand(1);
3250
3251  // If the target doesn't support this, store the value to a temporary
3252  // stack slot, then LOAD the scalar element back out.
3253  SDOperand StackPtr = CreateStackTemporary(Vector.getValueType());
3254  SDOperand Ch = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3255                             Vector, StackPtr, DAG.getSrcValue(NULL));
3256
3257  // Add the offset to the index.
3258  unsigned EltSize = MVT::getSizeInBits(Op.getValueType())/8;
3259  Idx = DAG.getNode(ISD::MUL, Idx.getValueType(), Idx,
3260                    DAG.getConstant(EltSize, Idx.getValueType()));
3261  StackPtr = DAG.getNode(ISD::ADD, Idx.getValueType(), Idx, StackPtr);
3262
3263  return DAG.getLoad(Op.getValueType(), Ch, StackPtr, DAG.getSrcValue(NULL));
3264}
3265
3266
3267/// LegalizeSetCCOperands - Attempts to create a legal LHS and RHS for a SETCC
3268/// with condition CC on the current target.  This usually involves legalizing
3269/// or promoting the arguments.  In the case where LHS and RHS must be expanded,
3270/// there may be no choice but to create a new SetCC node to represent the
3271/// legalized value of setcc lhs, rhs.  In this case, the value is returned in
3272/// LHS, and the SDOperand returned in RHS has a nil SDNode value.
3273void SelectionDAGLegalize::LegalizeSetCCOperands(SDOperand &LHS,
3274                                                 SDOperand &RHS,
3275                                                 SDOperand &CC) {
3276  SDOperand Tmp1, Tmp2, Result;
3277
3278  switch (getTypeAction(LHS.getValueType())) {
3279  case Legal:
3280    Tmp1 = LegalizeOp(LHS);   // LHS
3281    Tmp2 = LegalizeOp(RHS);   // RHS
3282    break;
3283  case Promote:
3284    Tmp1 = PromoteOp(LHS);   // LHS
3285    Tmp2 = PromoteOp(RHS);   // RHS
3286
3287    // If this is an FP compare, the operands have already been extended.
3288    if (MVT::isInteger(LHS.getValueType())) {
3289      MVT::ValueType VT = LHS.getValueType();
3290      MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
3291
3292      // Otherwise, we have to insert explicit sign or zero extends.  Note
3293      // that we could insert sign extends for ALL conditions, but zero extend
3294      // is cheaper on many machines (an AND instead of two shifts), so prefer
3295      // it.
3296      switch (cast<CondCodeSDNode>(CC)->get()) {
3297      default: assert(0 && "Unknown integer comparison!");
3298      case ISD::SETEQ:
3299      case ISD::SETNE:
3300      case ISD::SETUGE:
3301      case ISD::SETUGT:
3302      case ISD::SETULE:
3303      case ISD::SETULT:
3304        // ALL of these operations will work if we either sign or zero extend
3305        // the operands (including the unsigned comparisons!).  Zero extend is
3306        // usually a simpler/cheaper operation, so prefer it.
3307        Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
3308        Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
3309        break;
3310      case ISD::SETGE:
3311      case ISD::SETGT:
3312      case ISD::SETLT:
3313      case ISD::SETLE:
3314        Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
3315                           DAG.getValueType(VT));
3316        Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
3317                           DAG.getValueType(VT));
3318        break;
3319      }
3320    }
3321    break;
3322  case Expand:
3323    SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
3324    ExpandOp(LHS, LHSLo, LHSHi);
3325    ExpandOp(RHS, RHSLo, RHSHi);
3326    switch (cast<CondCodeSDNode>(CC)->get()) {
3327    case ISD::SETEQ:
3328    case ISD::SETNE:
3329      if (RHSLo == RHSHi)
3330        if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo))
3331          if (RHSCST->isAllOnesValue()) {
3332            // Comparison to -1.
3333            Tmp1 = DAG.getNode(ISD::AND, LHSLo.getValueType(), LHSLo, LHSHi);
3334            Tmp2 = RHSLo;
3335            break;
3336          }
3337
3338      Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
3339      Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
3340      Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
3341      Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
3342      break;
3343    default:
3344      // If this is a comparison of the sign bit, just look at the top part.
3345      // X > -1,  x < 0
3346      if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(RHS))
3347        if ((cast<CondCodeSDNode>(CC)->get() == ISD::SETLT &&
3348             CST->getValue() == 0) ||             // X < 0
3349            (cast<CondCodeSDNode>(CC)->get() == ISD::SETGT &&
3350             CST->isAllOnesValue())) {            // X > -1
3351          Tmp1 = LHSHi;
3352          Tmp2 = RHSHi;
3353          break;
3354        }
3355
3356      // FIXME: This generated code sucks.
3357      ISD::CondCode LowCC;
3358      switch (cast<CondCodeSDNode>(CC)->get()) {
3359      default: assert(0 && "Unknown integer setcc!");
3360      case ISD::SETLT:
3361      case ISD::SETULT: LowCC = ISD::SETULT; break;
3362      case ISD::SETGT:
3363      case ISD::SETUGT: LowCC = ISD::SETUGT; break;
3364      case ISD::SETLE:
3365      case ISD::SETULE: LowCC = ISD::SETULE; break;
3366      case ISD::SETGE:
3367      case ISD::SETUGE: LowCC = ISD::SETUGE; break;
3368      }
3369
3370      // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
3371      // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
3372      // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
3373
3374      // NOTE: on targets without efficient SELECT of bools, we can always use
3375      // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
3376      Tmp1 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSLo, RHSLo, LowCC);
3377      Tmp2 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(), LHSHi, RHSHi, CC);
3378      Result = DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, ISD::SETEQ);
3379      Result = LegalizeOp(DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
3380                                      Result, Tmp1, Tmp2));
3381      Tmp1 = Result;
3382      Tmp2 = SDOperand();
3383    }
3384  }
3385  LHS = Tmp1;
3386  RHS = Tmp2;
3387}
3388
3389/// ExpandBIT_CONVERT - Expand a BIT_CONVERT node into a store/load combination.
3390/// The resultant code need not be legal.  Note that SrcOp is the input operand
3391/// to the BIT_CONVERT, not the BIT_CONVERT node itself.
3392SDOperand SelectionDAGLegalize::ExpandBIT_CONVERT(MVT::ValueType DestVT,
3393                                                  SDOperand SrcOp) {
3394  // Create the stack frame object.
3395  SDOperand FIPtr = CreateStackTemporary(DestVT);
3396
3397  // Emit a store to the stack slot.
3398  SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3399                                SrcOp, FIPtr, DAG.getSrcValue(NULL));
3400  // Result is a load from the stack slot.
3401  return DAG.getLoad(DestVT, Store, FIPtr, DAG.getSrcValue(0));
3402}
3403
3404SDOperand SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
3405  // Create a vector sized/aligned stack slot, store the value to element #0,
3406  // then load the whole vector back out.
3407  SDOperand StackPtr = CreateStackTemporary(Node->getValueType(0));
3408  SDOperand Ch = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3409                             Node->getOperand(0), StackPtr,
3410                             DAG.getSrcValue(NULL));
3411  return DAG.getLoad(Node->getValueType(0), Ch, StackPtr,DAG.getSrcValue(NULL));
3412}
3413
3414
3415/// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
3416/// support the operation, but do support the resultant packed vector type.
3417SDOperand SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
3418
3419  // If the only non-undef value is the low element, turn this into a
3420  // SCALAR_TO_VECTOR node.  If this is { X, X, X, X }, determine X.
3421  unsigned NumElems = Node->getNumOperands();
3422  bool isOnlyLowElement = true;
3423  SDOperand SplatValue = Node->getOperand(0);
3424  std::map<SDOperand, std::vector<unsigned> > Values;
3425  Values[SplatValue].push_back(0);
3426  bool isConstant = true;
3427  if (!isa<ConstantFPSDNode>(SplatValue) && !isa<ConstantSDNode>(SplatValue) &&
3428      SplatValue.getOpcode() != ISD::UNDEF)
3429    isConstant = false;
3430
3431  for (unsigned i = 1; i < NumElems; ++i) {
3432    SDOperand V = Node->getOperand(i);
3433    std::map<SDOperand, std::vector<unsigned> >::iterator I = Values.find(V);
3434    if (I != Values.end())
3435      I->second.push_back(i);
3436    else
3437      Values[V].push_back(i);
3438    if (V.getOpcode() != ISD::UNDEF)
3439      isOnlyLowElement = false;
3440    if (SplatValue != V)
3441      SplatValue = SDOperand(0,0);
3442
3443    // If this isn't a constant element or an undef, we can't use a constant
3444    // pool load.
3445    if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V) &&
3446        V.getOpcode() != ISD::UNDEF)
3447      isConstant = false;
3448  }
3449
3450  if (isOnlyLowElement) {
3451    // If the low element is an undef too, then this whole things is an undef.
3452    if (Node->getOperand(0).getOpcode() == ISD::UNDEF)
3453      return DAG.getNode(ISD::UNDEF, Node->getValueType(0));
3454    // Otherwise, turn this into a scalar_to_vector node.
3455    return DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0),
3456                       Node->getOperand(0));
3457  }
3458
3459  // If all elements are constants, create a load from the constant pool.
3460  if (isConstant) {
3461    MVT::ValueType VT = Node->getValueType(0);
3462    const Type *OpNTy =
3463      MVT::getTypeForValueType(Node->getOperand(0).getValueType());
3464    std::vector<Constant*> CV;
3465    for (unsigned i = 0, e = NumElems; i != e; ++i) {
3466      if (ConstantFPSDNode *V =
3467          dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
3468        CV.push_back(ConstantFP::get(OpNTy, V->getValue()));
3469      } else if (ConstantSDNode *V =
3470                 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
3471        CV.push_back(ConstantUInt::get(OpNTy, V->getValue()));
3472      } else {
3473        assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
3474        CV.push_back(UndefValue::get(OpNTy));
3475      }
3476    }
3477    Constant *CP = ConstantPacked::get(CV);
3478    SDOperand CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
3479    return DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
3480                       DAG.getSrcValue(NULL));
3481  }
3482
3483  if (SplatValue.Val) {   // Splat of one value?
3484    // Build the shuffle constant vector: <0, 0, 0, 0>
3485    MVT::ValueType MaskVT =
3486      MVT::getIntVectorWithNumElements(NumElems);
3487    SDOperand Zero = DAG.getConstant(0, MVT::getVectorBaseType(MaskVT));
3488    std::vector<SDOperand> ZeroVec(NumElems, Zero);
3489    SDOperand SplatMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, ZeroVec);
3490
3491    // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
3492    if (isShuffleLegal(Node->getValueType(0), SplatMask)) {
3493      // Get the splatted value into the low element of a vector register.
3494      SDOperand LowValVec =
3495        DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0), SplatValue);
3496
3497      // Return shuffle(LowValVec, undef, <0,0,0,0>)
3498      return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), LowValVec,
3499                         DAG.getNode(ISD::UNDEF, Node->getValueType(0)),
3500                         SplatMask);
3501    }
3502  }
3503
3504  // If there are only two unique elements, we may be able to turn this into a
3505  // vector shuffle.
3506  if (Values.size() == 2) {
3507    // Build the shuffle constant vector: e.g. <0, 4, 0, 4>
3508    MVT::ValueType MaskVT =
3509      MVT::getIntVectorWithNumElements(NumElems);
3510    std::vector<SDOperand> MaskVec(NumElems);
3511    unsigned i = 0;
3512    for (std::map<SDOperand,std::vector<unsigned> >::iterator I=Values.begin(),
3513           E = Values.end(); I != E; ++I) {
3514      for (std::vector<unsigned>::iterator II = I->second.begin(),
3515             EE = I->second.end(); II != EE; ++II)
3516        MaskVec[*II] = DAG.getConstant(i, MVT::getVectorBaseType(MaskVT));
3517      i += NumElems;
3518    }
3519    SDOperand ShuffleMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
3520
3521    // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
3522    if (TLI.isOperationLegal(ISD::SCALAR_TO_VECTOR, Node->getValueType(0)) &&
3523        isShuffleLegal(Node->getValueType(0), ShuffleMask)) {
3524      std::vector<SDOperand> Ops;
3525      for(std::map<SDOperand,std::vector<unsigned> >::iterator I=Values.begin(),
3526            E = Values.end(); I != E; ++I) {
3527        SDOperand Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0),
3528                                   I->first);
3529        Ops.push_back(Op);
3530      }
3531      Ops.push_back(ShuffleMask);
3532
3533      // Return shuffle(LoValVec, HiValVec, <0,1,0,1>)
3534      return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), Ops);
3535    }
3536  }
3537
3538  // Otherwise, we can't handle this case efficiently.  Allocate a sufficiently
3539  // aligned object on the stack, store each element into it, then load
3540  // the result as a vector.
3541  MVT::ValueType VT = Node->getValueType(0);
3542  // Create the stack frame object.
3543  SDOperand FIPtr = CreateStackTemporary(VT);
3544
3545  // Emit a store of each element to the stack slot.
3546  std::vector<SDOperand> Stores;
3547  unsigned TypeByteSize =
3548    MVT::getSizeInBits(Node->getOperand(0).getValueType())/8;
3549  unsigned VectorSize = MVT::getSizeInBits(VT)/8;
3550  // Store (in the right endianness) the elements to memory.
3551  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
3552    // Ignore undef elements.
3553    if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
3554
3555    unsigned Offset = TypeByteSize*i;
3556
3557    SDOperand Idx = DAG.getConstant(Offset, FIPtr.getValueType());
3558    Idx = DAG.getNode(ISD::ADD, FIPtr.getValueType(), FIPtr, Idx);
3559
3560    Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3561                                 Node->getOperand(i), Idx,
3562                                 DAG.getSrcValue(NULL)));
3563  }
3564
3565  SDOperand StoreChain;
3566  if (!Stores.empty())    // Not all undef elements?
3567    StoreChain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores);
3568  else
3569    StoreChain = DAG.getEntryNode();
3570
3571  // Result is a load from the stack slot.
3572  return DAG.getLoad(VT, StoreChain, FIPtr, DAG.getSrcValue(0));
3573}
3574
3575/// CreateStackTemporary - Create a stack temporary, suitable for holding the
3576/// specified value type.
3577SDOperand SelectionDAGLegalize::CreateStackTemporary(MVT::ValueType VT) {
3578  MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
3579  unsigned ByteSize = MVT::getSizeInBits(VT)/8;
3580  int FrameIdx = FrameInfo->CreateStackObject(ByteSize, ByteSize);
3581  return DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
3582}
3583
3584void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
3585                                            SDOperand Op, SDOperand Amt,
3586                                            SDOperand &Lo, SDOperand &Hi) {
3587  // Expand the subcomponents.
3588  SDOperand LHSL, LHSH;
3589  ExpandOp(Op, LHSL, LHSH);
3590
3591  std::vector<SDOperand> Ops;
3592  Ops.push_back(LHSL);
3593  Ops.push_back(LHSH);
3594  Ops.push_back(Amt);
3595  std::vector<MVT::ValueType> VTs(2, LHSL.getValueType());
3596  Lo = DAG.getNode(NodeOp, VTs, Ops);
3597  Hi = Lo.getValue(1);
3598}
3599
3600
3601/// ExpandShift - Try to find a clever way to expand this shift operation out to
3602/// smaller elements.  If we can't find a way that is more efficient than a
3603/// libcall on this target, return false.  Otherwise, return true with the
3604/// low-parts expanded into Lo and Hi.
3605bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDOperand Op,SDOperand Amt,
3606                                       SDOperand &Lo, SDOperand &Hi) {
3607  assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
3608         "This is not a shift!");
3609
3610  MVT::ValueType NVT = TLI.getTypeToTransformTo(Op.getValueType());
3611  SDOperand ShAmt = LegalizeOp(Amt);
3612  MVT::ValueType ShTy = ShAmt.getValueType();
3613  unsigned VTBits = MVT::getSizeInBits(Op.getValueType());
3614  unsigned NVTBits = MVT::getSizeInBits(NVT);
3615
3616  // Handle the case when Amt is an immediate.  Other cases are currently broken
3617  // and are disabled.
3618  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Amt.Val)) {
3619    unsigned Cst = CN->getValue();
3620    // Expand the incoming operand to be shifted, so that we have its parts
3621    SDOperand InL, InH;
3622    ExpandOp(Op, InL, InH);
3623    switch(Opc) {
3624    case ISD::SHL:
3625      if (Cst > VTBits) {
3626        Lo = DAG.getConstant(0, NVT);
3627        Hi = DAG.getConstant(0, NVT);
3628      } else if (Cst > NVTBits) {
3629        Lo = DAG.getConstant(0, NVT);
3630        Hi = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst-NVTBits,ShTy));
3631      } else if (Cst == NVTBits) {
3632        Lo = DAG.getConstant(0, NVT);
3633        Hi = InL;
3634      } else {
3635        Lo = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst, ShTy));
3636        Hi = DAG.getNode(ISD::OR, NVT,
3637           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(Cst, ShTy)),
3638           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(NVTBits-Cst, ShTy)));
3639      }
3640      return true;
3641    case ISD::SRL:
3642      if (Cst > VTBits) {
3643        Lo = DAG.getConstant(0, NVT);
3644        Hi = DAG.getConstant(0, NVT);
3645      } else if (Cst > NVTBits) {
3646        Lo = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst-NVTBits,ShTy));
3647        Hi = DAG.getConstant(0, NVT);
3648      } else if (Cst == NVTBits) {
3649        Lo = InH;
3650        Hi = DAG.getConstant(0, NVT);
3651      } else {
3652        Lo = DAG.getNode(ISD::OR, NVT,
3653           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
3654           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
3655        Hi = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst, ShTy));
3656      }
3657      return true;
3658    case ISD::SRA:
3659      if (Cst > VTBits) {
3660        Hi = Lo = DAG.getNode(ISD::SRA, NVT, InH,
3661                              DAG.getConstant(NVTBits-1, ShTy));
3662      } else if (Cst > NVTBits) {
3663        Lo = DAG.getNode(ISD::SRA, NVT, InH,
3664                           DAG.getConstant(Cst-NVTBits, ShTy));
3665        Hi = DAG.getNode(ISD::SRA, NVT, InH,
3666                              DAG.getConstant(NVTBits-1, ShTy));
3667      } else if (Cst == NVTBits) {
3668        Lo = InH;
3669        Hi = DAG.getNode(ISD::SRA, NVT, InH,
3670                              DAG.getConstant(NVTBits-1, ShTy));
3671      } else {
3672        Lo = DAG.getNode(ISD::OR, NVT,
3673           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
3674           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
3675        Hi = DAG.getNode(ISD::SRA, NVT, InH, DAG.getConstant(Cst, ShTy));
3676      }
3677      return true;
3678    }
3679  }
3680  return false;
3681}
3682
3683
3684// ExpandLibCall - Expand a node into a call to a libcall.  If the result value
3685// does not fit into a register, return the lo part and set the hi part to the
3686// by-reg argument.  If it does fit into a single register, return the result
3687// and leave the Hi part unset.
3688SDOperand SelectionDAGLegalize::ExpandLibCall(const char *Name, SDNode *Node,
3689                                              SDOperand &Hi) {
3690  assert(!IsLegalizingCall && "Cannot overlap legalization of calls!");
3691  // The input chain to this libcall is the entry node of the function.
3692  // Legalizing the call will automatically add the previous call to the
3693  // dependence.
3694  SDOperand InChain = DAG.getEntryNode();
3695
3696  TargetLowering::ArgListTy Args;
3697  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
3698    MVT::ValueType ArgVT = Node->getOperand(i).getValueType();
3699    const Type *ArgTy = MVT::getTypeForValueType(ArgVT);
3700    Args.push_back(std::make_pair(Node->getOperand(i), ArgTy));
3701  }
3702  SDOperand Callee = DAG.getExternalSymbol(Name, TLI.getPointerTy());
3703
3704  // Splice the libcall in wherever FindInputOutputChains tells us to.
3705  const Type *RetTy = MVT::getTypeForValueType(Node->getValueType(0));
3706  std::pair<SDOperand,SDOperand> CallInfo =
3707    TLI.LowerCallTo(InChain, RetTy, false, CallingConv::C, false,
3708                    Callee, Args, DAG);
3709
3710  // Legalize the call sequence, starting with the chain.  This will advance
3711  // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
3712  // was added by LowerCallTo (guaranteeing proper serialization of calls).
3713  LegalizeOp(CallInfo.second);
3714  SDOperand Result;
3715  switch (getTypeAction(CallInfo.first.getValueType())) {
3716  default: assert(0 && "Unknown thing");
3717  case Legal:
3718    Result = CallInfo.first;
3719    break;
3720  case Expand:
3721    ExpandOp(CallInfo.first, Result, Hi);
3722    break;
3723  }
3724  return Result;
3725}
3726
3727
3728/// ExpandIntToFP - Expand a [US]INT_TO_FP operation, assuming that the
3729/// destination type is legal.
3730SDOperand SelectionDAGLegalize::
3731ExpandIntToFP(bool isSigned, MVT::ValueType DestTy, SDOperand Source) {
3732  assert(isTypeLegal(DestTy) && "Destination type is not legal!");
3733  assert(getTypeAction(Source.getValueType()) == Expand &&
3734         "This is not an expansion!");
3735  assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
3736
3737  if (!isSigned) {
3738    assert(Source.getValueType() == MVT::i64 &&
3739           "This only works for 64-bit -> FP");
3740    // The 64-bit value loaded will be incorrectly if the 'sign bit' of the
3741    // incoming integer is set.  To handle this, we dynamically test to see if
3742    // it is set, and, if so, add a fudge factor.
3743    SDOperand Lo, Hi;
3744    ExpandOp(Source, Lo, Hi);
3745
3746    // If this is unsigned, and not supported, first perform the conversion to
3747    // signed, then adjust the result if the sign bit is set.
3748    SDOperand SignedConv = ExpandIntToFP(true, DestTy,
3749                   DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), Lo, Hi));
3750
3751    SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Hi,
3752                                     DAG.getConstant(0, Hi.getValueType()),
3753                                     ISD::SETLT);
3754    SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
3755    SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
3756                                      SignSet, Four, Zero);
3757    uint64_t FF = 0x5f800000ULL;
3758    if (TLI.isLittleEndian()) FF <<= 32;
3759    static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
3760
3761    SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
3762    CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
3763    SDOperand FudgeInReg;
3764    if (DestTy == MVT::f32)
3765      FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
3766                               DAG.getSrcValue(NULL));
3767    else {
3768      assert(DestTy == MVT::f64 && "Unexpected conversion");
3769      FudgeInReg = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
3770                                  CPIdx, DAG.getSrcValue(NULL), MVT::f32);
3771    }
3772    return DAG.getNode(ISD::FADD, DestTy, SignedConv, FudgeInReg);
3773  }
3774
3775  // Check to see if the target has a custom way to lower this.  If so, use it.
3776  switch (TLI.getOperationAction(ISD::SINT_TO_FP, Source.getValueType())) {
3777  default: assert(0 && "This action not implemented for this operation!");
3778  case TargetLowering::Legal:
3779  case TargetLowering::Expand:
3780    break;   // This case is handled below.
3781  case TargetLowering::Custom: {
3782    SDOperand NV = TLI.LowerOperation(DAG.getNode(ISD::SINT_TO_FP, DestTy,
3783                                                  Source), DAG);
3784    if (NV.Val)
3785      return LegalizeOp(NV);
3786    break;   // The target decided this was legal after all
3787  }
3788  }
3789
3790  // Expand the source, then glue it back together for the call.  We must expand
3791  // the source in case it is shared (this pass of legalize must traverse it).
3792  SDOperand SrcLo, SrcHi;
3793  ExpandOp(Source, SrcLo, SrcHi);
3794  Source = DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), SrcLo, SrcHi);
3795
3796  const char *FnName = 0;
3797  if (DestTy == MVT::f32)
3798    FnName = "__floatdisf";
3799  else {
3800    assert(DestTy == MVT::f64 && "Unknown fp value type!");
3801    FnName = "__floatdidf";
3802  }
3803
3804  Source = DAG.getNode(ISD::SINT_TO_FP, DestTy, Source);
3805  SDOperand UnusedHiPart;
3806  return ExpandLibCall(FnName, Source.Val, UnusedHiPart);
3807}
3808
3809/// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
3810/// INT_TO_FP operation of the specified operand when the target requests that
3811/// we expand it.  At this point, we know that the result and operand types are
3812/// legal for the target.
3813SDOperand SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
3814                                                     SDOperand Op0,
3815                                                     MVT::ValueType DestVT) {
3816  if (Op0.getValueType() == MVT::i32) {
3817    // simple 32-bit [signed|unsigned] integer to float/double expansion
3818
3819    // get the stack frame index of a 8 byte buffer
3820    MachineFunction &MF = DAG.getMachineFunction();
3821    int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
3822    // get address of 8 byte buffer
3823    SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3824    // word offset constant for Hi/Lo address computation
3825    SDOperand WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
3826    // set up Hi and Lo (into buffer) address based on endian
3827    SDOperand Hi = StackSlot;
3828    SDOperand Lo = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot,WordOff);
3829    if (TLI.isLittleEndian())
3830      std::swap(Hi, Lo);
3831
3832    // if signed map to unsigned space
3833    SDOperand Op0Mapped;
3834    if (isSigned) {
3835      // constant used to invert sign bit (signed to unsigned mapping)
3836      SDOperand SignBit = DAG.getConstant(0x80000000u, MVT::i32);
3837      Op0Mapped = DAG.getNode(ISD::XOR, MVT::i32, Op0, SignBit);
3838    } else {
3839      Op0Mapped = Op0;
3840    }
3841    // store the lo of the constructed double - based on integer input
3842    SDOperand Store1 = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3843                                   Op0Mapped, Lo, DAG.getSrcValue(NULL));
3844    // initial hi portion of constructed double
3845    SDOperand InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
3846    // store the hi of the constructed double - biased exponent
3847    SDOperand Store2 = DAG.getNode(ISD::STORE, MVT::Other, Store1,
3848                                   InitialHi, Hi, DAG.getSrcValue(NULL));
3849    // load the constructed double
3850    SDOperand Load = DAG.getLoad(MVT::f64, Store2, StackSlot,
3851                               DAG.getSrcValue(NULL));
3852    // FP constant to bias correct the final result
3853    SDOperand Bias = DAG.getConstantFP(isSigned ?
3854                                            BitsToDouble(0x4330000080000000ULL)
3855                                          : BitsToDouble(0x4330000000000000ULL),
3856                                     MVT::f64);
3857    // subtract the bias
3858    SDOperand Sub = DAG.getNode(ISD::FSUB, MVT::f64, Load, Bias);
3859    // final result
3860    SDOperand Result;
3861    // handle final rounding
3862    if (DestVT == MVT::f64) {
3863      // do nothing
3864      Result = Sub;
3865    } else {
3866     // if f32 then cast to f32
3867      Result = DAG.getNode(ISD::FP_ROUND, MVT::f32, Sub);
3868    }
3869    return Result;
3870  }
3871  assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
3872  SDOperand Tmp1 = DAG.getNode(ISD::SINT_TO_FP, DestVT, Op0);
3873
3874  SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Op0,
3875                                   DAG.getConstant(0, Op0.getValueType()),
3876                                   ISD::SETLT);
3877  SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
3878  SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
3879                                    SignSet, Four, Zero);
3880
3881  // If the sign bit of the integer is set, the large number will be treated
3882  // as a negative number.  To counteract this, the dynamic code adds an
3883  // offset depending on the data type.
3884  uint64_t FF;
3885  switch (Op0.getValueType()) {
3886  default: assert(0 && "Unsupported integer type!");
3887  case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
3888  case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
3889  case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
3890  case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
3891  }
3892  if (TLI.isLittleEndian()) FF <<= 32;
3893  static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
3894
3895  SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
3896  CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
3897  SDOperand FudgeInReg;
3898  if (DestVT == MVT::f32)
3899    FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
3900                             DAG.getSrcValue(NULL));
3901  else {
3902    assert(DestVT == MVT::f64 && "Unexpected conversion");
3903    FudgeInReg = LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, MVT::f64,
3904                                           DAG.getEntryNode(), CPIdx,
3905                                           DAG.getSrcValue(NULL), MVT::f32));
3906  }
3907
3908  return DAG.getNode(ISD::FADD, DestVT, Tmp1, FudgeInReg);
3909}
3910
3911/// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
3912/// *INT_TO_FP operation of the specified operand when the target requests that
3913/// we promote it.  At this point, we know that the result and operand types are
3914/// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
3915/// operation that takes a larger input.
3916SDOperand SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDOperand LegalOp,
3917                                                      MVT::ValueType DestVT,
3918                                                      bool isSigned) {
3919  // First step, figure out the appropriate *INT_TO_FP operation to use.
3920  MVT::ValueType NewInTy = LegalOp.getValueType();
3921
3922  unsigned OpToUse = 0;
3923
3924  // Scan for the appropriate larger type to use.
3925  while (1) {
3926    NewInTy = (MVT::ValueType)(NewInTy+1);
3927    assert(MVT::isInteger(NewInTy) && "Ran out of possibilities!");
3928
3929    // If the target supports SINT_TO_FP of this type, use it.
3930    switch (TLI.getOperationAction(ISD::SINT_TO_FP, NewInTy)) {
3931      default: break;
3932      case TargetLowering::Legal:
3933        if (!TLI.isTypeLegal(NewInTy))
3934          break;  // Can't use this datatype.
3935        // FALL THROUGH.
3936      case TargetLowering::Custom:
3937        OpToUse = ISD::SINT_TO_FP;
3938        break;
3939    }
3940    if (OpToUse) break;
3941    if (isSigned) continue;
3942
3943    // If the target supports UINT_TO_FP of this type, use it.
3944    switch (TLI.getOperationAction(ISD::UINT_TO_FP, NewInTy)) {
3945      default: break;
3946      case TargetLowering::Legal:
3947        if (!TLI.isTypeLegal(NewInTy))
3948          break;  // Can't use this datatype.
3949        // FALL THROUGH.
3950      case TargetLowering::Custom:
3951        OpToUse = ISD::UINT_TO_FP;
3952        break;
3953    }
3954    if (OpToUse) break;
3955
3956    // Otherwise, try a larger type.
3957  }
3958
3959  // Okay, we found the operation and type to use.  Zero extend our input to the
3960  // desired type then run the operation on it.
3961  return DAG.getNode(OpToUse, DestVT,
3962                     DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
3963                                 NewInTy, LegalOp));
3964}
3965
3966/// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
3967/// FP_TO_*INT operation of the specified operand when the target requests that
3968/// we promote it.  At this point, we know that the result and operand types are
3969/// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
3970/// operation that returns a larger result.
3971SDOperand SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDOperand LegalOp,
3972                                                      MVT::ValueType DestVT,
3973                                                      bool isSigned) {
3974  // First step, figure out the appropriate FP_TO*INT operation to use.
3975  MVT::ValueType NewOutTy = DestVT;
3976
3977  unsigned OpToUse = 0;
3978
3979  // Scan for the appropriate larger type to use.
3980  while (1) {
3981    NewOutTy = (MVT::ValueType)(NewOutTy+1);
3982    assert(MVT::isInteger(NewOutTy) && "Ran out of possibilities!");
3983
3984    // If the target supports FP_TO_SINT returning this type, use it.
3985    switch (TLI.getOperationAction(ISD::FP_TO_SINT, NewOutTy)) {
3986    default: break;
3987    case TargetLowering::Legal:
3988      if (!TLI.isTypeLegal(NewOutTy))
3989        break;  // Can't use this datatype.
3990      // FALL THROUGH.
3991    case TargetLowering::Custom:
3992      OpToUse = ISD::FP_TO_SINT;
3993      break;
3994    }
3995    if (OpToUse) break;
3996
3997    // If the target supports FP_TO_UINT of this type, use it.
3998    switch (TLI.getOperationAction(ISD::FP_TO_UINT, NewOutTy)) {
3999    default: break;
4000    case TargetLowering::Legal:
4001      if (!TLI.isTypeLegal(NewOutTy))
4002        break;  // Can't use this datatype.
4003      // FALL THROUGH.
4004    case TargetLowering::Custom:
4005      OpToUse = ISD::FP_TO_UINT;
4006      break;
4007    }
4008    if (OpToUse) break;
4009
4010    // Otherwise, try a larger type.
4011  }
4012
4013  // Okay, we found the operation and type to use.  Truncate the result of the
4014  // extended FP_TO_*INT operation to the desired size.
4015  return DAG.getNode(ISD::TRUNCATE, DestVT,
4016                     DAG.getNode(OpToUse, NewOutTy, LegalOp));
4017}
4018
4019/// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
4020///
4021SDOperand SelectionDAGLegalize::ExpandBSWAP(SDOperand Op) {
4022  MVT::ValueType VT = Op.getValueType();
4023  MVT::ValueType SHVT = TLI.getShiftAmountTy();
4024  SDOperand Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
4025  switch (VT) {
4026  default: assert(0 && "Unhandled Expand type in BSWAP!"); abort();
4027  case MVT::i16:
4028    Tmp2 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
4029    Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
4030    return DAG.getNode(ISD::OR, VT, Tmp1, Tmp2);
4031  case MVT::i32:
4032    Tmp4 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
4033    Tmp3 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
4034    Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
4035    Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
4036    Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
4037    Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(0xFF00, VT));
4038    Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
4039    Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
4040    return DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
4041  case MVT::i64:
4042    Tmp8 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(56, SHVT));
4043    Tmp7 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(40, SHVT));
4044    Tmp6 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
4045    Tmp5 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
4046    Tmp4 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
4047    Tmp3 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
4048    Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(40, SHVT));
4049    Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(56, SHVT));
4050    Tmp7 = DAG.getNode(ISD::AND, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
4051    Tmp6 = DAG.getNode(ISD::AND, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
4052    Tmp5 = DAG.getNode(ISD::AND, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
4053    Tmp4 = DAG.getNode(ISD::AND, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
4054    Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
4055    Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
4056    Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp7);
4057    Tmp6 = DAG.getNode(ISD::OR, VT, Tmp6, Tmp5);
4058    Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
4059    Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
4060    Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp6);
4061    Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
4062    return DAG.getNode(ISD::OR, VT, Tmp8, Tmp4);
4063  }
4064}
4065
4066/// ExpandBitCount - Expand the specified bitcount instruction into operations.
4067///
4068SDOperand SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDOperand Op) {
4069  switch (Opc) {
4070  default: assert(0 && "Cannot expand this yet!");
4071  case ISD::CTPOP: {
4072    static const uint64_t mask[6] = {
4073      0x5555555555555555ULL, 0x3333333333333333ULL,
4074      0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
4075      0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
4076    };
4077    MVT::ValueType VT = Op.getValueType();
4078    MVT::ValueType ShVT = TLI.getShiftAmountTy();
4079    unsigned len = getSizeInBits(VT);
4080    for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
4081      //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
4082      SDOperand Tmp2 = DAG.getConstant(mask[i], VT);
4083      SDOperand Tmp3 = DAG.getConstant(1ULL << i, ShVT);
4084      Op = DAG.getNode(ISD::ADD, VT, DAG.getNode(ISD::AND, VT, Op, Tmp2),
4085                       DAG.getNode(ISD::AND, VT,
4086                                   DAG.getNode(ISD::SRL, VT, Op, Tmp3),Tmp2));
4087    }
4088    return Op;
4089  }
4090  case ISD::CTLZ: {
4091    // for now, we do this:
4092    // x = x | (x >> 1);
4093    // x = x | (x >> 2);
4094    // ...
4095    // x = x | (x >>16);
4096    // x = x | (x >>32); // for 64-bit input
4097    // return popcount(~x);
4098    //
4099    // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
4100    MVT::ValueType VT = Op.getValueType();
4101    MVT::ValueType ShVT = TLI.getShiftAmountTy();
4102    unsigned len = getSizeInBits(VT);
4103    for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
4104      SDOperand Tmp3 = DAG.getConstant(1ULL << i, ShVT);
4105      Op = DAG.getNode(ISD::OR, VT, Op, DAG.getNode(ISD::SRL, VT, Op, Tmp3));
4106    }
4107    Op = DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(~0ULL, VT));
4108    return DAG.getNode(ISD::CTPOP, VT, Op);
4109  }
4110  case ISD::CTTZ: {
4111    // for now, we use: { return popcount(~x & (x - 1)); }
4112    // unless the target has ctlz but not ctpop, in which case we use:
4113    // { return 32 - nlz(~x & (x-1)); }
4114    // see also http://www.hackersdelight.org/HDcode/ntz.cc
4115    MVT::ValueType VT = Op.getValueType();
4116    SDOperand Tmp2 = DAG.getConstant(~0ULL, VT);
4117    SDOperand Tmp3 = DAG.getNode(ISD::AND, VT,
4118                       DAG.getNode(ISD::XOR, VT, Op, Tmp2),
4119                       DAG.getNode(ISD::SUB, VT, Op, DAG.getConstant(1, VT)));
4120    // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
4121    if (!TLI.isOperationLegal(ISD::CTPOP, VT) &&
4122        TLI.isOperationLegal(ISD::CTLZ, VT))
4123      return DAG.getNode(ISD::SUB, VT,
4124                         DAG.getConstant(getSizeInBits(VT), VT),
4125                         DAG.getNode(ISD::CTLZ, VT, Tmp3));
4126    return DAG.getNode(ISD::CTPOP, VT, Tmp3);
4127  }
4128  }
4129}
4130
4131/// ExpandOp - Expand the specified SDOperand into its two component pieces
4132/// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
4133/// LegalizeNodes map is filled in for any results that are not expanded, the
4134/// ExpandedNodes map is filled in for any results that are expanded, and the
4135/// Lo/Hi values are returned.
4136void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
4137  MVT::ValueType VT = Op.getValueType();
4138  MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
4139  SDNode *Node = Op.Val;
4140  assert(getTypeAction(VT) == Expand && "Not an expanded type!");
4141  assert((MVT::isInteger(VT) || VT == MVT::Vector) &&
4142         "Cannot expand FP values!");
4143  assert(((MVT::isInteger(NVT) && NVT < VT) || VT == MVT::Vector) &&
4144         "Cannot expand to FP value or to larger int value!");
4145
4146  // See if we already expanded it.
4147  std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
4148    = ExpandedNodes.find(Op);
4149  if (I != ExpandedNodes.end()) {
4150    Lo = I->second.first;
4151    Hi = I->second.second;
4152    return;
4153  }
4154
4155  switch (Node->getOpcode()) {
4156  case ISD::CopyFromReg:
4157    assert(0 && "CopyFromReg must be legal!");
4158  default:
4159    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
4160    assert(0 && "Do not know how to expand this operator!");
4161    abort();
4162  case ISD::UNDEF:
4163    Lo = DAG.getNode(ISD::UNDEF, NVT);
4164    Hi = DAG.getNode(ISD::UNDEF, NVT);
4165    break;
4166  case ISD::Constant: {
4167    uint64_t Cst = cast<ConstantSDNode>(Node)->getValue();
4168    Lo = DAG.getConstant(Cst, NVT);
4169    Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
4170    break;
4171  }
4172  case ISD::BUILD_PAIR:
4173    // Return the operands.
4174    Lo = Node->getOperand(0);
4175    Hi = Node->getOperand(1);
4176    break;
4177
4178  case ISD::SIGN_EXTEND_INREG:
4179    ExpandOp(Node->getOperand(0), Lo, Hi);
4180    // Sign extend the lo-part.
4181    Hi = DAG.getNode(ISD::SRA, NVT, Lo,
4182                     DAG.getConstant(MVT::getSizeInBits(NVT)-1,
4183                                     TLI.getShiftAmountTy()));
4184    // sext_inreg the low part if needed.
4185    Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Lo, Node->getOperand(1));
4186    break;
4187
4188  case ISD::BSWAP: {
4189    ExpandOp(Node->getOperand(0), Lo, Hi);
4190    SDOperand TempLo = DAG.getNode(ISD::BSWAP, NVT, Hi);
4191    Hi = DAG.getNode(ISD::BSWAP, NVT, Lo);
4192    Lo = TempLo;
4193    break;
4194  }
4195
4196  case ISD::CTPOP:
4197    ExpandOp(Node->getOperand(0), Lo, Hi);
4198    Lo = DAG.getNode(ISD::ADD, NVT,          // ctpop(HL) -> ctpop(H)+ctpop(L)
4199                     DAG.getNode(ISD::CTPOP, NVT, Lo),
4200                     DAG.getNode(ISD::CTPOP, NVT, Hi));
4201    Hi = DAG.getConstant(0, NVT);
4202    break;
4203
4204  case ISD::CTLZ: {
4205    // ctlz (HL) -> ctlz(H) != 32 ? ctlz(H) : (ctlz(L)+32)
4206    ExpandOp(Node->getOperand(0), Lo, Hi);
4207    SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
4208    SDOperand HLZ = DAG.getNode(ISD::CTLZ, NVT, Hi);
4209    SDOperand TopNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), HLZ, BitsC,
4210                                        ISD::SETNE);
4211    SDOperand LowPart = DAG.getNode(ISD::CTLZ, NVT, Lo);
4212    LowPart = DAG.getNode(ISD::ADD, NVT, LowPart, BitsC);
4213
4214    Lo = DAG.getNode(ISD::SELECT, NVT, TopNotZero, HLZ, LowPart);
4215    Hi = DAG.getConstant(0, NVT);
4216    break;
4217  }
4218
4219  case ISD::CTTZ: {
4220    // cttz (HL) -> cttz(L) != 32 ? cttz(L) : (cttz(H)+32)
4221    ExpandOp(Node->getOperand(0), Lo, Hi);
4222    SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
4223    SDOperand LTZ = DAG.getNode(ISD::CTTZ, NVT, Lo);
4224    SDOperand BotNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), LTZ, BitsC,
4225                                        ISD::SETNE);
4226    SDOperand HiPart = DAG.getNode(ISD::CTTZ, NVT, Hi);
4227    HiPart = DAG.getNode(ISD::ADD, NVT, HiPart, BitsC);
4228
4229    Lo = DAG.getNode(ISD::SELECT, NVT, BotNotZero, LTZ, HiPart);
4230    Hi = DAG.getConstant(0, NVT);
4231    break;
4232  }
4233
4234  case ISD::VAARG: {
4235    SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
4236    SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
4237    Lo = DAG.getVAArg(NVT, Ch, Ptr, Node->getOperand(2));
4238    Hi = DAG.getVAArg(NVT, Lo.getValue(1), Ptr, Node->getOperand(2));
4239
4240    // Remember that we legalized the chain.
4241    Hi = LegalizeOp(Hi);
4242    AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
4243    if (!TLI.isLittleEndian())
4244      std::swap(Lo, Hi);
4245    break;
4246  }
4247
4248  case ISD::LOAD: {
4249    SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
4250    SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
4251    Lo = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
4252
4253    // Increment the pointer to the other half.
4254    unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
4255    Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4256                      getIntPtrConstant(IncrementSize));
4257    // FIXME: This creates a bogus srcvalue!
4258    Hi = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
4259
4260    // Build a factor node to remember that this load is independent of the
4261    // other one.
4262    SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
4263                               Hi.getValue(1));
4264
4265    // Remember that we legalized the chain.
4266    AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
4267    if (!TLI.isLittleEndian())
4268      std::swap(Lo, Hi);
4269    break;
4270  }
4271  case ISD::AND:
4272  case ISD::OR:
4273  case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
4274    SDOperand LL, LH, RL, RH;
4275    ExpandOp(Node->getOperand(0), LL, LH);
4276    ExpandOp(Node->getOperand(1), RL, RH);
4277    Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
4278    Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
4279    break;
4280  }
4281  case ISD::SELECT: {
4282    SDOperand LL, LH, RL, RH;
4283    ExpandOp(Node->getOperand(1), LL, LH);
4284    ExpandOp(Node->getOperand(2), RL, RH);
4285    Lo = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LL, RL);
4286    Hi = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LH, RH);
4287    break;
4288  }
4289  case ISD::SELECT_CC: {
4290    SDOperand TL, TH, FL, FH;
4291    ExpandOp(Node->getOperand(2), TL, TH);
4292    ExpandOp(Node->getOperand(3), FL, FH);
4293    Lo = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
4294                     Node->getOperand(1), TL, FL, Node->getOperand(4));
4295    Hi = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
4296                     Node->getOperand(1), TH, FH, Node->getOperand(4));
4297    break;
4298  }
4299  case ISD::SEXTLOAD: {
4300    SDOperand Chain = Node->getOperand(0);
4301    SDOperand Ptr   = Node->getOperand(1);
4302    MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
4303
4304    if (EVT == NVT)
4305      Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
4306    else
4307      Lo = DAG.getExtLoad(ISD::SEXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
4308                          EVT);
4309
4310    // Remember that we legalized the chain.
4311    AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
4312
4313    // The high part is obtained by SRA'ing all but one of the bits of the lo
4314    // part.
4315    unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
4316    Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1,
4317                                                       TLI.getShiftAmountTy()));
4318    break;
4319  }
4320  case ISD::ZEXTLOAD: {
4321    SDOperand Chain = Node->getOperand(0);
4322    SDOperand Ptr   = Node->getOperand(1);
4323    MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
4324
4325    if (EVT == NVT)
4326      Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
4327    else
4328      Lo = DAG.getExtLoad(ISD::ZEXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
4329                          EVT);
4330
4331    // Remember that we legalized the chain.
4332    AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
4333
4334    // The high part is just a zero.
4335    Hi = DAG.getConstant(0, NVT);
4336    break;
4337  }
4338  case ISD::EXTLOAD: {
4339    SDOperand Chain = Node->getOperand(0);
4340    SDOperand Ptr   = Node->getOperand(1);
4341    MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
4342
4343    if (EVT == NVT)
4344      Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
4345    else
4346      Lo = DAG.getExtLoad(ISD::EXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
4347                          EVT);
4348
4349    // Remember that we legalized the chain.
4350    AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
4351
4352    // The high part is undefined.
4353    Hi = DAG.getNode(ISD::UNDEF, NVT);
4354    break;
4355  }
4356  case ISD::ANY_EXTEND:
4357    // The low part is any extension of the input (which degenerates to a copy).
4358    Lo = DAG.getNode(ISD::ANY_EXTEND, NVT, Node->getOperand(0));
4359    // The high part is undefined.
4360    Hi = DAG.getNode(ISD::UNDEF, NVT);
4361    break;
4362  case ISD::SIGN_EXTEND: {
4363    // The low part is just a sign extension of the input (which degenerates to
4364    // a copy).
4365    Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, Node->getOperand(0));
4366
4367    // The high part is obtained by SRA'ing all but one of the bits of the lo
4368    // part.
4369    unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
4370    Hi = DAG.getNode(ISD::SRA, NVT, Lo,
4371                     DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
4372    break;
4373  }
4374  case ISD::ZERO_EXTEND:
4375    // The low part is just a zero extension of the input (which degenerates to
4376    // a copy).
4377    Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
4378
4379    // The high part is just a zero.
4380    Hi = DAG.getConstant(0, NVT);
4381    break;
4382
4383  case ISD::BIT_CONVERT: {
4384    SDOperand Tmp = ExpandBIT_CONVERT(Node->getValueType(0),
4385                                      Node->getOperand(0));
4386    ExpandOp(Tmp, Lo, Hi);
4387    break;
4388  }
4389
4390  case ISD::READCYCLECOUNTER:
4391    assert(TLI.getOperationAction(ISD::READCYCLECOUNTER, VT) ==
4392                 TargetLowering::Custom &&
4393           "Must custom expand ReadCycleCounter");
4394    Lo = TLI.LowerOperation(Op, DAG);
4395    assert(Lo.Val && "Node must be custom expanded!");
4396    Hi = Lo.getValue(1);
4397    AddLegalizedOperand(SDOperand(Node, 1), // Remember we legalized the chain.
4398                        LegalizeOp(Lo.getValue(2)));
4399    break;
4400
4401    // These operators cannot be expanded directly, emit them as calls to
4402    // library functions.
4403  case ISD::FP_TO_SINT:
4404    if (TLI.getOperationAction(ISD::FP_TO_SINT, VT) == TargetLowering::Custom) {
4405      SDOperand Op;
4406      switch (getTypeAction(Node->getOperand(0).getValueType())) {
4407      case Expand: assert(0 && "cannot expand FP!");
4408      case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
4409      case Promote: Op = PromoteOp (Node->getOperand(0)); break;
4410      }
4411
4412      Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_SINT, VT, Op), DAG);
4413
4414      // Now that the custom expander is done, expand the result, which is still
4415      // VT.
4416      if (Op.Val) {
4417        ExpandOp(Op, Lo, Hi);
4418        break;
4419      }
4420    }
4421
4422    if (Node->getOperand(0).getValueType() == MVT::f32)
4423      Lo = ExpandLibCall("__fixsfdi", Node, Hi);
4424    else
4425      Lo = ExpandLibCall("__fixdfdi", Node, Hi);
4426    break;
4427
4428  case ISD::FP_TO_UINT:
4429    if (TLI.getOperationAction(ISD::FP_TO_UINT, VT) == TargetLowering::Custom) {
4430      SDOperand Op;
4431      switch (getTypeAction(Node->getOperand(0).getValueType())) {
4432        case Expand: assert(0 && "cannot expand FP!");
4433        case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
4434        case Promote: Op = PromoteOp (Node->getOperand(0)); break;
4435      }
4436
4437      Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_UINT, VT, Op), DAG);
4438
4439      // Now that the custom expander is done, expand the result.
4440      if (Op.Val) {
4441        ExpandOp(Op, Lo, Hi);
4442        break;
4443      }
4444    }
4445
4446    if (Node->getOperand(0).getValueType() == MVT::f32)
4447      Lo = ExpandLibCall("__fixunssfdi", Node, Hi);
4448    else
4449      Lo = ExpandLibCall("__fixunsdfdi", Node, Hi);
4450    break;
4451
4452  case ISD::SHL: {
4453    // If the target wants custom lowering, do so.
4454    SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
4455    if (TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Custom) {
4456      SDOperand Op = DAG.getNode(ISD::SHL, VT, Node->getOperand(0), ShiftAmt);
4457      Op = TLI.LowerOperation(Op, DAG);
4458      if (Op.Val) {
4459        // Now that the custom expander is done, expand the result, which is
4460        // still VT.
4461        ExpandOp(Op, Lo, Hi);
4462        break;
4463      }
4464    }
4465
4466    // If we can emit an efficient shift operation, do so now.
4467    if (ExpandShift(ISD::SHL, Node->getOperand(0), ShiftAmt, Lo, Hi))
4468      break;
4469
4470    // If this target supports SHL_PARTS, use it.
4471    TargetLowering::LegalizeAction Action =
4472      TLI.getOperationAction(ISD::SHL_PARTS, NVT);
4473    if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
4474        Action == TargetLowering::Custom) {
4475      ExpandShiftParts(ISD::SHL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
4476      break;
4477    }
4478
4479    // Otherwise, emit a libcall.
4480    Lo = ExpandLibCall("__ashldi3", Node, Hi);
4481    break;
4482  }
4483
4484  case ISD::SRA: {
4485    // If the target wants custom lowering, do so.
4486    SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
4487    if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Custom) {
4488      SDOperand Op = DAG.getNode(ISD::SRA, VT, Node->getOperand(0), ShiftAmt);
4489      Op = TLI.LowerOperation(Op, DAG);
4490      if (Op.Val) {
4491        // Now that the custom expander is done, expand the result, which is
4492        // still VT.
4493        ExpandOp(Op, Lo, Hi);
4494        break;
4495      }
4496    }
4497
4498    // If we can emit an efficient shift operation, do so now.
4499    if (ExpandShift(ISD::SRA, Node->getOperand(0), ShiftAmt, Lo, Hi))
4500      break;
4501
4502    // If this target supports SRA_PARTS, use it.
4503    TargetLowering::LegalizeAction Action =
4504      TLI.getOperationAction(ISD::SRA_PARTS, NVT);
4505    if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
4506        Action == TargetLowering::Custom) {
4507      ExpandShiftParts(ISD::SRA_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
4508      break;
4509    }
4510
4511    // Otherwise, emit a libcall.
4512    Lo = ExpandLibCall("__ashrdi3", Node, Hi);
4513    break;
4514  }
4515
4516  case ISD::SRL: {
4517    // If the target wants custom lowering, do so.
4518    SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
4519    if (TLI.getOperationAction(ISD::SRL, VT) == TargetLowering::Custom) {
4520      SDOperand Op = DAG.getNode(ISD::SRL, VT, Node->getOperand(0), ShiftAmt);
4521      Op = TLI.LowerOperation(Op, DAG);
4522      if (Op.Val) {
4523        // Now that the custom expander is done, expand the result, which is
4524        // still VT.
4525        ExpandOp(Op, Lo, Hi);
4526        break;
4527      }
4528    }
4529
4530    // If we can emit an efficient shift operation, do so now.
4531    if (ExpandShift(ISD::SRL, Node->getOperand(0), ShiftAmt, Lo, Hi))
4532      break;
4533
4534    // If this target supports SRL_PARTS, use it.
4535    TargetLowering::LegalizeAction Action =
4536      TLI.getOperationAction(ISD::SRL_PARTS, NVT);
4537    if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
4538        Action == TargetLowering::Custom) {
4539      ExpandShiftParts(ISD::SRL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
4540      break;
4541    }
4542
4543    // Otherwise, emit a libcall.
4544    Lo = ExpandLibCall("__lshrdi3", Node, Hi);
4545    break;
4546  }
4547
4548  case ISD::ADD:
4549  case ISD::SUB: {
4550    // If the target wants to custom expand this, let them.
4551    if (TLI.getOperationAction(Node->getOpcode(), VT) ==
4552            TargetLowering::Custom) {
4553      Op = TLI.LowerOperation(Op, DAG);
4554      if (Op.Val) {
4555        ExpandOp(Op, Lo, Hi);
4556        break;
4557      }
4558    }
4559
4560    // Expand the subcomponents.
4561    SDOperand LHSL, LHSH, RHSL, RHSH;
4562    ExpandOp(Node->getOperand(0), LHSL, LHSH);
4563    ExpandOp(Node->getOperand(1), RHSL, RHSH);
4564    std::vector<MVT::ValueType> VTs;
4565    std::vector<SDOperand> LoOps, HiOps;
4566    VTs.push_back(LHSL.getValueType());
4567    VTs.push_back(MVT::Flag);
4568    LoOps.push_back(LHSL);
4569    LoOps.push_back(RHSL);
4570    HiOps.push_back(LHSH);
4571    HiOps.push_back(RHSH);
4572    if (Node->getOpcode() == ISD::ADD) {
4573      Lo = DAG.getNode(ISD::ADDC, VTs, LoOps);
4574      HiOps.push_back(Lo.getValue(1));
4575      Hi = DAG.getNode(ISD::ADDE, VTs, HiOps);
4576    } else {
4577      Lo = DAG.getNode(ISD::SUBC, VTs, LoOps);
4578      HiOps.push_back(Lo.getValue(1));
4579      Hi = DAG.getNode(ISD::SUBE, VTs, HiOps);
4580    }
4581    break;
4582  }
4583  case ISD::MUL: {
4584    if (TLI.isOperationLegal(ISD::MULHU, NVT)) {
4585      SDOperand LL, LH, RL, RH;
4586      ExpandOp(Node->getOperand(0), LL, LH);
4587      ExpandOp(Node->getOperand(1), RL, RH);
4588      unsigned SH = MVT::getSizeInBits(RH.getValueType())-1;
4589      // MULHS implicitly sign extends its inputs.  Check to see if ExpandOp
4590      // extended the sign bit of the low half through the upper half, and if so
4591      // emit a MULHS instead of the alternate sequence that is valid for any
4592      // i64 x i64 multiply.
4593      if (TLI.isOperationLegal(ISD::MULHS, NVT) &&
4594          // is RH an extension of the sign bit of RL?
4595          RH.getOpcode() == ISD::SRA && RH.getOperand(0) == RL &&
4596          RH.getOperand(1).getOpcode() == ISD::Constant &&
4597          cast<ConstantSDNode>(RH.getOperand(1))->getValue() == SH &&
4598          // is LH an extension of the sign bit of LL?
4599          LH.getOpcode() == ISD::SRA && LH.getOperand(0) == LL &&
4600          LH.getOperand(1).getOpcode() == ISD::Constant &&
4601          cast<ConstantSDNode>(LH.getOperand(1))->getValue() == SH) {
4602        Hi = DAG.getNode(ISD::MULHS, NVT, LL, RL);
4603      } else {
4604        Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
4605        RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
4606        LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
4607        Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
4608        Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
4609      }
4610      Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
4611    } else {
4612      Lo = ExpandLibCall("__muldi3" , Node, Hi);
4613    }
4614    break;
4615  }
4616  case ISD::SDIV: Lo = ExpandLibCall("__divdi3" , Node, Hi); break;
4617  case ISD::UDIV: Lo = ExpandLibCall("__udivdi3", Node, Hi); break;
4618  case ISD::SREM: Lo = ExpandLibCall("__moddi3" , Node, Hi); break;
4619  case ISD::UREM: Lo = ExpandLibCall("__umoddi3", Node, Hi); break;
4620  }
4621
4622  // Make sure the resultant values have been legalized themselves, unless this
4623  // is a type that requires multi-step expansion.
4624  if (getTypeAction(NVT) != Expand && NVT != MVT::isVoid) {
4625    Lo = LegalizeOp(Lo);
4626    Hi = LegalizeOp(Hi);
4627  }
4628
4629  // Remember in a map if the values will be reused later.
4630  bool isNew =
4631    ExpandedNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
4632  assert(isNew && "Value already expanded?!?");
4633}
4634
4635/// SplitVectorOp - Given an operand of MVT::Vector type, break it down into
4636/// two smaller values of MVT::Vector type.
4637void SelectionDAGLegalize::SplitVectorOp(SDOperand Op, SDOperand &Lo,
4638                                         SDOperand &Hi) {
4639  assert(Op.getValueType() == MVT::Vector && "Cannot split non-vector type!");
4640  SDNode *Node = Op.Val;
4641  unsigned NumElements = cast<ConstantSDNode>(*(Node->op_end()-2))->getValue();
4642  assert(NumElements > 1 && "Cannot split a single element vector!");
4643  unsigned NewNumElts = NumElements/2;
4644  SDOperand NewNumEltsNode = DAG.getConstant(NewNumElts, MVT::i32);
4645  SDOperand TypeNode = *(Node->op_end()-1);
4646
4647  // See if we already split it.
4648  std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
4649    = SplitNodes.find(Op);
4650  if (I != SplitNodes.end()) {
4651    Lo = I->second.first;
4652    Hi = I->second.second;
4653    return;
4654  }
4655
4656  switch (Node->getOpcode()) {
4657  default: Node->dump(); assert(0 && "Unhandled operation in SplitVectorOp!");
4658  case ISD::VBUILD_VECTOR: {
4659    std::vector<SDOperand> LoOps(Node->op_begin(), Node->op_begin()+NewNumElts);
4660    LoOps.push_back(NewNumEltsNode);
4661    LoOps.push_back(TypeNode);
4662    Lo = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, LoOps);
4663
4664    std::vector<SDOperand> HiOps(Node->op_begin()+NewNumElts, Node->op_end()-2);
4665    HiOps.push_back(NewNumEltsNode);
4666    HiOps.push_back(TypeNode);
4667    Hi = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, HiOps);
4668    break;
4669  }
4670  case ISD::VADD:
4671  case ISD::VSUB:
4672  case ISD::VMUL:
4673  case ISD::VSDIV:
4674  case ISD::VUDIV:
4675  case ISD::VAND:
4676  case ISD::VOR:
4677  case ISD::VXOR: {
4678    SDOperand LL, LH, RL, RH;
4679    SplitVectorOp(Node->getOperand(0), LL, LH);
4680    SplitVectorOp(Node->getOperand(1), RL, RH);
4681
4682    Lo = DAG.getNode(Node->getOpcode(), MVT::Vector, LL, RL,
4683                     NewNumEltsNode, TypeNode);
4684    Hi = DAG.getNode(Node->getOpcode(), MVT::Vector, LH, RH,
4685                     NewNumEltsNode, TypeNode);
4686    break;
4687  }
4688  case ISD::VLOAD: {
4689    SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
4690    SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
4691    MVT::ValueType EVT = cast<VTSDNode>(TypeNode)->getVT();
4692
4693    Lo = DAG.getVecLoad(NewNumElts, EVT, Ch, Ptr, Node->getOperand(2));
4694    unsigned IncrementSize = NewNumElts * MVT::getSizeInBits(EVT)/8;
4695    Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4696                      getIntPtrConstant(IncrementSize));
4697    // FIXME: This creates a bogus srcvalue!
4698    Hi = DAG.getVecLoad(NewNumElts, EVT, Ch, Ptr, Node->getOperand(2));
4699
4700    // Build a factor node to remember that this load is independent of the
4701    // other one.
4702    SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
4703                               Hi.getValue(1));
4704
4705    // Remember that we legalized the chain.
4706    AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
4707    break;
4708  }
4709  case ISD::VBIT_CONVERT: {
4710    // We know the result is a vector.  The input may be either a vector or a
4711    // scalar value.
4712    if (Op.getOperand(0).getValueType() != MVT::Vector) {
4713      // Lower to a store/load.  FIXME: this could be improved probably.
4714      SDOperand Ptr = CreateStackTemporary(Op.getOperand(0).getValueType());
4715
4716      SDOperand St = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
4717                                 Op.getOperand(0), Ptr, DAG.getSrcValue(0));
4718      MVT::ValueType EVT = cast<VTSDNode>(TypeNode)->getVT();
4719      St = DAG.getVecLoad(NumElements, EVT, St, Ptr, DAG.getSrcValue(0));
4720      SplitVectorOp(St, Lo, Hi);
4721    } else {
4722      // If the input is a vector type, we have to either scalarize it, pack it
4723      // or convert it based on whether the input vector type is legal.
4724      SDNode *InVal = Node->getOperand(0).Val;
4725      unsigned NumElems =
4726        cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
4727      MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
4728
4729      // If the input is from a single element vector, scalarize the vector,
4730      // then treat like a scalar.
4731      if (NumElems == 1) {
4732        SDOperand Scalar = PackVectorOp(Op.getOperand(0), EVT);
4733        Scalar = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Scalar,
4734                             Op.getOperand(1), Op.getOperand(2));
4735        SplitVectorOp(Scalar, Lo, Hi);
4736      } else {
4737        // Split the input vector.
4738        SplitVectorOp(Op.getOperand(0), Lo, Hi);
4739
4740        // Convert each of the pieces now.
4741        Lo = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Lo,
4742                         NewNumEltsNode, TypeNode);
4743        Hi = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Hi,
4744                         NewNumEltsNode, TypeNode);
4745      }
4746      break;
4747    }
4748  }
4749  }
4750
4751  // Remember in a map if the values will be reused later.
4752  bool isNew =
4753    SplitNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
4754  assert(isNew && "Value already expanded?!?");
4755}
4756
4757
4758/// PackVectorOp - Given an operand of MVT::Vector type, convert it into the
4759/// equivalent operation that returns a scalar (e.g. F32) or packed value
4760/// (e.g. MVT::V4F32).  When this is called, we know that PackedVT is the right
4761/// type for the result.
4762SDOperand SelectionDAGLegalize::PackVectorOp(SDOperand Op,
4763                                             MVT::ValueType NewVT) {
4764  assert(Op.getValueType() == MVT::Vector && "Bad PackVectorOp invocation!");
4765  SDNode *Node = Op.Val;
4766
4767  // See if we already packed it.
4768  std::map<SDOperand, SDOperand>::iterator I = PackedNodes.find(Op);
4769  if (I != PackedNodes.end()) return I->second;
4770
4771  SDOperand Result;
4772  switch (Node->getOpcode()) {
4773  default:
4774    Node->dump(); std::cerr << "\n";
4775    assert(0 && "Unknown vector operation in PackVectorOp!");
4776  case ISD::VADD:
4777  case ISD::VSUB:
4778  case ISD::VMUL:
4779  case ISD::VSDIV:
4780  case ISD::VUDIV:
4781  case ISD::VAND:
4782  case ISD::VOR:
4783  case ISD::VXOR:
4784    Result = DAG.getNode(getScalarizedOpcode(Node->getOpcode(), NewVT),
4785                         NewVT,
4786                         PackVectorOp(Node->getOperand(0), NewVT),
4787                         PackVectorOp(Node->getOperand(1), NewVT));
4788    break;
4789  case ISD::VLOAD: {
4790    SDOperand Ch = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
4791    SDOperand Ptr = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
4792
4793    Result = DAG.getLoad(NewVT, Ch, Ptr, Node->getOperand(2));
4794
4795    // Remember that we legalized the chain.
4796    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4797    break;
4798  }
4799  case ISD::VBUILD_VECTOR:
4800    if (Node->getOperand(0).getValueType() == NewVT) {
4801      // Returning a scalar?
4802      Result = Node->getOperand(0);
4803    } else {
4804      // Returning a BUILD_VECTOR?
4805
4806      // If all elements of the build_vector are undefs, return an undef.
4807      bool AllUndef = true;
4808      for (unsigned i = 0, e = Node->getNumOperands()-2; i != e; ++i)
4809        if (Node->getOperand(i).getOpcode() != ISD::UNDEF) {
4810          AllUndef = false;
4811          break;
4812        }
4813      if (AllUndef) {
4814        Result = DAG.getNode(ISD::UNDEF, NewVT);
4815      } else {
4816        std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end()-2);
4817        Result = DAG.getNode(ISD::BUILD_VECTOR, NewVT, Ops);
4818      }
4819    }
4820    break;
4821  case ISD::VINSERT_VECTOR_ELT:
4822    if (!MVT::isVector(NewVT)) {
4823      // Returning a scalar?  Must be the inserted element.
4824      Result = Node->getOperand(1);
4825    } else {
4826      Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, NewVT,
4827                           PackVectorOp(Node->getOperand(0), NewVT),
4828                           Node->getOperand(1), Node->getOperand(2));
4829    }
4830    break;
4831  case ISD::VVECTOR_SHUFFLE:
4832    if (!MVT::isVector(NewVT)) {
4833      // Returning a scalar?  Figure out if it is the LHS or RHS and return it.
4834      SDOperand EltNum = Node->getOperand(2).getOperand(0);
4835      if (cast<ConstantSDNode>(EltNum)->getValue())
4836        Result = PackVectorOp(Node->getOperand(1), NewVT);
4837      else
4838        Result = PackVectorOp(Node->getOperand(0), NewVT);
4839    } else {
4840      // Otherwise, return a VECTOR_SHUFFLE node.  First convert the index
4841      // vector from a VBUILD_VECTOR to a BUILD_VECTOR.
4842      std::vector<SDOperand> BuildVecIdx(Node->getOperand(2).Val->op_begin(),
4843                                         Node->getOperand(2).Val->op_end()-2);
4844      MVT::ValueType BVT = MVT::getIntVectorWithNumElements(BuildVecIdx.size());
4845      SDOperand BV = DAG.getNode(ISD::BUILD_VECTOR, BVT, BuildVecIdx);
4846
4847      Result = DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT,
4848                           PackVectorOp(Node->getOperand(0), NewVT),
4849                           PackVectorOp(Node->getOperand(1), NewVT), BV);
4850    }
4851    break;
4852  case ISD::VBIT_CONVERT:
4853    if (Op.getOperand(0).getValueType() != MVT::Vector)
4854      Result = DAG.getNode(ISD::BIT_CONVERT, NewVT, Op.getOperand(0));
4855    else {
4856      // If the input is a vector type, we have to either scalarize it, pack it
4857      // or convert it based on whether the input vector type is legal.
4858      SDNode *InVal = Node->getOperand(0).Val;
4859      unsigned NumElems =
4860        cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
4861      MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
4862
4863      // Figure out if there is a Packed type corresponding to this Vector
4864      // type.  If so, convert to the packed type.
4865      MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
4866      if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
4867        // Turn this into a bit convert of the packed input.
4868        Result = DAG.getNode(ISD::BIT_CONVERT, NewVT,
4869                             PackVectorOp(Node->getOperand(0), TVT));
4870        break;
4871      } else if (NumElems == 1) {
4872        // Turn this into a bit convert of the scalar input.
4873        Result = DAG.getNode(ISD::BIT_CONVERT, NewVT,
4874                             PackVectorOp(Node->getOperand(0), EVT));
4875        break;
4876      } else {
4877        // FIXME: UNIMP!
4878        assert(0 && "Cast from unsupported vector type not implemented yet!");
4879      }
4880    }
4881    break;
4882  case ISD::VSELECT:
4883    Result = DAG.getNode(ISD::SELECT, NewVT, Op.getOperand(0),
4884                         PackVectorOp(Op.getOperand(1), NewVT),
4885                         PackVectorOp(Op.getOperand(2), NewVT));
4886    break;
4887  }
4888
4889  if (TLI.isTypeLegal(NewVT))
4890    Result = LegalizeOp(Result);
4891  bool isNew = PackedNodes.insert(std::make_pair(Op, Result)).second;
4892  assert(isNew && "Value already packed?");
4893  return Result;
4894}
4895
4896
4897// SelectionDAG::Legalize - This is the entry point for the file.
4898//
4899void SelectionDAG::Legalize() {
4900  if (ViewLegalizeDAGs) viewGraph();
4901
4902  /// run - This is the main entry point to this class.
4903  ///
4904  SelectionDAGLegalize(*this).LegalizeDAG();
4905}
4906
4907