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