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