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