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