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