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