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