LegalizeDAG.cpp revision c741ea424a290373b24b06b77f161d06f08f7fa7
1//===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the SelectionDAG::Legalize method.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/CodeGen/SelectionDAG.h"
15#include "llvm/CodeGen/MachineFunction.h"
16#include "llvm/CodeGen/MachineFrameInfo.h"
17#include "llvm/Support/MathExtras.h"
18#include "llvm/Target/TargetLowering.h"
19#include "llvm/Target/TargetData.h"
20#include "llvm/Target/TargetOptions.h"
21#include "llvm/CallingConv.h"
22#include "llvm/Constants.h"
23#include <iostream>
24#include <map>
25using namespace llvm;
26
27//===----------------------------------------------------------------------===//
28/// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
29/// hacks on it until the target machine can handle it.  This involves
30/// eliminating value sizes the machine cannot handle (promoting small sizes to
31/// large sizes or splitting up large values into small values) as well as
32/// eliminating operations the machine cannot handle.
33///
34/// This code also does a small amount of optimization and recognition of idioms
35/// as part of its processing.  For example, if a target does not support a
36/// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
37/// will attempt merge setcc and brc instructions into brcc's.
38///
39namespace {
40class SelectionDAGLegalize {
41  TargetLowering &TLI;
42  SelectionDAG &DAG;
43
44  // Libcall insertion helpers.
45
46  /// LastCALLSEQ_END - This keeps track of the CALLSEQ_END node that has been
47  /// legalized.  We use this to ensure that calls are properly serialized
48  /// against each other, including inserted libcalls.
49  SDOperand LastCALLSEQ_END;
50
51  /// IsLegalizingCall - This member is used *only* for purposes of providing
52  /// helpful assertions that a libcall isn't created while another call is
53  /// being legalized (which could lead to non-serialized call sequences).
54  bool IsLegalizingCall;
55
56  enum LegalizeAction {
57    Legal,      // The target natively supports this operation.
58    Promote,    // This operation should be executed in a larger type.
59    Expand,     // Try to expand this to other ops, otherwise use a libcall.
60  };
61
62  /// ValueTypeActions - This is a bitvector that contains two bits for each
63  /// value type, where the two bits correspond to the LegalizeAction enum.
64  /// This can be queried with "getTypeAction(VT)".
65  TargetLowering::ValueTypeActionImpl ValueTypeActions;
66
67  /// LegalizedNodes - For nodes that are of legal width, and that have more
68  /// than one use, this map indicates what regularized operand to use.  This
69  /// allows us to avoid legalizing the same thing more than once.
70  std::map<SDOperand, SDOperand> LegalizedNodes;
71
72  /// PromotedNodes - For nodes that are below legal width, and that have more
73  /// than one use, this map indicates what promoted value to use.  This allows
74  /// us to avoid promoting the same thing more than once.
75  std::map<SDOperand, SDOperand> PromotedNodes;
76
77  /// ExpandedNodes - For nodes that need to be expanded this map indicates
78  /// which which operands are the expanded version of the input.  This allows
79  /// us to avoid expanding the same node more than once.
80  std::map<SDOperand, std::pair<SDOperand, SDOperand> > ExpandedNodes;
81
82  /// SplitNodes - For vector nodes that need to be split, this map indicates
83  /// which which operands are the split version of the input.  This allows us
84  /// to avoid splitting the same node more than once.
85  std::map<SDOperand, std::pair<SDOperand, SDOperand> > SplitNodes;
86
87  /// PackedNodes - For nodes that need to be packed from MVT::Vector types to
88  /// concrete packed types, this contains the mapping of ones we have already
89  /// processed to the result.
90  std::map<SDOperand, SDOperand> PackedNodes;
91
92  void AddLegalizedOperand(SDOperand From, SDOperand To) {
93    LegalizedNodes.insert(std::make_pair(From, To));
94    // If someone requests legalization of the new node, return itself.
95    if (From != To)
96      LegalizedNodes.insert(std::make_pair(To, To));
97  }
98  void AddPromotedOperand(SDOperand From, SDOperand To) {
99    bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
100    assert(isNew && "Got into the map somehow?");
101    // If someone requests legalization of the new node, return itself.
102    LegalizedNodes.insert(std::make_pair(To, To));
103  }
104
105public:
106
107  SelectionDAGLegalize(SelectionDAG &DAG);
108
109  /// getTypeAction - Return how we should legalize values of this type, either
110  /// it is already legal or we need to expand it into multiple registers of
111  /// smaller integer type, or we need to promote it to a larger type.
112  LegalizeAction getTypeAction(MVT::ValueType VT) const {
113    return (LegalizeAction)ValueTypeActions.getTypeAction(VT);
114  }
115
116  /// isTypeLegal - Return true if this type is legal on this target.
117  ///
118  bool isTypeLegal(MVT::ValueType VT) const {
119    return getTypeAction(VT) == Legal;
120  }
121
122  void LegalizeDAG();
123
124private:
125  /// HandleOp - Legalize, Promote, Expand or Pack the specified operand as
126  /// appropriate for its type.
127  void HandleOp(SDOperand Op);
128
129  /// LegalizeOp - We know that the specified value has a legal type.
130  /// Recursively ensure that the operands have legal types, then return the
131  /// result.
132  SDOperand LegalizeOp(SDOperand O);
133
134  /// PromoteOp - Given an operation that produces a value in an invalid type,
135  /// promote it to compute the value into a larger type.  The produced value
136  /// will have the correct bits for the low portion of the register, but no
137  /// guarantee is made about the top bits: it may be zero, sign-extended, or
138  /// garbage.
139  SDOperand PromoteOp(SDOperand O);
140
141  /// ExpandOp - Expand the specified SDOperand into its two component pieces
142  /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this,
143  /// the LegalizeNodes map is filled in for any results that are not expanded,
144  /// the ExpandedNodes map is filled in for any results that are expanded, and
145  /// the Lo/Hi values are returned.   This applies to integer types and Vector
146  /// types.
147  void ExpandOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
148
149  /// SplitVectorOp - Given an operand of MVT::Vector type, break it down into
150  /// two smaller values of MVT::Vector type.
151  void SplitVectorOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
152
153  /// PackVectorOp - Given an operand of MVT::Vector type, convert it into the
154  /// equivalent operation that returns a packed value (e.g. MVT::V4F32).  When
155  /// this is called, we know that PackedVT is the right type for the result and
156  /// we know that this type is legal for the target.
157  SDOperand PackVectorOp(SDOperand O, MVT::ValueType PackedVT);
158
159  bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest);
160
161  void LegalizeSetCCOperands(SDOperand &LHS, SDOperand &RHS, SDOperand &CC);
162
163  SDOperand CreateStackTemporary(MVT::ValueType VT);
164
165  SDOperand ExpandLibCall(const char *Name, SDNode *Node,
166                          SDOperand &Hi);
167  SDOperand ExpandIntToFP(bool isSigned, MVT::ValueType DestTy,
168                          SDOperand Source);
169
170  SDOperand ExpandBIT_CONVERT(MVT::ValueType DestVT, SDOperand SrcOp);
171  SDOperand ExpandBUILD_VECTOR(SDNode *Node);
172  SDOperand ExpandLegalINT_TO_FP(bool isSigned,
173                                 SDOperand LegalOp,
174                                 MVT::ValueType DestVT);
175  SDOperand PromoteLegalINT_TO_FP(SDOperand LegalOp, MVT::ValueType DestVT,
176                                  bool isSigned);
177  SDOperand PromoteLegalFP_TO_INT(SDOperand LegalOp, MVT::ValueType DestVT,
178                                  bool isSigned);
179
180  SDOperand ExpandBSWAP(SDOperand Op);
181  SDOperand ExpandBitCount(unsigned Opc, SDOperand Op);
182  bool ExpandShift(unsigned Opc, SDOperand Op, SDOperand Amt,
183                   SDOperand &Lo, SDOperand &Hi);
184  void ExpandShiftParts(unsigned NodeOp, SDOperand Op, SDOperand Amt,
185                        SDOperand &Lo, SDOperand &Hi);
186
187  SDOperand LowerVEXTRACT_VECTOR_ELT(SDOperand Op);
188
189  SDOperand getIntPtrConstant(uint64_t Val) {
190    return DAG.getConstant(Val, TLI.getPointerTy());
191  }
192};
193}
194
195/// getScalarizedOpcode - Return the scalar opcode that corresponds to the
196/// specified vector opcode.
197static unsigned getScalarizedOpcode(unsigned VecOp, MVT::ValueType VT) {
198  switch (VecOp) {
199  default: assert(0 && "Don't know how to scalarize this opcode!");
200  case ISD::VADD:  return MVT::isInteger(VT) ? ISD::ADD : ISD::FADD;
201  case ISD::VSUB:  return MVT::isInteger(VT) ? ISD::SUB : ISD::FSUB;
202  case ISD::VMUL:  return MVT::isInteger(VT) ? ISD::MUL : ISD::FMUL;
203  case ISD::VSDIV: return MVT::isInteger(VT) ? ISD::SDIV: ISD::FDIV;
204  case ISD::VUDIV: return MVT::isInteger(VT) ? ISD::UDIV: ISD::FDIV;
205  case ISD::VAND:  return MVT::isInteger(VT) ? ISD::AND : 0;
206  case ISD::VOR:   return MVT::isInteger(VT) ? ISD::OR  : 0;
207  case ISD::VXOR:  return MVT::isInteger(VT) ? ISD::XOR : 0;
208  }
209}
210
211SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag)
212  : TLI(dag.getTargetLoweringInfo()), DAG(dag),
213    ValueTypeActions(TLI.getValueTypeActions()) {
214  assert(MVT::LAST_VALUETYPE <= 32 &&
215         "Too many value types for ValueTypeActions to hold!");
216}
217
218/// ComputeTopDownOrdering - Add the specified node to the Order list if it has
219/// not been visited yet and if all of its operands have already been visited.
220static void ComputeTopDownOrdering(SDNode *N, std::vector<SDNode*> &Order,
221                                   std::map<SDNode*, unsigned> &Visited) {
222  if (++Visited[N] != N->getNumOperands())
223    return;  // Haven't visited all operands yet
224
225  Order.push_back(N);
226
227  if (N->hasOneUse()) { // Tail recurse in common case.
228    ComputeTopDownOrdering(*N->use_begin(), Order, Visited);
229    return;
230  }
231
232  // Now that we have N in, add anything that uses it if all of their operands
233  // are now done.
234  for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); UI != E;++UI)
235    ComputeTopDownOrdering(*UI, Order, Visited);
236}
237
238
239void SelectionDAGLegalize::LegalizeDAG() {
240  LastCALLSEQ_END = DAG.getEntryNode();
241  IsLegalizingCall = false;
242
243  // The legalize process is inherently a bottom-up recursive process (users
244  // legalize their uses before themselves).  Given infinite stack space, we
245  // could just start legalizing on the root and traverse the whole graph.  In
246  // practice however, this causes us to run out of stack space on large basic
247  // blocks.  To avoid this problem, compute an ordering of the nodes where each
248  // node is only legalized after all of its operands are legalized.
249  std::map<SDNode*, unsigned> Visited;
250  std::vector<SDNode*> Order;
251
252  // Compute ordering from all of the leaves in the graphs, those (like the
253  // entry node) that have no operands.
254  for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
255       E = DAG.allnodes_end(); I != E; ++I) {
256    if (I->getNumOperands() == 0) {
257      Visited[I] = 0 - 1U;
258      ComputeTopDownOrdering(I, Order, Visited);
259    }
260  }
261
262  assert(Order.size() == Visited.size() &&
263         Order.size() ==
264            (unsigned)std::distance(DAG.allnodes_begin(), DAG.allnodes_end()) &&
265         "Error: DAG is cyclic!");
266  Visited.clear();
267
268  for (unsigned i = 0, e = Order.size(); i != e; ++i)
269    HandleOp(SDOperand(Order[i], 0));
270
271  // Finally, it's possible the root changed.  Get the new root.
272  SDOperand OldRoot = DAG.getRoot();
273  assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
274  DAG.setRoot(LegalizedNodes[OldRoot]);
275
276  ExpandedNodes.clear();
277  LegalizedNodes.clear();
278  PromotedNodes.clear();
279  SplitNodes.clear();
280  PackedNodes.clear();
281
282  // Remove dead nodes now.
283  DAG.RemoveDeadNodes(OldRoot.Val);
284}
285
286
287/// FindCallEndFromCallStart - Given a chained node that is part of a call
288/// sequence, find the CALLSEQ_END node that terminates the call sequence.
289static SDNode *FindCallEndFromCallStart(SDNode *Node) {
290  if (Node->getOpcode() == ISD::CALLSEQ_END)
291    return Node;
292  if (Node->use_empty())
293    return 0;   // No CallSeqEnd
294
295  // The chain is usually at the end.
296  SDOperand TheChain(Node, Node->getNumValues()-1);
297  if (TheChain.getValueType() != MVT::Other) {
298    // Sometimes it's at the beginning.
299    TheChain = SDOperand(Node, 0);
300    if (TheChain.getValueType() != MVT::Other) {
301      // Otherwise, hunt for it.
302      for (unsigned i = 1, e = Node->getNumValues(); i != e; ++i)
303        if (Node->getValueType(i) == MVT::Other) {
304          TheChain = SDOperand(Node, i);
305          break;
306        }
307
308      // Otherwise, we walked into a node without a chain.
309      if (TheChain.getValueType() != MVT::Other)
310        return 0;
311    }
312  }
313
314  for (SDNode::use_iterator UI = Node->use_begin(),
315       E = Node->use_end(); UI != E; ++UI) {
316
317    // Make sure to only follow users of our token chain.
318    SDNode *User = *UI;
319    for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
320      if (User->getOperand(i) == TheChain)
321        if (SDNode *Result = FindCallEndFromCallStart(User))
322          return Result;
323  }
324  return 0;
325}
326
327/// FindCallStartFromCallEnd - Given a chained node that is part of a call
328/// sequence, find the CALLSEQ_START node that initiates the call sequence.
329static SDNode *FindCallStartFromCallEnd(SDNode *Node) {
330  assert(Node && "Didn't find callseq_start for a call??");
331  if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
332
333  assert(Node->getOperand(0).getValueType() == MVT::Other &&
334         "Node doesn't have a token chain argument!");
335  return FindCallStartFromCallEnd(Node->getOperand(0).Val);
336}
337
338/// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking to
339/// see if any uses can reach Dest.  If no dest operands can get to dest,
340/// legalize them, legalize ourself, and return false, otherwise, return true.
341bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N,
342                                                        SDNode *Dest) {
343  if (N == Dest) return true;  // N certainly leads to Dest :)
344
345  // If the first result of this node has been already legalized, then it cannot
346  // reach N.
347  switch (getTypeAction(N->getValueType(0))) {
348  case Legal:
349    if (LegalizedNodes.count(SDOperand(N, 0))) return false;
350    break;
351  case Promote:
352    if (PromotedNodes.count(SDOperand(N, 0))) return false;
353    break;
354  case Expand:
355    if (ExpandedNodes.count(SDOperand(N, 0))) return false;
356    break;
357  }
358
359  // Okay, this node has not already been legalized.  Check and legalize all
360  // operands.  If none lead to Dest, then we can legalize this node.
361  bool OperandsLeadToDest = false;
362  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
363    OperandsLeadToDest |=     // If an operand leads to Dest, so do we.
364      LegalizeAllNodesNotLeadingTo(N->getOperand(i).Val, Dest);
365
366  if (OperandsLeadToDest) return true;
367
368  // Okay, this node looks safe, legalize it and return false.
369  switch (getTypeAction(N->getValueType(0))) {
370  case Legal:
371    LegalizeOp(SDOperand(N, 0));
372    break;
373  case Promote:
374    PromoteOp(SDOperand(N, 0));
375    break;
376  case Expand: {
377    SDOperand X, Y;
378    ExpandOp(SDOperand(N, 0), X, Y);
379    break;
380  }
381  }
382  return false;
383}
384
385/// HandleOp - Legalize, Promote, Expand or Pack the specified operand as
386/// appropriate for its type.
387void SelectionDAGLegalize::HandleOp(SDOperand Op) {
388  switch (getTypeAction(Op.getValueType())) {
389  default: assert(0 && "Bad type action!");
390  case Legal:   LegalizeOp(Op); break;
391  case Promote: PromoteOp(Op);  break;
392  case Expand:
393    if (Op.getValueType() != MVT::Vector) {
394      SDOperand X, Y;
395      ExpandOp(Op, X, Y);
396    } else {
397      SDNode *N = Op.Val;
398      unsigned NumOps = N->getNumOperands();
399      unsigned NumElements =
400        cast<ConstantSDNode>(N->getOperand(NumOps-2))->getValue();
401      MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(NumOps-1))->getVT();
402      MVT::ValueType PackedVT = getVectorType(EVT, NumElements);
403      if (PackedVT != MVT::Other && TLI.isTypeLegal(PackedVT)) {
404        // In the common case, this is a legal vector type, convert it to the
405        // packed operation and type now.
406        PackVectorOp(Op, PackedVT);
407      } else if (NumElements == 1) {
408        // Otherwise, if this is a single element vector, convert it to a
409        // scalar operation.
410        PackVectorOp(Op, EVT);
411      } else {
412        // Otherwise, this is a multiple element vector that isn't supported.
413        // Split it in half and legalize both parts.
414        SDOperand X, Y;
415        SplitVectorOp(Op, X, Y);
416      }
417    }
418    break;
419  }
420}
421
422
423/// LegalizeOp - We know that the specified value has a legal type.
424/// Recursively ensure that the operands have legal types, then return the
425/// result.
426SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
427  assert(isTypeLegal(Op.getValueType()) &&
428         "Caller should expand or promote operands that are not legal!");
429  SDNode *Node = Op.Val;
430
431  // If this operation defines any values that cannot be represented in a
432  // register on this target, make sure to expand or promote them.
433  if (Node->getNumValues() > 1) {
434    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
435      if (getTypeAction(Node->getValueType(i)) != Legal) {
436        HandleOp(Op.getValue(i));
437        assert(LegalizedNodes.count(Op) &&
438               "Handling didn't add legal operands!");
439        return LegalizedNodes[Op];
440      }
441  }
442
443  // Note that LegalizeOp may be reentered even from single-use nodes, which
444  // means that we always must cache transformed nodes.
445  std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
446  if (I != LegalizedNodes.end()) return I->second;
447
448  SDOperand Tmp1, Tmp2, Tmp3, Tmp4;
449  SDOperand Result = Op;
450  bool isCustom = false;
451
452  switch (Node->getOpcode()) {
453  case ISD::FrameIndex:
454  case ISD::EntryToken:
455  case ISD::Register:
456  case ISD::BasicBlock:
457  case ISD::TargetFrameIndex:
458  case ISD::TargetConstant:
459  case ISD::TargetConstantFP:
460  case ISD::TargetConstantPool:
461  case ISD::TargetGlobalAddress:
462  case ISD::TargetExternalSymbol:
463  case ISD::VALUETYPE:
464  case ISD::SRCVALUE:
465  case ISD::STRING:
466  case ISD::CONDCODE:
467    // Primitives must all be legal.
468    assert(TLI.isOperationLegal(Node->getValueType(0), Node->getValueType(0)) &&
469           "This must be legal!");
470    break;
471  default:
472    if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
473      // If this is a target node, legalize it by legalizing the operands then
474      // passing it through.
475      std::vector<SDOperand> Ops;
476      bool Changed = false;
477      for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
478        Ops.push_back(LegalizeOp(Node->getOperand(i)));
479        Changed = Changed || Node->getOperand(i) != Ops.back();
480      }
481      if (Changed)
482        if (Node->getNumValues() == 1)
483          Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Ops);
484        else {
485          std::vector<MVT::ValueType> VTs(Node->value_begin(),
486                                          Node->value_end());
487          Result = DAG.getNode(Node->getOpcode(), VTs, Ops);
488        }
489
490      for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
491        AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
492      return Result.getValue(Op.ResNo);
493    }
494    // Otherwise this is an unhandled builtin node.  splat.
495    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
496    assert(0 && "Do not know how to legalize this operator!");
497    abort();
498  case ISD::GlobalAddress:
499  case ISD::ExternalSymbol:
500  case ISD::ConstantPool:           // Nothing to do.
501    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
502    default: assert(0 && "This action is not supported yet!");
503    case TargetLowering::Custom:
504      Tmp1 = TLI.LowerOperation(Op, DAG);
505      if (Tmp1.Val) Result = Tmp1;
506      // FALLTHROUGH if the target doesn't want to lower this op after all.
507    case TargetLowering::Legal:
508      break;
509    }
510    break;
511  case ISD::AssertSext:
512  case ISD::AssertZext:
513    Tmp1 = LegalizeOp(Node->getOperand(0));
514    Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
515    break;
516  case ISD::MERGE_VALUES:
517    // Legalize eliminates MERGE_VALUES nodes.
518    Result = Node->getOperand(Op.ResNo);
519    break;
520  case ISD::CopyFromReg:
521    Tmp1 = LegalizeOp(Node->getOperand(0));
522    Result = Op.getValue(0);
523    if (Node->getNumValues() == 2) {
524      Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
525    } else {
526      assert(Node->getNumValues() == 3 && "Invalid copyfromreg!");
527      if (Node->getNumOperands() == 3) {
528        Tmp2 = LegalizeOp(Node->getOperand(2));
529        Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
530      } else {
531        Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
532      }
533      AddLegalizedOperand(Op.getValue(2), Result.getValue(2));
534    }
535    // Since CopyFromReg produces two values, make sure to remember that we
536    // legalized both of them.
537    AddLegalizedOperand(Op.getValue(0), Result);
538    AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
539    return Result.getValue(Op.ResNo);
540  case ISD::UNDEF: {
541    MVT::ValueType VT = Op.getValueType();
542    switch (TLI.getOperationAction(ISD::UNDEF, VT)) {
543    default: assert(0 && "This action is not supported yet!");
544    case TargetLowering::Expand:
545      if (MVT::isInteger(VT))
546        Result = DAG.getConstant(0, VT);
547      else if (MVT::isFloatingPoint(VT))
548        Result = DAG.getConstantFP(0, VT);
549      else
550        assert(0 && "Unknown value type!");
551      break;
552    case TargetLowering::Legal:
553      break;
554    }
555    break;
556  }
557
558  case ISD::INTRINSIC_W_CHAIN:
559  case ISD::INTRINSIC_WO_CHAIN:
560  case ISD::INTRINSIC_VOID: {
561    std::vector<SDOperand> Ops;
562    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
563      Ops.push_back(LegalizeOp(Node->getOperand(i)));
564    Result = DAG.UpdateNodeOperands(Result, Ops);
565
566    // Allow the target to custom lower its intrinsics if it wants to.
567    if (TLI.getOperationAction(Node->getOpcode(), MVT::Other) ==
568        TargetLowering::Custom) {
569      Tmp3 = TLI.LowerOperation(Result, DAG);
570      if (Tmp3.Val) Result = Tmp3;
571    }
572
573    if (Result.Val->getNumValues() == 1) break;
574
575    // Must have return value and chain result.
576    assert(Result.Val->getNumValues() == 2 &&
577           "Cannot return more than two values!");
578
579    // Since loads produce two values, make sure to remember that we
580    // legalized both of them.
581    AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
582    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
583    return Result.getValue(Op.ResNo);
584  }
585
586  case ISD::LOCATION:
587    assert(Node->getNumOperands() == 5 && "Invalid LOCATION node!");
588    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the input chain.
589
590    switch (TLI.getOperationAction(ISD::LOCATION, MVT::Other)) {
591    case TargetLowering::Promote:
592    default: assert(0 && "This action is not supported yet!");
593    case TargetLowering::Expand: {
594      MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
595      bool useDEBUG_LOC = TLI.isOperationLegal(ISD::DEBUG_LOC, MVT::Other);
596      bool useDEBUG_LABEL = TLI.isOperationLegal(ISD::DEBUG_LABEL, MVT::Other);
597
598      if (DebugInfo && (useDEBUG_LOC || useDEBUG_LABEL)) {
599        const std::string &FName =
600          cast<StringSDNode>(Node->getOperand(3))->getValue();
601        const std::string &DirName =
602          cast<StringSDNode>(Node->getOperand(4))->getValue();
603        unsigned SrcFile = DebugInfo->RecordSource(DirName, FName);
604
605        std::vector<SDOperand> Ops;
606        Ops.push_back(Tmp1);  // chain
607        SDOperand LineOp = Node->getOperand(1);
608        SDOperand ColOp = Node->getOperand(2);
609
610        if (useDEBUG_LOC) {
611          Ops.push_back(LineOp);  // line #
612          Ops.push_back(ColOp);  // col #
613          Ops.push_back(DAG.getConstant(SrcFile, MVT::i32));  // source file id
614          Result = DAG.getNode(ISD::DEBUG_LOC, MVT::Other, Ops);
615        } else {
616          unsigned Line = cast<ConstantSDNode>(LineOp)->getValue();
617          unsigned Col = cast<ConstantSDNode>(ColOp)->getValue();
618          unsigned ID = DebugInfo->RecordLabel(Line, Col, SrcFile);
619          Ops.push_back(DAG.getConstant(ID, MVT::i32));
620          Result = DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops);
621        }
622      } else {
623        Result = Tmp1;  // chain
624      }
625      break;
626    }
627    case TargetLowering::Legal:
628      if (Tmp1 != Node->getOperand(0) ||
629          getTypeAction(Node->getOperand(1).getValueType()) == Promote) {
630        std::vector<SDOperand> Ops;
631        Ops.push_back(Tmp1);
632        if (getTypeAction(Node->getOperand(1).getValueType()) == Legal) {
633          Ops.push_back(Node->getOperand(1));  // line # must be legal.
634          Ops.push_back(Node->getOperand(2));  // col # must be legal.
635        } else {
636          // Otherwise promote them.
637          Ops.push_back(PromoteOp(Node->getOperand(1)));
638          Ops.push_back(PromoteOp(Node->getOperand(2)));
639        }
640        Ops.push_back(Node->getOperand(3));  // filename must be legal.
641        Ops.push_back(Node->getOperand(4));  // working dir # must be legal.
642        Result = DAG.UpdateNodeOperands(Result, Ops);
643      }
644      break;
645    }
646    break;
647
648  case ISD::DEBUG_LOC:
649    assert(Node->getNumOperands() == 4 && "Invalid DEBUG_LOC node!");
650    switch (TLI.getOperationAction(ISD::DEBUG_LOC, MVT::Other)) {
651    default: assert(0 && "This action is not supported yet!");
652    case TargetLowering::Legal:
653      Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
654      Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the line #.
655      Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the col #.
656      Tmp4 = LegalizeOp(Node->getOperand(3));  // Legalize the source file id.
657      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4);
658      break;
659    }
660    break;
661
662  case ISD::DEBUG_LABEL:
663    assert(Node->getNumOperands() == 2 && "Invalid DEBUG_LABEL node!");
664    switch (TLI.getOperationAction(ISD::DEBUG_LABEL, MVT::Other)) {
665    default: assert(0 && "This action is not supported yet!");
666    case TargetLowering::Legal:
667      Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
668      Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the label id.
669      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
670      break;
671    }
672    break;
673
674  case ISD::Constant:
675    // We know we don't need to expand constants here, constants only have one
676    // value and we check that it is fine above.
677
678    // FIXME: Maybe we should handle things like targets that don't support full
679    // 32-bit immediates?
680    break;
681  case ISD::ConstantFP: {
682    // Spill FP immediates to the constant pool if the target cannot directly
683    // codegen them.  Targets often have some immediate values that can be
684    // efficiently generated into an FP register without a load.  We explicitly
685    // leave these constants as ConstantFP nodes for the target to deal with.
686    ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
687
688    // Check to see if this FP immediate is already legal.
689    bool isLegal = false;
690    for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
691           E = TLI.legal_fpimm_end(); I != E; ++I)
692      if (CFP->isExactlyValue(*I)) {
693        isLegal = true;
694        break;
695      }
696
697    // If this is a legal constant, turn it into a TargetConstantFP node.
698    if (isLegal) {
699      Result = DAG.getTargetConstantFP(CFP->getValue(), CFP->getValueType(0));
700      break;
701    }
702
703    switch (TLI.getOperationAction(ISD::ConstantFP, CFP->getValueType(0))) {
704    default: assert(0 && "This action is not supported yet!");
705    case TargetLowering::Custom:
706      Tmp3 = TLI.LowerOperation(Result, DAG);
707      if (Tmp3.Val) {
708        Result = Tmp3;
709        break;
710      }
711      // FALLTHROUGH
712    case TargetLowering::Expand:
713      // Otherwise we need to spill the constant to memory.
714      bool Extend = false;
715
716      // If a FP immediate is precise when represented as a float and if the
717      // target can do an extending load from float to double, we put it into
718      // the constant pool as a float, even if it's is statically typed as a
719      // double.
720      MVT::ValueType VT = CFP->getValueType(0);
721      bool isDouble = VT == MVT::f64;
722      ConstantFP *LLVMC = ConstantFP::get(isDouble ? Type::DoubleTy :
723                                             Type::FloatTy, CFP->getValue());
724      if (isDouble && CFP->isExactlyValue((float)CFP->getValue()) &&
725          // Only do this if the target has a native EXTLOAD instruction from
726          // f32.
727          TLI.isOperationLegal(ISD::EXTLOAD, MVT::f32)) {
728        LLVMC = cast<ConstantFP>(ConstantExpr::getCast(LLVMC, Type::FloatTy));
729        VT = MVT::f32;
730        Extend = true;
731      }
732
733      SDOperand CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
734      if (Extend) {
735        Result = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
736                                CPIdx, DAG.getSrcValue(NULL), MVT::f32);
737      } else {
738        Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
739                             DAG.getSrcValue(NULL));
740      }
741    }
742    break;
743  }
744  case ISD::TokenFactor:
745    if (Node->getNumOperands() == 2) {
746      Tmp1 = LegalizeOp(Node->getOperand(0));
747      Tmp2 = LegalizeOp(Node->getOperand(1));
748      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
749    } else if (Node->getNumOperands() == 3) {
750      Tmp1 = LegalizeOp(Node->getOperand(0));
751      Tmp2 = LegalizeOp(Node->getOperand(1));
752      Tmp3 = LegalizeOp(Node->getOperand(2));
753      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
754    } else {
755      std::vector<SDOperand> Ops;
756      // Legalize the operands.
757      for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
758        Ops.push_back(LegalizeOp(Node->getOperand(i)));
759      Result = DAG.UpdateNodeOperands(Result, Ops);
760    }
761    break;
762
763  case ISD::BUILD_VECTOR:
764    switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
765    default: assert(0 && "This action is not supported yet!");
766    case TargetLowering::Custom:
767      Tmp3 = TLI.LowerOperation(Result, DAG);
768      if (Tmp3.Val) {
769        Result = Tmp3;
770        break;
771      }
772      // FALLTHROUGH
773    case TargetLowering::Expand:
774      Result = ExpandBUILD_VECTOR(Result.Val);
775      break;
776    }
777    break;
778  case ISD::INSERT_VECTOR_ELT:
779    Tmp1 = LegalizeOp(Node->getOperand(0));  // InVec
780    Tmp2 = LegalizeOp(Node->getOperand(1));  // InVal
781    Tmp3 = LegalizeOp(Node->getOperand(2));  // InEltNo
782    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
783
784    switch (TLI.getOperationAction(ISD::INSERT_VECTOR_ELT,
785                                   Node->getValueType(0))) {
786    default: assert(0 && "This action is not supported yet!");
787    case TargetLowering::Legal:
788      break;
789    case TargetLowering::Custom:
790      Tmp3 = TLI.LowerOperation(Result, DAG);
791      if (Tmp3.Val) {
792        Result = Tmp3;
793        break;
794      }
795      // FALLTHROUGH
796    case TargetLowering::Expand: {
797      // If the target doesn't support this, we have to spill the input vector
798      // to a temporary stack slot, update the element, then reload it.  This is
799      // badness.  We could also load the value into a vector register (either
800      // with a "move to register" or "extload into register" instruction, then
801      // permute it into place, if the idx is a constant and if the idx is
802      // supported by the target.
803      SDOperand StackPtr = CreateStackTemporary(Tmp1.getValueType());
804      // Store the vector.
805      SDOperand Ch = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
806                                 Tmp1, StackPtr, DAG.getSrcValue(NULL));
807
808      // Truncate or zero extend offset to target pointer type.
809      MVT::ValueType IntPtr = TLI.getPointerTy();
810      if (Tmp3.getValueType() > IntPtr)
811        Tmp3 = DAG.getNode(ISD::TRUNCATE, IntPtr, Tmp3);
812      else
813        Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Tmp3);
814
815      // Add the offset to the index.
816      unsigned EltSize = MVT::getSizeInBits(Result.getValueType())/8;
817      Tmp3 = DAG.getNode(ISD::MUL, Tmp3.getValueType(), Tmp3,
818                         DAG.getConstant(EltSize, Tmp3.getValueType()));
819      SDOperand StackPtr2 =
820        DAG.getNode(ISD::ADD, Tmp3.getValueType(), Tmp3, StackPtr);
821      // Store the scalar value.
822      Ch = DAG.getNode(ISD::STORE, MVT::Other, Ch,
823                       Tmp2, StackPtr2, DAG.getSrcValue(NULL));
824      // Load the updated vector.
825      Result = DAG.getLoad(Result.getValueType(), Ch, StackPtr,
826                           DAG.getSrcValue(NULL));
827      break;
828    }
829    }
830    break;
831  case ISD::SCALAR_TO_VECTOR:
832    Tmp1 = LegalizeOp(Node->getOperand(0));  // InVal
833    Result = DAG.UpdateNodeOperands(Result, Tmp1);
834    switch (TLI.getOperationAction(ISD::SCALAR_TO_VECTOR,
835                                   Node->getValueType(0))) {
836    default: assert(0 && "This action is not supported yet!");
837    case TargetLowering::Legal:
838      break;
839    case TargetLowering::Custom:
840      Tmp3 = TLI.LowerOperation(Result, DAG);
841      if (Tmp3.Val) {
842        Result = Tmp3;
843        break;
844      }
845      // FALLTHROUGH
846    case TargetLowering::Expand: {
847      // If the target doesn't support this, store the value to a temporary
848      // stack slot, then EXTLOAD the vector back out.
849      // TODO: If a target doesn't support this, create a stack slot for the
850      // whole vector, then store into it, then load the whole vector.
851      SDOperand StackPtr =
852        CreateStackTemporary(Node->getOperand(0).getValueType());
853      SDOperand Ch = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
854                                 Node->getOperand(0), StackPtr,
855                                 DAG.getSrcValue(NULL));
856      Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0), Ch, StackPtr,
857                              DAG.getSrcValue(NULL),
858                              Node->getOperand(0).getValueType());
859      break;
860    }
861    }
862    break;
863  case ISD::VECTOR_SHUFFLE:
864    assert(TLI.isShuffleLegal(Result.getValueType(), Node->getOperand(2)) &&
865           "vector shuffle should not be created if not legal!");
866    Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the input vectors,
867    Tmp2 = LegalizeOp(Node->getOperand(1));   // but not the shuffle mask.
868    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
869
870    // Allow targets to custom lower the SHUFFLEs they support.
871    if (TLI.getOperationAction(ISD::VECTOR_SHUFFLE, Result.getValueType())
872        == TargetLowering::Custom) {
873      Tmp1 = TLI.LowerOperation(Result, DAG);
874      if (Tmp1.Val) Result = Tmp1;
875    }
876    break;
877
878  case ISD::EXTRACT_VECTOR_ELT:
879    Tmp1 = LegalizeOp(Node->getOperand(0));
880    Tmp2 = LegalizeOp(Node->getOperand(1));
881    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
882
883    switch (TLI.getOperationAction(ISD::EXTRACT_VECTOR_ELT,
884                                   Tmp1.getValueType())) {
885    default: assert(0 && "This action is not supported yet!");
886    case TargetLowering::Legal:
887      break;
888    case TargetLowering::Custom:
889      Tmp3 = TLI.LowerOperation(Result, DAG);
890      if (Tmp3.Val) {
891        Result = Tmp3;
892        break;
893      }
894      // FALLTHROUGH
895    case TargetLowering::Expand: {
896      // If the target doesn't support this, store the value to a temporary
897      // stack slot, then LOAD the scalar element back out.
898      SDOperand StackPtr = CreateStackTemporary(Tmp1.getValueType());
899      SDOperand Ch = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
900                                 Tmp1, StackPtr, DAG.getSrcValue(NULL));
901
902      // Add the offset to the index.
903      unsigned EltSize = MVT::getSizeInBits(Result.getValueType())/8;
904      Tmp2 = DAG.getNode(ISD::MUL, Tmp2.getValueType(), Tmp2,
905                         DAG.getConstant(EltSize, Tmp2.getValueType()));
906      StackPtr = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2, StackPtr);
907
908      Result = DAG.getLoad(Result.getValueType(), Ch, StackPtr,
909                              DAG.getSrcValue(NULL));
910      break;
911    }
912    }
913    break;
914
915  case ISD::VEXTRACT_VECTOR_ELT:
916    Result = LegalizeOp(LowerVEXTRACT_VECTOR_ELT(Op));
917    break;
918
919  case ISD::CALLSEQ_START: {
920    SDNode *CallEnd = FindCallEndFromCallStart(Node);
921
922    // Recursively Legalize all of the inputs of the call end that do not lead
923    // to this call start.  This ensures that any libcalls that need be inserted
924    // are inserted *before* the CALLSEQ_START.
925    for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
926      LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).Val, Node);
927
928    // Now that we legalized all of the inputs (which may have inserted
929    // libcalls) create the new CALLSEQ_START node.
930    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
931
932    // Merge in the last call, to ensure that this call start after the last
933    // call ended.
934    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
935    Tmp1 = LegalizeOp(Tmp1);
936
937    // Do not try to legalize the target-specific arguments (#1+).
938    if (Tmp1 != Node->getOperand(0)) {
939      std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
940      Ops[0] = Tmp1;
941      Result = DAG.UpdateNodeOperands(Result, Ops);
942    }
943
944    // Remember that the CALLSEQ_START is legalized.
945    AddLegalizedOperand(Op.getValue(0), Result);
946    if (Node->getNumValues() == 2)    // If this has a flag result, remember it.
947      AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
948
949    // Now that the callseq_start and all of the non-call nodes above this call
950    // sequence have been legalized, legalize the call itself.  During this
951    // process, no libcalls can/will be inserted, guaranteeing that no calls
952    // can overlap.
953    assert(!IsLegalizingCall && "Inconsistent sequentialization of calls!");
954    SDOperand InCallSEQ = LastCALLSEQ_END;
955    // Note that we are selecting this call!
956    LastCALLSEQ_END = SDOperand(CallEnd, 0);
957    IsLegalizingCall = true;
958
959    // Legalize the call, starting from the CALLSEQ_END.
960    LegalizeOp(LastCALLSEQ_END);
961    assert(!IsLegalizingCall && "CALLSEQ_END should have cleared this!");
962    return Result;
963  }
964  case ISD::CALLSEQ_END:
965    // If the CALLSEQ_START node hasn't been legalized first, legalize it.  This
966    // will cause this node to be legalized as well as handling libcalls right.
967    if (LastCALLSEQ_END.Val != Node) {
968      LegalizeOp(SDOperand(FindCallStartFromCallEnd(Node), 0));
969      std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
970      assert(I != LegalizedNodes.end() &&
971             "Legalizing the call start should have legalized this node!");
972      return I->second;
973    }
974
975    // Otherwise, the call start has been legalized and everything is going
976    // according to plan.  Just legalize ourselves normally here.
977    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
978    // Do not try to legalize the target-specific arguments (#1+), except for
979    // an optional flag input.
980    if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Flag){
981      if (Tmp1 != Node->getOperand(0)) {
982        std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
983        Ops[0] = Tmp1;
984        Result = DAG.UpdateNodeOperands(Result, Ops);
985      }
986    } else {
987      Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
988      if (Tmp1 != Node->getOperand(0) ||
989          Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
990        std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
991        Ops[0] = Tmp1;
992        Ops.back() = Tmp2;
993        Result = DAG.UpdateNodeOperands(Result, Ops);
994      }
995    }
996    assert(IsLegalizingCall && "Call sequence imbalance between start/end?");
997    // This finishes up call legalization.
998    IsLegalizingCall = false;
999
1000    // If the CALLSEQ_END node has a flag, remember that we legalized it.
1001    AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1002    if (Node->getNumValues() == 2)
1003      AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1004    return Result.getValue(Op.ResNo);
1005  case ISD::DYNAMIC_STACKALLOC: {
1006    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1007    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
1008    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
1009    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1010
1011    Tmp1 = Result.getValue(0);
1012    Tmp2 = Result.getValue(1);
1013    switch (TLI.getOperationAction(Node->getOpcode(),
1014                                   Node->getValueType(0))) {
1015    default: assert(0 && "This action is not supported yet!");
1016    case TargetLowering::Expand: {
1017      unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1018      assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1019             " not tell us which reg is the stack pointer!");
1020      SDOperand Chain = Tmp1.getOperand(0);
1021      SDOperand Size  = Tmp2.getOperand(1);
1022      SDOperand SP = DAG.getCopyFromReg(Chain, SPReg, Node->getValueType(0));
1023      Tmp1 = DAG.getNode(ISD::SUB, Node->getValueType(0), SP, Size);    // Value
1024      Tmp2 = DAG.getCopyToReg(SP.getValue(1), SPReg, Tmp1);      // Output chain
1025      Tmp1 = LegalizeOp(Tmp1);
1026      Tmp2 = LegalizeOp(Tmp2);
1027      break;
1028    }
1029    case TargetLowering::Custom:
1030      Tmp3 = TLI.LowerOperation(Tmp1, DAG);
1031      if (Tmp3.Val) {
1032        Tmp1 = LegalizeOp(Tmp3);
1033        Tmp2 = LegalizeOp(Tmp3.getValue(1));
1034      }
1035      break;
1036    case TargetLowering::Legal:
1037      break;
1038    }
1039    // Since this op produce two values, make sure to remember that we
1040    // legalized both of them.
1041    AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1042    AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1043    return Op.ResNo ? Tmp2 : Tmp1;
1044  }
1045  case ISD::INLINEASM:
1046    Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize Chain.
1047    Tmp2 = Node->getOperand(Node->getNumOperands()-1);
1048    if (Tmp2.getValueType() == MVT::Flag)     // Legalize Flag if it exists.
1049      Tmp2 = Tmp3 = SDOperand(0, 0);
1050    else
1051      Tmp3 = LegalizeOp(Tmp2);
1052
1053    if (Tmp1 != Node->getOperand(0) || Tmp2 != Tmp3) {
1054      std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
1055      Ops[0] = Tmp1;
1056      if (Tmp3.Val) Ops.back() = Tmp3;
1057      Result = DAG.UpdateNodeOperands(Result, Ops);
1058    }
1059
1060    // INLINE asm returns a chain and flag, make sure to add both to the map.
1061    AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1062    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1063    return Result.getValue(Op.ResNo);
1064  case ISD::BR:
1065    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1066    // Ensure that libcalls are emitted before a branch.
1067    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1068    Tmp1 = LegalizeOp(Tmp1);
1069    LastCALLSEQ_END = DAG.getEntryNode();
1070
1071    Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1072    break;
1073
1074  case ISD::BRCOND:
1075    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1076    // Ensure that libcalls are emitted before a return.
1077    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1078    Tmp1 = LegalizeOp(Tmp1);
1079    LastCALLSEQ_END = DAG.getEntryNode();
1080
1081    switch (getTypeAction(Node->getOperand(1).getValueType())) {
1082    case Expand: assert(0 && "It's impossible to expand bools");
1083    case Legal:
1084      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
1085      break;
1086    case Promote:
1087      Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
1088      break;
1089    }
1090
1091    // Basic block destination (Op#2) is always legal.
1092    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1093
1094    switch (TLI.getOperationAction(ISD::BRCOND, MVT::Other)) {
1095    default: assert(0 && "This action is not supported yet!");
1096    case TargetLowering::Legal: break;
1097    case TargetLowering::Custom:
1098      Tmp1 = TLI.LowerOperation(Result, DAG);
1099      if (Tmp1.Val) Result = Tmp1;
1100      break;
1101    case TargetLowering::Expand:
1102      // Expand brcond's setcc into its constituent parts and create a BR_CC
1103      // Node.
1104      if (Tmp2.getOpcode() == ISD::SETCC) {
1105        Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Tmp2.getOperand(2),
1106                             Tmp2.getOperand(0), Tmp2.getOperand(1),
1107                             Node->getOperand(2));
1108      } else {
1109        // Make sure the condition is either zero or one.  It may have been
1110        // promoted from something else.
1111        unsigned NumBits = MVT::getSizeInBits(Tmp2.getValueType());
1112        if (!TLI.MaskedValueIsZero(Tmp2, (~0ULL >> (64-NumBits))^1))
1113          Tmp2 = DAG.getZeroExtendInReg(Tmp2, MVT::i1);
1114
1115        Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1,
1116                             DAG.getCondCode(ISD::SETNE), Tmp2,
1117                             DAG.getConstant(0, Tmp2.getValueType()),
1118                             Node->getOperand(2));
1119      }
1120      break;
1121    }
1122    break;
1123  case ISD::BR_CC:
1124    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1125    // Ensure that libcalls are emitted before a branch.
1126    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1127    Tmp1 = LegalizeOp(Tmp1);
1128    LastCALLSEQ_END = DAG.getEntryNode();
1129
1130    Tmp2 = Node->getOperand(2);              // LHS
1131    Tmp3 = Node->getOperand(3);              // RHS
1132    Tmp4 = Node->getOperand(1);              // CC
1133
1134    LegalizeSetCCOperands(Tmp2, Tmp3, Tmp4);
1135
1136    // If we didn't get both a LHS and RHS back from LegalizeSetCCOperands,
1137    // the LHS is a legal SETCC itself.  In this case, we need to compare
1138    // the result against zero to select between true and false values.
1139    if (Tmp3.Val == 0) {
1140      Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
1141      Tmp4 = DAG.getCondCode(ISD::SETNE);
1142    }
1143
1144    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp4, Tmp2, Tmp3,
1145                                    Node->getOperand(4));
1146
1147    switch (TLI.getOperationAction(ISD::BR_CC, Tmp3.getValueType())) {
1148    default: assert(0 && "Unexpected action for BR_CC!");
1149    case TargetLowering::Legal: break;
1150    case TargetLowering::Custom:
1151      Tmp4 = TLI.LowerOperation(Result, DAG);
1152      if (Tmp4.Val) Result = Tmp4;
1153      break;
1154    }
1155    break;
1156  case ISD::LOAD: {
1157    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1158    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1159
1160    MVT::ValueType VT = Node->getValueType(0);
1161    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1162    Tmp2 = Result.getValue(0);
1163    Tmp3 = Result.getValue(1);
1164
1165    switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1166    default: assert(0 && "This action is not supported yet!");
1167    case TargetLowering::Legal: break;
1168    case TargetLowering::Custom:
1169      Tmp1 = TLI.LowerOperation(Tmp2, DAG);
1170      if (Tmp1.Val) {
1171        Tmp2 = LegalizeOp(Tmp1);
1172        Tmp3 = LegalizeOp(Tmp1.getValue(1));
1173      }
1174      break;
1175    }
1176    // Since loads produce two values, make sure to remember that we
1177    // legalized both of them.
1178    AddLegalizedOperand(SDOperand(Node, 0), Tmp2);
1179    AddLegalizedOperand(SDOperand(Node, 1), Tmp3);
1180    return Op.ResNo ? Tmp3 : Tmp2;
1181  }
1182  case ISD::EXTLOAD:
1183  case ISD::SEXTLOAD:
1184  case ISD::ZEXTLOAD: {
1185    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1186    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1187
1188    MVT::ValueType SrcVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
1189    switch (TLI.getOperationAction(Node->getOpcode(), SrcVT)) {
1190    default: assert(0 && "This action is not supported yet!");
1191    case TargetLowering::Promote:
1192      assert(SrcVT == MVT::i1 && "Can only promote EXTLOAD from i1 -> i8!");
1193      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2),
1194                                      DAG.getValueType(MVT::i8));
1195      Tmp1 = Result.getValue(0);
1196      Tmp2 = Result.getValue(1);
1197      break;
1198    case TargetLowering::Custom:
1199      isCustom = true;
1200      // FALLTHROUGH
1201    case TargetLowering::Legal:
1202      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2),
1203                                      Node->getOperand(3));
1204      Tmp1 = Result.getValue(0);
1205      Tmp2 = Result.getValue(1);
1206
1207      if (isCustom) {
1208        Tmp3 = TLI.LowerOperation(Tmp3, DAG);
1209        if (Tmp3.Val) {
1210          Tmp1 = LegalizeOp(Tmp3);
1211          Tmp2 = LegalizeOp(Tmp3.getValue(1));
1212        }
1213      }
1214      break;
1215    case TargetLowering::Expand:
1216      // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
1217      if (SrcVT == MVT::f32 && Node->getValueType(0) == MVT::f64) {
1218        SDOperand Load = DAG.getLoad(SrcVT, Tmp1, Tmp2, Node->getOperand(2));
1219        Result = DAG.getNode(ISD::FP_EXTEND, Node->getValueType(0), Load);
1220        Tmp1 = LegalizeOp(Result);  // Relegalize new nodes.
1221        Tmp2 = LegalizeOp(Load.getValue(1));
1222        break;
1223      }
1224      assert(Node->getOpcode() != ISD::EXTLOAD &&
1225             "EXTLOAD should always be supported!");
1226      // Turn the unsupported load into an EXTLOAD followed by an explicit
1227      // zero/sign extend inreg.
1228      Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
1229                              Tmp1, Tmp2, Node->getOperand(2), SrcVT);
1230      SDOperand ValRes;
1231      if (Node->getOpcode() == ISD::SEXTLOAD)
1232        ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1233                             Result, DAG.getValueType(SrcVT));
1234      else
1235        ValRes = DAG.getZeroExtendInReg(Result, SrcVT);
1236      Tmp1 = LegalizeOp(ValRes);  // Relegalize new nodes.
1237      Tmp2 = LegalizeOp(Result.getValue(1));  // Relegalize new nodes.
1238      break;
1239    }
1240    // Since loads produce two values, make sure to remember that we legalized
1241    // both of them.
1242    AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1243    AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1244    return Op.ResNo ? Tmp2 : Tmp1;
1245  }
1246  case ISD::EXTRACT_ELEMENT: {
1247    MVT::ValueType OpTy = Node->getOperand(0).getValueType();
1248    switch (getTypeAction(OpTy)) {
1249    default: assert(0 && "EXTRACT_ELEMENT action for type unimplemented!");
1250    case Legal:
1251      if (cast<ConstantSDNode>(Node->getOperand(1))->getValue()) {
1252        // 1 -> Hi
1253        Result = DAG.getNode(ISD::SRL, OpTy, Node->getOperand(0),
1254                             DAG.getConstant(MVT::getSizeInBits(OpTy)/2,
1255                                             TLI.getShiftAmountTy()));
1256        Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Result);
1257      } else {
1258        // 0 -> Lo
1259        Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0),
1260                             Node->getOperand(0));
1261      }
1262      break;
1263    case Expand:
1264      // Get both the low and high parts.
1265      ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
1266      if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
1267        Result = Tmp2;  // 1 -> Hi
1268      else
1269        Result = Tmp1;  // 0 -> Lo
1270      break;
1271    }
1272    break;
1273  }
1274
1275  case ISD::CopyToReg:
1276    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1277
1278    assert(isTypeLegal(Node->getOperand(2).getValueType()) &&
1279           "Register type must be legal!");
1280    // Legalize the incoming value (must be a legal type).
1281    Tmp2 = LegalizeOp(Node->getOperand(2));
1282    if (Node->getNumValues() == 1) {
1283      Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2);
1284    } else {
1285      assert(Node->getNumValues() == 2 && "Unknown CopyToReg");
1286      if (Node->getNumOperands() == 4) {
1287        Tmp3 = LegalizeOp(Node->getOperand(3));
1288        Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2,
1289                                        Tmp3);
1290      } else {
1291        Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
1292      }
1293
1294      // Since this produces two values, make sure to remember that we legalized
1295      // both of them.
1296      AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1297      AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1298      return Result;
1299    }
1300    break;
1301
1302  case ISD::RET:
1303    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1304
1305    // Ensure that libcalls are emitted before a return.
1306    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1307    Tmp1 = LegalizeOp(Tmp1);
1308    LastCALLSEQ_END = DAG.getEntryNode();
1309
1310    switch (Node->getNumOperands()) {
1311    case 2:  // ret val
1312      switch (getTypeAction(Node->getOperand(1).getValueType())) {
1313      case Legal:
1314        Tmp2 = LegalizeOp(Node->getOperand(1));
1315        Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1316        break;
1317      case Expand: {
1318        SDOperand Lo, Hi;
1319        ExpandOp(Node->getOperand(1), Lo, Hi);
1320        Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
1321        break;
1322      }
1323      case Promote:
1324        Tmp2 = PromoteOp(Node->getOperand(1));
1325        Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1326        Result = LegalizeOp(Result);
1327        break;
1328      }
1329      break;
1330    case 1:  // ret void
1331      Result = DAG.UpdateNodeOperands(Result, Tmp1);
1332      break;
1333    default: { // ret <values>
1334      std::vector<SDOperand> NewValues;
1335      NewValues.push_back(Tmp1);
1336      for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1337        switch (getTypeAction(Node->getOperand(i).getValueType())) {
1338        case Legal:
1339          NewValues.push_back(LegalizeOp(Node->getOperand(i)));
1340          break;
1341        case Expand: {
1342          SDOperand Lo, Hi;
1343          ExpandOp(Node->getOperand(i), Lo, Hi);
1344          NewValues.push_back(Lo);
1345          NewValues.push_back(Hi);
1346          break;
1347        }
1348        case Promote:
1349          assert(0 && "Can't promote multiple return value yet!");
1350        }
1351
1352      if (NewValues.size() == Node->getNumOperands())
1353        Result = DAG.UpdateNodeOperands(Result, NewValues);
1354      else
1355        Result = DAG.getNode(ISD::RET, MVT::Other, NewValues);
1356      break;
1357    }
1358    }
1359
1360    if (Result.getOpcode() == ISD::RET) {
1361      switch (TLI.getOperationAction(Result.getOpcode(), MVT::Other)) {
1362      default: assert(0 && "This action is not supported yet!");
1363      case TargetLowering::Legal: break;
1364      case TargetLowering::Custom:
1365        Tmp1 = TLI.LowerOperation(Result, DAG);
1366        if (Tmp1.Val) Result = Tmp1;
1367        break;
1368      }
1369    }
1370    break;
1371  case ISD::STORE: {
1372    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1373    Tmp2 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
1374
1375    // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
1376    // FIXME: We shouldn't do this for TargetConstantFP's.
1377    // FIXME: move this to the DAG Combiner!
1378    if (ConstantFPSDNode *CFP =dyn_cast<ConstantFPSDNode>(Node->getOperand(1))){
1379      if (CFP->getValueType(0) == MVT::f32) {
1380        Tmp3 = DAG.getConstant(FloatToBits(CFP->getValue()), MVT::i32);
1381      } else {
1382        assert(CFP->getValueType(0) == MVT::f64 && "Unknown FP type!");
1383        Tmp3 = DAG.getConstant(DoubleToBits(CFP->getValue()), MVT::i64);
1384      }
1385      Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Tmp3, Tmp2,
1386                           Node->getOperand(3));
1387      break;
1388    }
1389
1390    switch (getTypeAction(Node->getOperand(1).getValueType())) {
1391    case Legal: {
1392      Tmp3 = LegalizeOp(Node->getOperand(1));
1393      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
1394                                      Node->getOperand(3));
1395
1396      MVT::ValueType VT = Tmp3.getValueType();
1397      switch (TLI.getOperationAction(ISD::STORE, VT)) {
1398      default: assert(0 && "This action is not supported yet!");
1399      case TargetLowering::Legal:  break;
1400      case TargetLowering::Custom:
1401        Tmp1 = TLI.LowerOperation(Result, DAG);
1402        if (Tmp1.Val) Result = Tmp1;
1403        break;
1404      }
1405      break;
1406    }
1407    case Promote:
1408      // Truncate the value and store the result.
1409      Tmp3 = PromoteOp(Node->getOperand(1));
1410      Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp3, Tmp2,
1411                           Node->getOperand(3),
1412                          DAG.getValueType(Node->getOperand(1).getValueType()));
1413      break;
1414
1415    case Expand:
1416      unsigned IncrementSize = 0;
1417      SDOperand Lo, Hi;
1418
1419      // If this is a vector type, then we have to calculate the increment as
1420      // the product of the element size in bytes, and the number of elements
1421      // in the high half of the vector.
1422      if (Node->getOperand(1).getValueType() == MVT::Vector) {
1423        SDNode *InVal = Node->getOperand(1).Val;
1424        unsigned NumElems =
1425          cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
1426        MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
1427
1428        // Figure out if there is a Packed type corresponding to this Vector
1429        // type.  If so, convert to the packed type.
1430        MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
1431        if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
1432          // Turn this into a normal store of the packed type.
1433          Tmp3 = PackVectorOp(Node->getOperand(1), TVT);
1434          Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
1435                                          Node->getOperand(3));
1436          break;
1437        } else if (NumElems == 1) {
1438          // Turn this into a normal store of the scalar type.
1439          Tmp3 = PackVectorOp(Node->getOperand(1), EVT);
1440          Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
1441                                          Node->getOperand(3));
1442          // The scalarized value type may not be legal, e.g. it might require
1443          // promotion or expansion.  Relegalize the scalar store.
1444          Result = LegalizeOp(Result);
1445          break;
1446        } else {
1447          SplitVectorOp(Node->getOperand(1), Lo, Hi);
1448          IncrementSize = NumElems/2 * MVT::getSizeInBits(EVT)/8;
1449        }
1450      } else {
1451        ExpandOp(Node->getOperand(1), Lo, Hi);
1452        IncrementSize = MVT::getSizeInBits(Hi.getValueType())/8;
1453
1454        if (!TLI.isLittleEndian())
1455          std::swap(Lo, Hi);
1456      }
1457
1458      Lo = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Lo, Tmp2,
1459                       Node->getOperand(3));
1460      Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
1461                         getIntPtrConstant(IncrementSize));
1462      assert(isTypeLegal(Tmp2.getValueType()) &&
1463             "Pointers must be legal!");
1464      // FIXME: This sets the srcvalue of both halves to be the same, which is
1465      // wrong.
1466      Hi = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Hi, Tmp2,
1467                       Node->getOperand(3));
1468      Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
1469      break;
1470    }
1471    break;
1472  }
1473  case ISD::PCMARKER:
1474    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1475    Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1476    break;
1477  case ISD::STACKSAVE:
1478    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1479    Result = DAG.UpdateNodeOperands(Result, Tmp1);
1480    Tmp1 = Result.getValue(0);
1481    Tmp2 = Result.getValue(1);
1482
1483    switch (TLI.getOperationAction(ISD::STACKSAVE, MVT::Other)) {
1484    default: assert(0 && "This action is not supported yet!");
1485    case TargetLowering::Legal: break;
1486    case TargetLowering::Custom:
1487      Tmp3 = TLI.LowerOperation(Result, DAG);
1488      if (Tmp3.Val) {
1489        Tmp1 = LegalizeOp(Tmp3);
1490        Tmp2 = LegalizeOp(Tmp3.getValue(1));
1491      }
1492      break;
1493    case TargetLowering::Expand:
1494      // Expand to CopyFromReg if the target set
1495      // StackPointerRegisterToSaveRestore.
1496      if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
1497        Tmp1 = DAG.getCopyFromReg(Result.getOperand(0), SP,
1498                                  Node->getValueType(0));
1499        Tmp2 = Tmp1.getValue(1);
1500      } else {
1501        Tmp1 = DAG.getNode(ISD::UNDEF, Node->getValueType(0));
1502        Tmp2 = Node->getOperand(0);
1503      }
1504      break;
1505    }
1506
1507    // Since stacksave produce two values, make sure to remember that we
1508    // legalized both of them.
1509    AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1510    AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1511    return Op.ResNo ? Tmp2 : Tmp1;
1512
1513  case ISD::STACKRESTORE:
1514    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1515    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1516    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1517
1518    switch (TLI.getOperationAction(ISD::STACKRESTORE, MVT::Other)) {
1519    default: assert(0 && "This action is not supported yet!");
1520    case TargetLowering::Legal: break;
1521    case TargetLowering::Custom:
1522      Tmp1 = TLI.LowerOperation(Result, DAG);
1523      if (Tmp1.Val) Result = Tmp1;
1524      break;
1525    case TargetLowering::Expand:
1526      // Expand to CopyToReg if the target set
1527      // StackPointerRegisterToSaveRestore.
1528      if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
1529        Result = DAG.getCopyToReg(Tmp1, SP, Tmp2);
1530      } else {
1531        Result = Tmp1;
1532      }
1533      break;
1534    }
1535    break;
1536
1537  case ISD::READCYCLECOUNTER:
1538    Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain
1539    Result = DAG.UpdateNodeOperands(Result, Tmp1);
1540
1541    // Since rdcc produce two values, make sure to remember that we legalized
1542    // both of them.
1543    AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1544    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1545    return Result;
1546
1547  case ISD::TRUNCSTORE: {
1548    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1549    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
1550
1551    assert(isTypeLegal(Node->getOperand(1).getValueType()) &&
1552           "Cannot handle illegal TRUNCSTORE yet!");
1553    Tmp2 = LegalizeOp(Node->getOperand(1));
1554
1555    // The only promote case we handle is TRUNCSTORE:i1 X into
1556    //   -> TRUNCSTORE:i8 (and X, 1)
1557    if (cast<VTSDNode>(Node->getOperand(4))->getVT() == MVT::i1 &&
1558        TLI.getOperationAction(ISD::TRUNCSTORE, MVT::i1) ==
1559              TargetLowering::Promote) {
1560      // Promote the bool to a mask then store.
1561      Tmp2 = DAG.getNode(ISD::AND, Tmp2.getValueType(), Tmp2,
1562                         DAG.getConstant(1, Tmp2.getValueType()));
1563      Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
1564                           Node->getOperand(3), DAG.getValueType(MVT::i8));
1565
1566    } else if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1567               Tmp3 != Node->getOperand(2)) {
1568      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3,
1569                                      Node->getOperand(3), Node->getOperand(4));
1570    }
1571
1572    MVT::ValueType StVT = cast<VTSDNode>(Result.Val->getOperand(4))->getVT();
1573    switch (TLI.getOperationAction(Result.Val->getOpcode(), StVT)) {
1574    default: assert(0 && "This action is not supported yet!");
1575    case TargetLowering::Legal: break;
1576    case TargetLowering::Custom:
1577      Tmp1 = TLI.LowerOperation(Result, DAG);
1578      if (Tmp1.Val) Result = Tmp1;
1579      break;
1580    }
1581    break;
1582  }
1583  case ISD::SELECT:
1584    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1585    case Expand: assert(0 && "It's impossible to expand bools");
1586    case Legal:
1587      Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
1588      break;
1589    case Promote:
1590      Tmp1 = PromoteOp(Node->getOperand(0));  // Promote the condition.
1591      break;
1592    }
1593    Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
1594    Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
1595
1596    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1597
1598    switch (TLI.getOperationAction(ISD::SELECT, Tmp2.getValueType())) {
1599    default: assert(0 && "This action is not supported yet!");
1600    case TargetLowering::Legal: break;
1601    case TargetLowering::Custom: {
1602      Tmp1 = TLI.LowerOperation(Result, DAG);
1603      if (Tmp1.Val) Result = Tmp1;
1604      break;
1605    }
1606    case TargetLowering::Expand:
1607      if (Tmp1.getOpcode() == ISD::SETCC) {
1608        Result = DAG.getSelectCC(Tmp1.getOperand(0), Tmp1.getOperand(1),
1609                              Tmp2, Tmp3,
1610                              cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
1611      } else {
1612        // Make sure the condition is either zero or one.  It may have been
1613        // promoted from something else.
1614        unsigned NumBits = MVT::getSizeInBits(Tmp1.getValueType());
1615        if (!TLI.MaskedValueIsZero(Tmp1, (~0ULL >> (64-NumBits))^1))
1616          Tmp1 = DAG.getZeroExtendInReg(Tmp1, MVT::i1);
1617        Result = DAG.getSelectCC(Tmp1,
1618                                 DAG.getConstant(0, Tmp1.getValueType()),
1619                                 Tmp2, Tmp3, ISD::SETNE);
1620      }
1621      break;
1622    case TargetLowering::Promote: {
1623      MVT::ValueType NVT =
1624        TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
1625      unsigned ExtOp, TruncOp;
1626      if (MVT::isInteger(Tmp2.getValueType())) {
1627        ExtOp   = ISD::ANY_EXTEND;
1628        TruncOp = ISD::TRUNCATE;
1629      } else {
1630        ExtOp   = ISD::FP_EXTEND;
1631        TruncOp = ISD::FP_ROUND;
1632      }
1633      // Promote each of the values to the new type.
1634      Tmp2 = DAG.getNode(ExtOp, NVT, Tmp2);
1635      Tmp3 = DAG.getNode(ExtOp, NVT, Tmp3);
1636      // Perform the larger operation, then round down.
1637      Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2,Tmp3);
1638      Result = DAG.getNode(TruncOp, Node->getValueType(0), Result);
1639      break;
1640    }
1641    }
1642    break;
1643  case ISD::SELECT_CC: {
1644    Tmp1 = Node->getOperand(0);               // LHS
1645    Tmp2 = Node->getOperand(1);               // RHS
1646    Tmp3 = LegalizeOp(Node->getOperand(2));   // True
1647    Tmp4 = LegalizeOp(Node->getOperand(3));   // False
1648    SDOperand CC = Node->getOperand(4);
1649
1650    LegalizeSetCCOperands(Tmp1, Tmp2, CC);
1651
1652    // If we didn't get both a LHS and RHS back from LegalizeSetCCOperands,
1653    // the LHS is a legal SETCC itself.  In this case, we need to compare
1654    // the result against zero to select between true and false values.
1655    if (Tmp2.Val == 0) {
1656      Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
1657      CC = DAG.getCondCode(ISD::SETNE);
1658    }
1659    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4, CC);
1660
1661    // Everything is legal, see if we should expand this op or something.
1662    switch (TLI.getOperationAction(ISD::SELECT_CC, Tmp3.getValueType())) {
1663    default: assert(0 && "This action is not supported yet!");
1664    case TargetLowering::Legal: break;
1665    case TargetLowering::Custom:
1666      Tmp1 = TLI.LowerOperation(Result, DAG);
1667      if (Tmp1.Val) Result = Tmp1;
1668      break;
1669    }
1670    break;
1671  }
1672  case ISD::SETCC:
1673    Tmp1 = Node->getOperand(0);
1674    Tmp2 = Node->getOperand(1);
1675    Tmp3 = Node->getOperand(2);
1676    LegalizeSetCCOperands(Tmp1, Tmp2, Tmp3);
1677
1678    // If we had to Expand the SetCC operands into a SELECT node, then it may
1679    // not always be possible to return a true LHS & RHS.  In this case, just
1680    // return the value we legalized, returned in the LHS
1681    if (Tmp2.Val == 0) {
1682      Result = Tmp1;
1683      break;
1684    }
1685
1686    switch (TLI.getOperationAction(ISD::SETCC, Tmp1.getValueType())) {
1687    default: assert(0 && "Cannot handle this action for SETCC yet!");
1688    case TargetLowering::Custom:
1689      isCustom = true;
1690      // FALLTHROUGH.
1691    case TargetLowering::Legal:
1692      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1693      if (isCustom) {
1694        Tmp3 = TLI.LowerOperation(Result, DAG);
1695        if (Tmp3.Val) Result = Tmp3;
1696      }
1697      break;
1698    case TargetLowering::Promote: {
1699      // First step, figure out the appropriate operation to use.
1700      // Allow SETCC to not be supported for all legal data types
1701      // Mostly this targets FP
1702      MVT::ValueType NewInTy = Node->getOperand(0).getValueType();
1703      MVT::ValueType OldVT = NewInTy;
1704
1705      // Scan for the appropriate larger type to use.
1706      while (1) {
1707        NewInTy = (MVT::ValueType)(NewInTy+1);
1708
1709        assert(MVT::isInteger(NewInTy) == MVT::isInteger(OldVT) &&
1710               "Fell off of the edge of the integer world");
1711        assert(MVT::isFloatingPoint(NewInTy) == MVT::isFloatingPoint(OldVT) &&
1712               "Fell off of the edge of the floating point world");
1713
1714        // If the target supports SETCC of this type, use it.
1715        if (TLI.isOperationLegal(ISD::SETCC, NewInTy))
1716          break;
1717      }
1718      if (MVT::isInteger(NewInTy))
1719        assert(0 && "Cannot promote Legal Integer SETCC yet");
1720      else {
1721        Tmp1 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp1);
1722        Tmp2 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp2);
1723      }
1724      Tmp1 = LegalizeOp(Tmp1);
1725      Tmp2 = LegalizeOp(Tmp2);
1726      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1727      Result = LegalizeOp(Result);
1728      break;
1729    }
1730    case TargetLowering::Expand:
1731      // Expand a setcc node into a select_cc of the same condition, lhs, and
1732      // rhs that selects between const 1 (true) and const 0 (false).
1733      MVT::ValueType VT = Node->getValueType(0);
1734      Result = DAG.getNode(ISD::SELECT_CC, VT, Tmp1, Tmp2,
1735                           DAG.getConstant(1, VT), DAG.getConstant(0, VT),
1736                           Node->getOperand(2));
1737      break;
1738    }
1739    break;
1740  case ISD::MEMSET:
1741  case ISD::MEMCPY:
1742  case ISD::MEMMOVE: {
1743    Tmp1 = LegalizeOp(Node->getOperand(0));      // Chain
1744    Tmp2 = LegalizeOp(Node->getOperand(1));      // Pointer
1745
1746    if (Node->getOpcode() == ISD::MEMSET) {      // memset = ubyte
1747      switch (getTypeAction(Node->getOperand(2).getValueType())) {
1748      case Expand: assert(0 && "Cannot expand a byte!");
1749      case Legal:
1750        Tmp3 = LegalizeOp(Node->getOperand(2));
1751        break;
1752      case Promote:
1753        Tmp3 = PromoteOp(Node->getOperand(2));
1754        break;
1755      }
1756    } else {
1757      Tmp3 = LegalizeOp(Node->getOperand(2));    // memcpy/move = pointer,
1758    }
1759
1760    SDOperand Tmp4;
1761    switch (getTypeAction(Node->getOperand(3).getValueType())) {
1762    case Expand: {
1763      // Length is too big, just take the lo-part of the length.
1764      SDOperand HiPart;
1765      ExpandOp(Node->getOperand(3), HiPart, Tmp4);
1766      break;
1767    }
1768    case Legal:
1769      Tmp4 = LegalizeOp(Node->getOperand(3));
1770      break;
1771    case Promote:
1772      Tmp4 = PromoteOp(Node->getOperand(3));
1773      break;
1774    }
1775
1776    SDOperand Tmp5;
1777    switch (getTypeAction(Node->getOperand(4).getValueType())) {  // uint
1778    case Expand: assert(0 && "Cannot expand this yet!");
1779    case Legal:
1780      Tmp5 = LegalizeOp(Node->getOperand(4));
1781      break;
1782    case Promote:
1783      Tmp5 = PromoteOp(Node->getOperand(4));
1784      break;
1785    }
1786
1787    switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
1788    default: assert(0 && "This action not implemented for this operation!");
1789    case TargetLowering::Custom:
1790      isCustom = true;
1791      // FALLTHROUGH
1792    case TargetLowering::Legal:
1793      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4, Tmp5);
1794      if (isCustom) {
1795        Tmp1 = TLI.LowerOperation(Result, DAG);
1796        if (Tmp1.Val) Result = Tmp1;
1797      }
1798      break;
1799    case TargetLowering::Expand: {
1800      // Otherwise, the target does not support this operation.  Lower the
1801      // operation to an explicit libcall as appropriate.
1802      MVT::ValueType IntPtr = TLI.getPointerTy();
1803      const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
1804      std::vector<std::pair<SDOperand, const Type*> > Args;
1805
1806      const char *FnName = 0;
1807      if (Node->getOpcode() == ISD::MEMSET) {
1808        Args.push_back(std::make_pair(Tmp2, IntPtrTy));
1809        // Extend the (previously legalized) ubyte argument to be an int value
1810        // for the call.
1811        if (Tmp3.getValueType() > MVT::i32)
1812          Tmp3 = DAG.getNode(ISD::TRUNCATE, MVT::i32, Tmp3);
1813        else
1814          Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Tmp3);
1815        Args.push_back(std::make_pair(Tmp3, Type::IntTy));
1816        Args.push_back(std::make_pair(Tmp4, IntPtrTy));
1817
1818        FnName = "memset";
1819      } else if (Node->getOpcode() == ISD::MEMCPY ||
1820                 Node->getOpcode() == ISD::MEMMOVE) {
1821        Args.push_back(std::make_pair(Tmp2, IntPtrTy));
1822        Args.push_back(std::make_pair(Tmp3, IntPtrTy));
1823        Args.push_back(std::make_pair(Tmp4, IntPtrTy));
1824        FnName = Node->getOpcode() == ISD::MEMMOVE ? "memmove" : "memcpy";
1825      } else {
1826        assert(0 && "Unknown op!");
1827      }
1828
1829      std::pair<SDOperand,SDOperand> CallResult =
1830        TLI.LowerCallTo(Tmp1, Type::VoidTy, false, CallingConv::C, false,
1831                        DAG.getExternalSymbol(FnName, IntPtr), Args, DAG);
1832      Result = CallResult.second;
1833      break;
1834    }
1835    }
1836    break;
1837  }
1838
1839  case ISD::SHL_PARTS:
1840  case ISD::SRA_PARTS:
1841  case ISD::SRL_PARTS: {
1842    std::vector<SDOperand> Ops;
1843    bool Changed = false;
1844    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1845      Ops.push_back(LegalizeOp(Node->getOperand(i)));
1846      Changed |= Ops.back() != Node->getOperand(i);
1847    }
1848    if (Changed)
1849      Result = DAG.UpdateNodeOperands(Result, Ops);
1850
1851    switch (TLI.getOperationAction(Node->getOpcode(),
1852                                   Node->getValueType(0))) {
1853    default: assert(0 && "This action is not supported yet!");
1854    case TargetLowering::Legal: break;
1855    case TargetLowering::Custom:
1856      Tmp1 = TLI.LowerOperation(Result, DAG);
1857      if (Tmp1.Val) {
1858        SDOperand Tmp2, RetVal(0, 0);
1859        for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
1860          Tmp2 = LegalizeOp(Tmp1.getValue(i));
1861          AddLegalizedOperand(SDOperand(Node, i), Tmp2);
1862          if (i == Op.ResNo)
1863            RetVal = Tmp2;
1864        }
1865        assert(RetVal.Val && "Illegal result number");
1866        return RetVal;
1867      }
1868      break;
1869    }
1870
1871    // Since these produce multiple values, make sure to remember that we
1872    // legalized all of them.
1873    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
1874      AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
1875    return Result.getValue(Op.ResNo);
1876  }
1877
1878    // Binary operators
1879  case ISD::ADD:
1880  case ISD::SUB:
1881  case ISD::MUL:
1882  case ISD::MULHS:
1883  case ISD::MULHU:
1884  case ISD::UDIV:
1885  case ISD::SDIV:
1886  case ISD::AND:
1887  case ISD::OR:
1888  case ISD::XOR:
1889  case ISD::SHL:
1890  case ISD::SRL:
1891  case ISD::SRA:
1892  case ISD::FADD:
1893  case ISD::FSUB:
1894  case ISD::FMUL:
1895  case ISD::FDIV:
1896    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
1897    switch (getTypeAction(Node->getOperand(1).getValueType())) {
1898    case Expand: assert(0 && "Not possible");
1899    case Legal:
1900      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
1901      break;
1902    case Promote:
1903      Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
1904      break;
1905    }
1906
1907    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1908
1909    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1910    default: assert(0 && "Operation not supported");
1911    case TargetLowering::Legal: break;
1912    case TargetLowering::Custom:
1913      Tmp1 = TLI.LowerOperation(Result, DAG);
1914      if (Tmp1.Val) Result = Tmp1;
1915      break;
1916    }
1917    break;
1918
1919  case ISD::FCOPYSIGN:  // FCOPYSIGN does not require LHS/RHS to match type!
1920    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
1921    switch (getTypeAction(Node->getOperand(1).getValueType())) {
1922      case Expand: assert(0 && "Not possible");
1923      case Legal:
1924        Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
1925        break;
1926      case Promote:
1927        Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
1928        break;
1929    }
1930
1931    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1932
1933    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1934    default: assert(0 && "Operation not supported");
1935    case TargetLowering::Custom:
1936      Tmp1 = TLI.LowerOperation(Result, DAG);
1937      if (Tmp1.Val) Result = Tmp1;
1938      break;
1939    case TargetLowering::Legal: break;
1940    case TargetLowering::Expand:
1941      // If this target supports fabs/fneg natively, do this efficiently.
1942      if (TLI.isOperationLegal(ISD::FABS, Tmp1.getValueType()) &&
1943          TLI.isOperationLegal(ISD::FNEG, Tmp1.getValueType())) {
1944        // Get the sign bit of the RHS.
1945        MVT::ValueType IVT =
1946          Tmp2.getValueType() == MVT::f32 ? MVT::i32 : MVT::i64;
1947        SDOperand SignBit = DAG.getNode(ISD::BIT_CONVERT, IVT, Tmp2);
1948        SignBit = DAG.getSetCC(TLI.getSetCCResultTy(),
1949                               SignBit, DAG.getConstant(0, IVT), ISD::SETLT);
1950        // Get the absolute value of the result.
1951        SDOperand AbsVal = DAG.getNode(ISD::FABS, Tmp1.getValueType(), Tmp1);
1952        // Select between the nabs and abs value based on the sign bit of
1953        // the input.
1954        Result = DAG.getNode(ISD::SELECT, AbsVal.getValueType(), SignBit,
1955                             DAG.getNode(ISD::FNEG, AbsVal.getValueType(),
1956                                         AbsVal),
1957                             AbsVal);
1958        Result = LegalizeOp(Result);
1959        break;
1960      }
1961
1962      // Otherwise, do bitwise ops!
1963
1964      // copysign -> copysignf/copysign libcall.
1965      const char *FnName;
1966      if (Node->getValueType(0) == MVT::f32) {
1967        FnName = "copysignf";
1968        if (Tmp2.getValueType() != MVT::f32)  // Force operands to match type.
1969          Result = DAG.UpdateNodeOperands(Result, Tmp1,
1970                                    DAG.getNode(ISD::FP_ROUND, MVT::f32, Tmp2));
1971      } else {
1972        FnName = "copysign";
1973        if (Tmp2.getValueType() != MVT::f64)  // Force operands to match type.
1974          Result = DAG.UpdateNodeOperands(Result, Tmp1,
1975                                   DAG.getNode(ISD::FP_EXTEND, MVT::f64, Tmp2));
1976      }
1977      SDOperand Dummy;
1978      Result = ExpandLibCall(FnName, Node, Dummy);
1979      break;
1980    }
1981    break;
1982
1983  case ISD::ADDC:
1984  case ISD::SUBC:
1985    Tmp1 = LegalizeOp(Node->getOperand(0));
1986    Tmp2 = LegalizeOp(Node->getOperand(1));
1987    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1988    // Since this produces two values, make sure to remember that we legalized
1989    // both of them.
1990    AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1991    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1992    return Result;
1993
1994  case ISD::ADDE:
1995  case ISD::SUBE:
1996    Tmp1 = LegalizeOp(Node->getOperand(0));
1997    Tmp2 = LegalizeOp(Node->getOperand(1));
1998    Tmp3 = LegalizeOp(Node->getOperand(2));
1999    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2000    // Since this produces two values, make sure to remember that we legalized
2001    // both of them.
2002    AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
2003    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
2004    return Result;
2005
2006  case ISD::BUILD_PAIR: {
2007    MVT::ValueType PairTy = Node->getValueType(0);
2008    // TODO: handle the case where the Lo and Hi operands are not of legal type
2009    Tmp1 = LegalizeOp(Node->getOperand(0));   // Lo
2010    Tmp2 = LegalizeOp(Node->getOperand(1));   // Hi
2011    switch (TLI.getOperationAction(ISD::BUILD_PAIR, PairTy)) {
2012    case TargetLowering::Promote:
2013    case TargetLowering::Custom:
2014      assert(0 && "Cannot promote/custom this yet!");
2015    case TargetLowering::Legal:
2016      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
2017        Result = DAG.getNode(ISD::BUILD_PAIR, PairTy, Tmp1, Tmp2);
2018      break;
2019    case TargetLowering::Expand:
2020      Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, PairTy, Tmp1);
2021      Tmp2 = DAG.getNode(ISD::ANY_EXTEND, PairTy, Tmp2);
2022      Tmp2 = DAG.getNode(ISD::SHL, PairTy, Tmp2,
2023                         DAG.getConstant(MVT::getSizeInBits(PairTy)/2,
2024                                         TLI.getShiftAmountTy()));
2025      Result = DAG.getNode(ISD::OR, PairTy, Tmp1, Tmp2);
2026      break;
2027    }
2028    break;
2029  }
2030
2031  case ISD::UREM:
2032  case ISD::SREM:
2033  case ISD::FREM:
2034    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2035    Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
2036
2037    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2038    case TargetLowering::Promote: assert(0 && "Cannot promote this yet!");
2039    case TargetLowering::Custom:
2040      isCustom = true;
2041      // FALLTHROUGH
2042    case TargetLowering::Legal:
2043      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2044      if (isCustom) {
2045        Tmp1 = TLI.LowerOperation(Result, DAG);
2046        if (Tmp1.Val) Result = Tmp1;
2047      }
2048      break;
2049    case TargetLowering::Expand:
2050      if (MVT::isInteger(Node->getValueType(0))) {
2051        // X % Y -> X-X/Y*Y
2052        MVT::ValueType VT = Node->getValueType(0);
2053        unsigned Opc = Node->getOpcode() == ISD::UREM ? ISD::UDIV : ISD::SDIV;
2054        Result = DAG.getNode(Opc, VT, Tmp1, Tmp2);
2055        Result = DAG.getNode(ISD::MUL, VT, Result, Tmp2);
2056        Result = DAG.getNode(ISD::SUB, VT, Tmp1, Result);
2057      } else {
2058        // Floating point mod -> fmod libcall.
2059        const char *FnName = Node->getValueType(0) == MVT::f32 ? "fmodf":"fmod";
2060        SDOperand Dummy;
2061        Result = ExpandLibCall(FnName, Node, Dummy);
2062      }
2063      break;
2064    }
2065    break;
2066  case ISD::VAARG: {
2067    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2068    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2069
2070    MVT::ValueType VT = Node->getValueType(0);
2071    switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
2072    default: assert(0 && "This action is not supported yet!");
2073    case TargetLowering::Custom:
2074      isCustom = true;
2075      // FALLTHROUGH
2076    case TargetLowering::Legal:
2077      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2078      Result = Result.getValue(0);
2079      Tmp1 = Result.getValue(1);
2080
2081      if (isCustom) {
2082        Tmp2 = TLI.LowerOperation(Result, DAG);
2083        if (Tmp2.Val) {
2084          Result = LegalizeOp(Tmp2);
2085          Tmp1 = LegalizeOp(Tmp2.getValue(1));
2086        }
2087      }
2088      break;
2089    case TargetLowering::Expand: {
2090      SDOperand VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2,
2091                                     Node->getOperand(2));
2092      // Increment the pointer, VAList, to the next vaarg
2093      Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList,
2094                         DAG.getConstant(MVT::getSizeInBits(VT)/8,
2095                                         TLI.getPointerTy()));
2096      // Store the incremented VAList to the legalized pointer
2097      Tmp3 = DAG.getNode(ISD::STORE, MVT::Other, VAList.getValue(1), Tmp3, Tmp2,
2098                         Node->getOperand(2));
2099      // Load the actual argument out of the pointer VAList
2100      Result = DAG.getLoad(VT, Tmp3, VAList, DAG.getSrcValue(0));
2101      Tmp1 = LegalizeOp(Result.getValue(1));
2102      Result = LegalizeOp(Result);
2103      break;
2104    }
2105    }
2106    // Since VAARG produces two values, make sure to remember that we
2107    // legalized both of them.
2108    AddLegalizedOperand(SDOperand(Node, 0), Result);
2109    AddLegalizedOperand(SDOperand(Node, 1), Tmp1);
2110    return Op.ResNo ? Tmp1 : Result;
2111  }
2112
2113  case ISD::VACOPY:
2114    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2115    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the dest pointer.
2116    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the source pointer.
2117
2118    switch (TLI.getOperationAction(ISD::VACOPY, MVT::Other)) {
2119    default: assert(0 && "This action is not supported yet!");
2120    case TargetLowering::Custom:
2121      isCustom = true;
2122      // FALLTHROUGH
2123    case TargetLowering::Legal:
2124      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3,
2125                                      Node->getOperand(3), Node->getOperand(4));
2126      if (isCustom) {
2127        Tmp1 = TLI.LowerOperation(Result, DAG);
2128        if (Tmp1.Val) Result = Tmp1;
2129      }
2130      break;
2131    case TargetLowering::Expand:
2132      // This defaults to loading a pointer from the input and storing it to the
2133      // output, returning the chain.
2134      Tmp4 = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp3, Node->getOperand(3));
2135      Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp4.getValue(1), Tmp4, Tmp2,
2136                           Node->getOperand(4));
2137      break;
2138    }
2139    break;
2140
2141  case ISD::VAEND:
2142    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2143    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2144
2145    switch (TLI.getOperationAction(ISD::VAEND, MVT::Other)) {
2146    default: assert(0 && "This action is not supported yet!");
2147    case TargetLowering::Custom:
2148      isCustom = true;
2149      // FALLTHROUGH
2150    case TargetLowering::Legal:
2151      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2152      if (isCustom) {
2153        Tmp1 = TLI.LowerOperation(Tmp1, DAG);
2154        if (Tmp1.Val) Result = Tmp1;
2155      }
2156      break;
2157    case TargetLowering::Expand:
2158      Result = Tmp1; // Default to a no-op, return the chain
2159      break;
2160    }
2161    break;
2162
2163  case ISD::VASTART:
2164    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2165    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2166
2167    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2168
2169    switch (TLI.getOperationAction(ISD::VASTART, MVT::Other)) {
2170    default: assert(0 && "This action is not supported yet!");
2171    case TargetLowering::Legal: break;
2172    case TargetLowering::Custom:
2173      Tmp1 = TLI.LowerOperation(Result, DAG);
2174      if (Tmp1.Val) Result = Tmp1;
2175      break;
2176    }
2177    break;
2178
2179  case ISD::ROTL:
2180  case ISD::ROTR:
2181    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2182    Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
2183
2184    assert(TLI.isOperationLegal(Node->getOpcode(), Node->getValueType(0)) &&
2185           "Cannot handle this yet!");
2186    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2187    break;
2188
2189  case ISD::BSWAP:
2190    Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
2191    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2192    case TargetLowering::Custom:
2193      assert(0 && "Cannot custom legalize this yet!");
2194    case TargetLowering::Legal:
2195      Result = DAG.UpdateNodeOperands(Result, Tmp1);
2196      break;
2197    case TargetLowering::Promote: {
2198      MVT::ValueType OVT = Tmp1.getValueType();
2199      MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
2200      unsigned DiffBits = getSizeInBits(NVT) - getSizeInBits(OVT);
2201
2202      Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
2203      Tmp1 = DAG.getNode(ISD::BSWAP, NVT, Tmp1);
2204      Result = DAG.getNode(ISD::SRL, NVT, Tmp1,
2205                           DAG.getConstant(DiffBits, TLI.getShiftAmountTy()));
2206      break;
2207    }
2208    case TargetLowering::Expand:
2209      Result = ExpandBSWAP(Tmp1);
2210      break;
2211    }
2212    break;
2213
2214  case ISD::CTPOP:
2215  case ISD::CTTZ:
2216  case ISD::CTLZ:
2217    Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
2218    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2219    case TargetLowering::Custom: assert(0 && "Cannot custom handle this yet!");
2220    case TargetLowering::Legal:
2221      Result = DAG.UpdateNodeOperands(Result, Tmp1);
2222      break;
2223    case TargetLowering::Promote: {
2224      MVT::ValueType OVT = Tmp1.getValueType();
2225      MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
2226
2227      // Zero extend the argument.
2228      Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
2229      // Perform the larger operation, then subtract if needed.
2230      Tmp1 = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2231      switch (Node->getOpcode()) {
2232      case ISD::CTPOP:
2233        Result = Tmp1;
2234        break;
2235      case ISD::CTTZ:
2236        //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
2237        Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
2238                            DAG.getConstant(getSizeInBits(NVT), NVT),
2239                            ISD::SETEQ);
2240        Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
2241                           DAG.getConstant(getSizeInBits(OVT),NVT), Tmp1);
2242        break;
2243      case ISD::CTLZ:
2244        // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
2245        Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
2246                             DAG.getConstant(getSizeInBits(NVT) -
2247                                             getSizeInBits(OVT), NVT));
2248        break;
2249      }
2250      break;
2251    }
2252    case TargetLowering::Expand:
2253      Result = ExpandBitCount(Node->getOpcode(), Tmp1);
2254      break;
2255    }
2256    break;
2257
2258    // Unary operators
2259  case ISD::FABS:
2260  case ISD::FNEG:
2261  case ISD::FSQRT:
2262  case ISD::FSIN:
2263  case ISD::FCOS:
2264    Tmp1 = LegalizeOp(Node->getOperand(0));
2265    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2266    case TargetLowering::Promote:
2267    case TargetLowering::Custom:
2268     isCustom = true;
2269     // FALLTHROUGH
2270    case TargetLowering::Legal:
2271      Result = DAG.UpdateNodeOperands(Result, Tmp1);
2272      if (isCustom) {
2273        Tmp1 = TLI.LowerOperation(Result, DAG);
2274        if (Tmp1.Val) Result = Tmp1;
2275      }
2276      break;
2277    case TargetLowering::Expand:
2278      switch (Node->getOpcode()) {
2279      default: assert(0 && "Unreachable!");
2280      case ISD::FNEG:
2281        // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
2282        Tmp2 = DAG.getConstantFP(-0.0, Node->getValueType(0));
2283        Result = DAG.getNode(ISD::FSUB, Node->getValueType(0), Tmp2, Tmp1);
2284        break;
2285      case ISD::FABS: {
2286        // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
2287        MVT::ValueType VT = Node->getValueType(0);
2288        Tmp2 = DAG.getConstantFP(0.0, VT);
2289        Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1, Tmp2, ISD::SETUGT);
2290        Tmp3 = DAG.getNode(ISD::FNEG, VT, Tmp1);
2291        Result = DAG.getNode(ISD::SELECT, VT, Tmp2, Tmp1, Tmp3);
2292        break;
2293      }
2294      case ISD::FSQRT:
2295      case ISD::FSIN:
2296      case ISD::FCOS: {
2297        MVT::ValueType VT = Node->getValueType(0);
2298        const char *FnName = 0;
2299        switch(Node->getOpcode()) {
2300        case ISD::FSQRT: FnName = VT == MVT::f32 ? "sqrtf" : "sqrt"; break;
2301        case ISD::FSIN:  FnName = VT == MVT::f32 ? "sinf"  : "sin"; break;
2302        case ISD::FCOS:  FnName = VT == MVT::f32 ? "cosf"  : "cos"; break;
2303        default: assert(0 && "Unreachable!");
2304        }
2305        SDOperand Dummy;
2306        Result = ExpandLibCall(FnName, Node, Dummy);
2307        break;
2308      }
2309      }
2310      break;
2311    }
2312    break;
2313
2314  case ISD::BIT_CONVERT:
2315    if (!isTypeLegal(Node->getOperand(0).getValueType())) {
2316      Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2317    } else {
2318      switch (TLI.getOperationAction(ISD::BIT_CONVERT,
2319                                     Node->getOperand(0).getValueType())) {
2320      default: assert(0 && "Unknown operation action!");
2321      case TargetLowering::Expand:
2322        Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2323        break;
2324      case TargetLowering::Legal:
2325        Tmp1 = LegalizeOp(Node->getOperand(0));
2326        Result = DAG.UpdateNodeOperands(Result, Tmp1);
2327        break;
2328      }
2329    }
2330    break;
2331  case ISD::VBIT_CONVERT: {
2332    assert(Op.getOperand(0).getValueType() == MVT::Vector &&
2333           "Can only have VBIT_CONVERT where input or output is MVT::Vector!");
2334
2335    // The input has to be a vector type, we have to either scalarize it, pack
2336    // it, or convert it based on whether the input vector type is legal.
2337    SDNode *InVal = Node->getOperand(0).Val;
2338    unsigned NumElems =
2339      cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
2340    MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
2341
2342    // Figure out if there is a Packed type corresponding to this Vector
2343    // type.  If so, convert to the packed type.
2344    MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
2345    if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
2346      // Turn this into a bit convert of the packed input.
2347      Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0),
2348                           PackVectorOp(Node->getOperand(0), TVT));
2349      break;
2350    } else if (NumElems == 1) {
2351      // Turn this into a bit convert of the scalar input.
2352      Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0),
2353                           PackVectorOp(Node->getOperand(0), EVT));
2354      break;
2355    } else {
2356      // FIXME: UNIMP!  Store then reload
2357      assert(0 && "Cast from unsupported vector type not implemented yet!");
2358    }
2359  }
2360
2361    // Conversion operators.  The source and destination have different types.
2362  case ISD::SINT_TO_FP:
2363  case ISD::UINT_TO_FP: {
2364    bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
2365    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2366    case Legal:
2367      switch (TLI.getOperationAction(Node->getOpcode(),
2368                                     Node->getOperand(0).getValueType())) {
2369      default: assert(0 && "Unknown operation action!");
2370      case TargetLowering::Custom:
2371        isCustom = true;
2372        // FALLTHROUGH
2373      case TargetLowering::Legal:
2374        Tmp1 = LegalizeOp(Node->getOperand(0));
2375        Result = DAG.UpdateNodeOperands(Result, Tmp1);
2376        if (isCustom) {
2377          Tmp1 = TLI.LowerOperation(Result, DAG);
2378          if (Tmp1.Val) Result = Tmp1;
2379        }
2380        break;
2381      case TargetLowering::Expand:
2382        Result = ExpandLegalINT_TO_FP(isSigned,
2383                                      LegalizeOp(Node->getOperand(0)),
2384                                      Node->getValueType(0));
2385        break;
2386      case TargetLowering::Promote:
2387        Result = PromoteLegalINT_TO_FP(LegalizeOp(Node->getOperand(0)),
2388                                       Node->getValueType(0),
2389                                       isSigned);
2390        break;
2391      }
2392      break;
2393    case Expand:
2394      Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP,
2395                             Node->getValueType(0), Node->getOperand(0));
2396      break;
2397    case Promote:
2398      Tmp1 = PromoteOp(Node->getOperand(0));
2399      if (isSigned) {
2400        Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, Tmp1.getValueType(),
2401                 Tmp1, DAG.getValueType(Node->getOperand(0).getValueType()));
2402      } else {
2403        Tmp1 = DAG.getZeroExtendInReg(Tmp1,
2404                                      Node->getOperand(0).getValueType());
2405      }
2406      Result = DAG.UpdateNodeOperands(Result, Tmp1);
2407      Result = LegalizeOp(Result);  // The 'op' is not necessarily legal!
2408      break;
2409    }
2410    break;
2411  }
2412  case ISD::TRUNCATE:
2413    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2414    case Legal:
2415      Tmp1 = LegalizeOp(Node->getOperand(0));
2416      Result = DAG.UpdateNodeOperands(Result, Tmp1);
2417      break;
2418    case Expand:
2419      ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
2420
2421      // Since the result is legal, we should just be able to truncate the low
2422      // part of the source.
2423      Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
2424      break;
2425    case Promote:
2426      Result = PromoteOp(Node->getOperand(0));
2427      Result = DAG.getNode(ISD::TRUNCATE, Op.getValueType(), Result);
2428      break;
2429    }
2430    break;
2431
2432  case ISD::FP_TO_SINT:
2433  case ISD::FP_TO_UINT:
2434    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2435    case Legal:
2436      Tmp1 = LegalizeOp(Node->getOperand(0));
2437
2438      switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))){
2439      default: assert(0 && "Unknown operation action!");
2440      case TargetLowering::Custom:
2441        isCustom = true;
2442        // FALLTHROUGH
2443      case TargetLowering::Legal:
2444        Result = DAG.UpdateNodeOperands(Result, Tmp1);
2445        if (isCustom) {
2446          Tmp1 = TLI.LowerOperation(Result, DAG);
2447          if (Tmp1.Val) Result = Tmp1;
2448        }
2449        break;
2450      case TargetLowering::Promote:
2451        Result = PromoteLegalFP_TO_INT(Tmp1, Node->getValueType(0),
2452                                       Node->getOpcode() == ISD::FP_TO_SINT);
2453        break;
2454      case TargetLowering::Expand:
2455        if (Node->getOpcode() == ISD::FP_TO_UINT) {
2456          SDOperand True, False;
2457          MVT::ValueType VT =  Node->getOperand(0).getValueType();
2458          MVT::ValueType NVT = Node->getValueType(0);
2459          unsigned ShiftAmt = MVT::getSizeInBits(Node->getValueType(0))-1;
2460          Tmp2 = DAG.getConstantFP((double)(1ULL << ShiftAmt), VT);
2461          Tmp3 = DAG.getSetCC(TLI.getSetCCResultTy(),
2462                            Node->getOperand(0), Tmp2, ISD::SETLT);
2463          True = DAG.getNode(ISD::FP_TO_SINT, NVT, Node->getOperand(0));
2464          False = DAG.getNode(ISD::FP_TO_SINT, NVT,
2465                              DAG.getNode(ISD::FSUB, VT, Node->getOperand(0),
2466                                          Tmp2));
2467          False = DAG.getNode(ISD::XOR, NVT, False,
2468                              DAG.getConstant(1ULL << ShiftAmt, NVT));
2469          Result = DAG.getNode(ISD::SELECT, NVT, Tmp3, True, False);
2470          break;
2471        } else {
2472          assert(0 && "Do not know how to expand FP_TO_SINT yet!");
2473        }
2474        break;
2475      }
2476      break;
2477    case Expand:
2478      assert(0 && "Shouldn't need to expand other operators here!");
2479    case Promote:
2480      Tmp1 = PromoteOp(Node->getOperand(0));
2481      Result = DAG.UpdateNodeOperands(Result, LegalizeOp(Tmp1));
2482      Result = LegalizeOp(Result);
2483      break;
2484    }
2485    break;
2486
2487  case ISD::ANY_EXTEND:
2488  case ISD::ZERO_EXTEND:
2489  case ISD::SIGN_EXTEND:
2490  case ISD::FP_EXTEND:
2491  case ISD::FP_ROUND:
2492    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2493    case Expand: assert(0 && "Shouldn't need to expand other operators here!");
2494    case Legal:
2495      Tmp1 = LegalizeOp(Node->getOperand(0));
2496      Result = DAG.UpdateNodeOperands(Result, Tmp1);
2497      break;
2498    case Promote:
2499      switch (Node->getOpcode()) {
2500      case ISD::ANY_EXTEND:
2501        Tmp1 = PromoteOp(Node->getOperand(0));
2502        Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Tmp1);
2503        break;
2504      case ISD::ZERO_EXTEND:
2505        Result = PromoteOp(Node->getOperand(0));
2506        Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
2507        Result = DAG.getZeroExtendInReg(Result,
2508                                        Node->getOperand(0).getValueType());
2509        break;
2510      case ISD::SIGN_EXTEND:
2511        Result = PromoteOp(Node->getOperand(0));
2512        Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
2513        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2514                             Result,
2515                          DAG.getValueType(Node->getOperand(0).getValueType()));
2516        break;
2517      case ISD::FP_EXTEND:
2518        Result = PromoteOp(Node->getOperand(0));
2519        if (Result.getValueType() != Op.getValueType())
2520          // Dynamically dead while we have only 2 FP types.
2521          Result = DAG.getNode(ISD::FP_EXTEND, Op.getValueType(), Result);
2522        break;
2523      case ISD::FP_ROUND:
2524        Result = PromoteOp(Node->getOperand(0));
2525        Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
2526        break;
2527      }
2528    }
2529    break;
2530  case ISD::FP_ROUND_INREG:
2531  case ISD::SIGN_EXTEND_INREG: {
2532    Tmp1 = LegalizeOp(Node->getOperand(0));
2533    MVT::ValueType ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2534
2535    // If this operation is not supported, convert it to a shl/shr or load/store
2536    // pair.
2537    switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
2538    default: assert(0 && "This action not supported for this op yet!");
2539    case TargetLowering::Legal:
2540      Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
2541      break;
2542    case TargetLowering::Expand:
2543      // If this is an integer extend and shifts are supported, do that.
2544      if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
2545        // NOTE: we could fall back on load/store here too for targets without
2546        // SAR.  However, it is doubtful that any exist.
2547        unsigned BitsDiff = MVT::getSizeInBits(Node->getValueType(0)) -
2548                            MVT::getSizeInBits(ExtraVT);
2549        SDOperand ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
2550        Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
2551                             Node->getOperand(0), ShiftCst);
2552        Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
2553                             Result, ShiftCst);
2554      } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
2555        // The only way we can lower this is to turn it into a STORETRUNC,
2556        // EXTLOAD pair, targetting a temporary location (a stack slot).
2557
2558        // NOTE: there is a choice here between constantly creating new stack
2559        // slots and always reusing the same one.  We currently always create
2560        // new ones, as reuse may inhibit scheduling.
2561        const Type *Ty = MVT::getTypeForValueType(ExtraVT);
2562        unsigned TySize = (unsigned)TLI.getTargetData().getTypeSize(Ty);
2563        unsigned Align  = TLI.getTargetData().getTypeAlignment(Ty);
2564        MachineFunction &MF = DAG.getMachineFunction();
2565        int SSFI =
2566          MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
2567        SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
2568        Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, DAG.getEntryNode(),
2569                             Node->getOperand(0), StackSlot,
2570                             DAG.getSrcValue(NULL), DAG.getValueType(ExtraVT));
2571        Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
2572                                Result, StackSlot, DAG.getSrcValue(NULL),
2573                                ExtraVT);
2574      } else {
2575        assert(0 && "Unknown op");
2576      }
2577      break;
2578    }
2579    break;
2580  }
2581  }
2582
2583  // Make sure that the generated code is itself legal.
2584  if (Result != Op)
2585    Result = LegalizeOp(Result);
2586
2587  // Note that LegalizeOp may be reentered even from single-use nodes, which
2588  // means that we always must cache transformed nodes.
2589  AddLegalizedOperand(Op, Result);
2590  return Result;
2591}
2592
2593/// PromoteOp - Given an operation that produces a value in an invalid type,
2594/// promote it to compute the value into a larger type.  The produced value will
2595/// have the correct bits for the low portion of the register, but no guarantee
2596/// is made about the top bits: it may be zero, sign-extended, or garbage.
2597SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
2598  MVT::ValueType VT = Op.getValueType();
2599  MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
2600  assert(getTypeAction(VT) == Promote &&
2601         "Caller should expand or legalize operands that are not promotable!");
2602  assert(NVT > VT && MVT::isInteger(NVT) == MVT::isInteger(VT) &&
2603         "Cannot promote to smaller type!");
2604
2605  SDOperand Tmp1, Tmp2, Tmp3;
2606  SDOperand Result;
2607  SDNode *Node = Op.Val;
2608
2609  std::map<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
2610  if (I != PromotedNodes.end()) return I->second;
2611
2612  switch (Node->getOpcode()) {
2613  case ISD::CopyFromReg:
2614    assert(0 && "CopyFromReg must be legal!");
2615  default:
2616    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
2617    assert(0 && "Do not know how to promote this operator!");
2618    abort();
2619  case ISD::UNDEF:
2620    Result = DAG.getNode(ISD::UNDEF, NVT);
2621    break;
2622  case ISD::Constant:
2623    if (VT != MVT::i1)
2624      Result = DAG.getNode(ISD::SIGN_EXTEND, NVT, Op);
2625    else
2626      Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
2627    assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
2628    break;
2629  case ISD::ConstantFP:
2630    Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
2631    assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
2632    break;
2633
2634  case ISD::SETCC:
2635    assert(isTypeLegal(TLI.getSetCCResultTy()) && "SetCC type is not legal??");
2636    Result = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),Node->getOperand(0),
2637                         Node->getOperand(1), Node->getOperand(2));
2638    break;
2639
2640  case ISD::TRUNCATE:
2641    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2642    case Legal:
2643      Result = LegalizeOp(Node->getOperand(0));
2644      assert(Result.getValueType() >= NVT &&
2645             "This truncation doesn't make sense!");
2646      if (Result.getValueType() > NVT)    // Truncate to NVT instead of VT
2647        Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
2648      break;
2649    case Promote:
2650      // The truncation is not required, because we don't guarantee anything
2651      // about high bits anyway.
2652      Result = PromoteOp(Node->getOperand(0));
2653      break;
2654    case Expand:
2655      ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
2656      // Truncate the low part of the expanded value to the result type
2657      Result = DAG.getNode(ISD::TRUNCATE, NVT, Tmp1);
2658    }
2659    break;
2660  case ISD::SIGN_EXTEND:
2661  case ISD::ZERO_EXTEND:
2662  case ISD::ANY_EXTEND:
2663    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2664    case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
2665    case Legal:
2666      // Input is legal?  Just do extend all the way to the larger type.
2667      Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
2668      break;
2669    case Promote:
2670      // Promote the reg if it's smaller.
2671      Result = PromoteOp(Node->getOperand(0));
2672      // The high bits are not guaranteed to be anything.  Insert an extend.
2673      if (Node->getOpcode() == ISD::SIGN_EXTEND)
2674        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
2675                         DAG.getValueType(Node->getOperand(0).getValueType()));
2676      else if (Node->getOpcode() == ISD::ZERO_EXTEND)
2677        Result = DAG.getZeroExtendInReg(Result,
2678                                        Node->getOperand(0).getValueType());
2679      break;
2680    }
2681    break;
2682  case ISD::BIT_CONVERT:
2683    Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2684    Result = PromoteOp(Result);
2685    break;
2686
2687  case ISD::FP_EXTEND:
2688    assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
2689  case ISD::FP_ROUND:
2690    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2691    case Expand: assert(0 && "BUG: Cannot expand FP regs!");
2692    case Promote:  assert(0 && "Unreachable with 2 FP types!");
2693    case Legal:
2694      // Input is legal?  Do an FP_ROUND_INREG.
2695      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Node->getOperand(0),
2696                           DAG.getValueType(VT));
2697      break;
2698    }
2699    break;
2700
2701  case ISD::SINT_TO_FP:
2702  case ISD::UINT_TO_FP:
2703    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2704    case Legal:
2705      // No extra round required here.
2706      Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
2707      break;
2708
2709    case Promote:
2710      Result = PromoteOp(Node->getOperand(0));
2711      if (Node->getOpcode() == ISD::SINT_TO_FP)
2712        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2713                             Result,
2714                         DAG.getValueType(Node->getOperand(0).getValueType()));
2715      else
2716        Result = DAG.getZeroExtendInReg(Result,
2717                                        Node->getOperand(0).getValueType());
2718      // No extra round required here.
2719      Result = DAG.getNode(Node->getOpcode(), NVT, Result);
2720      break;
2721    case Expand:
2722      Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, NVT,
2723                             Node->getOperand(0));
2724      // Round if we cannot tolerate excess precision.
2725      if (NoExcessFPPrecision)
2726        Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2727                             DAG.getValueType(VT));
2728      break;
2729    }
2730    break;
2731
2732  case ISD::SIGN_EXTEND_INREG:
2733    Result = PromoteOp(Node->getOperand(0));
2734    Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
2735                         Node->getOperand(1));
2736    break;
2737  case ISD::FP_TO_SINT:
2738  case ISD::FP_TO_UINT:
2739    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2740    case Legal:
2741      Tmp1 = Node->getOperand(0);
2742      break;
2743    case Promote:
2744      // The input result is prerounded, so we don't have to do anything
2745      // special.
2746      Tmp1 = PromoteOp(Node->getOperand(0));
2747      break;
2748    case Expand:
2749      assert(0 && "not implemented");
2750    }
2751    // If we're promoting a UINT to a larger size, check to see if the new node
2752    // will be legal.  If it isn't, check to see if FP_TO_SINT is legal, since
2753    // we can use that instead.  This allows us to generate better code for
2754    // FP_TO_UINT for small destination sizes on targets where FP_TO_UINT is not
2755    // legal, such as PowerPC.
2756    if (Node->getOpcode() == ISD::FP_TO_UINT &&
2757        !TLI.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
2758        (TLI.isOperationLegal(ISD::FP_TO_SINT, NVT) ||
2759         TLI.getOperationAction(ISD::FP_TO_SINT, NVT)==TargetLowering::Custom)){
2760      Result = DAG.getNode(ISD::FP_TO_SINT, NVT, Tmp1);
2761    } else {
2762      Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2763    }
2764    break;
2765
2766  case ISD::FABS:
2767  case ISD::FNEG:
2768    Tmp1 = PromoteOp(Node->getOperand(0));
2769    assert(Tmp1.getValueType() == NVT);
2770    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2771    // NOTE: we do not have to do any extra rounding here for
2772    // NoExcessFPPrecision, because we know the input will have the appropriate
2773    // precision, and these operations don't modify precision at all.
2774    break;
2775
2776  case ISD::FSQRT:
2777  case ISD::FSIN:
2778  case ISD::FCOS:
2779    Tmp1 = PromoteOp(Node->getOperand(0));
2780    assert(Tmp1.getValueType() == NVT);
2781    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2782    if (NoExcessFPPrecision)
2783      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2784                           DAG.getValueType(VT));
2785    break;
2786
2787  case ISD::AND:
2788  case ISD::OR:
2789  case ISD::XOR:
2790  case ISD::ADD:
2791  case ISD::SUB:
2792  case ISD::MUL:
2793    // The input may have strange things in the top bits of the registers, but
2794    // these operations don't care.  They may have weird bits going out, but
2795    // that too is okay if they are integer operations.
2796    Tmp1 = PromoteOp(Node->getOperand(0));
2797    Tmp2 = PromoteOp(Node->getOperand(1));
2798    assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
2799    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2800    break;
2801  case ISD::FADD:
2802  case ISD::FSUB:
2803  case ISD::FMUL:
2804    Tmp1 = PromoteOp(Node->getOperand(0));
2805    Tmp2 = PromoteOp(Node->getOperand(1));
2806    assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
2807    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2808
2809    // Floating point operations will give excess precision that we may not be
2810    // able to tolerate.  If we DO allow excess precision, just leave it,
2811    // otherwise excise it.
2812    // FIXME: Why would we need to round FP ops more than integer ones?
2813    //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
2814    if (NoExcessFPPrecision)
2815      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2816                           DAG.getValueType(VT));
2817    break;
2818
2819  case ISD::SDIV:
2820  case ISD::SREM:
2821    // These operators require that their input be sign extended.
2822    Tmp1 = PromoteOp(Node->getOperand(0));
2823    Tmp2 = PromoteOp(Node->getOperand(1));
2824    if (MVT::isInteger(NVT)) {
2825      Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
2826                         DAG.getValueType(VT));
2827      Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
2828                         DAG.getValueType(VT));
2829    }
2830    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2831
2832    // Perform FP_ROUND: this is probably overly pessimistic.
2833    if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
2834      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2835                           DAG.getValueType(VT));
2836    break;
2837  case ISD::FDIV:
2838  case ISD::FREM:
2839  case ISD::FCOPYSIGN:
2840    // These operators require that their input be fp extended.
2841    Tmp1 = PromoteOp(Node->getOperand(0));
2842    Tmp2 = PromoteOp(Node->getOperand(1));
2843    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2844
2845    // Perform FP_ROUND: this is probably overly pessimistic.
2846    if (NoExcessFPPrecision && Node->getOpcode() != ISD::FCOPYSIGN)
2847      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2848                           DAG.getValueType(VT));
2849    break;
2850
2851  case ISD::UDIV:
2852  case ISD::UREM:
2853    // These operators require that their input be zero extended.
2854    Tmp1 = PromoteOp(Node->getOperand(0));
2855    Tmp2 = PromoteOp(Node->getOperand(1));
2856    assert(MVT::isInteger(NVT) && "Operators don't apply to FP!");
2857    Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
2858    Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
2859    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2860    break;
2861
2862  case ISD::SHL:
2863    Tmp1 = PromoteOp(Node->getOperand(0));
2864    Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Node->getOperand(1));
2865    break;
2866  case ISD::SRA:
2867    // The input value must be properly sign extended.
2868    Tmp1 = PromoteOp(Node->getOperand(0));
2869    Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
2870                       DAG.getValueType(VT));
2871    Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Node->getOperand(1));
2872    break;
2873  case ISD::SRL:
2874    // The input value must be properly zero extended.
2875    Tmp1 = PromoteOp(Node->getOperand(0));
2876    Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
2877    Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Node->getOperand(1));
2878    break;
2879
2880  case ISD::VAARG:
2881    Tmp1 = Node->getOperand(0);   // Get the chain.
2882    Tmp2 = Node->getOperand(1);   // Get the pointer.
2883    if (TLI.getOperationAction(ISD::VAARG, VT) == TargetLowering::Custom) {
2884      Tmp3 = DAG.getVAArg(VT, Tmp1, Tmp2, Node->getOperand(2));
2885      Result = TLI.CustomPromoteOperation(Tmp3, DAG);
2886    } else {
2887      SDOperand VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2,
2888                                     Node->getOperand(2));
2889      // Increment the pointer, VAList, to the next vaarg
2890      Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList,
2891                         DAG.getConstant(MVT::getSizeInBits(VT)/8,
2892                                         TLI.getPointerTy()));
2893      // Store the incremented VAList to the legalized pointer
2894      Tmp3 = DAG.getNode(ISD::STORE, MVT::Other, VAList.getValue(1), Tmp3, Tmp2,
2895                         Node->getOperand(2));
2896      // Load the actual argument out of the pointer VAList
2897      Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Tmp3, VAList,
2898                              DAG.getSrcValue(0), VT);
2899    }
2900    // Remember that we legalized the chain.
2901    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
2902    break;
2903
2904  case ISD::LOAD:
2905    Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Node->getOperand(0),
2906                            Node->getOperand(1), Node->getOperand(2), VT);
2907    // Remember that we legalized the chain.
2908    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
2909    break;
2910  case ISD::SEXTLOAD:
2911  case ISD::ZEXTLOAD:
2912  case ISD::EXTLOAD:
2913    Result = DAG.getExtLoad(Node->getOpcode(), NVT, Node->getOperand(0),
2914                            Node->getOperand(1), Node->getOperand(2),
2915                            cast<VTSDNode>(Node->getOperand(3))->getVT());
2916    // Remember that we legalized the chain.
2917    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
2918    break;
2919  case ISD::SELECT:
2920    Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
2921    Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
2922    Result = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), Tmp2, Tmp3);
2923    break;
2924  case ISD::SELECT_CC:
2925    Tmp2 = PromoteOp(Node->getOperand(2));   // True
2926    Tmp3 = PromoteOp(Node->getOperand(3));   // False
2927    Result = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
2928                         Node->getOperand(1), Tmp2, Tmp3, Node->getOperand(4));
2929    break;
2930  case ISD::BSWAP:
2931    Tmp1 = Node->getOperand(0);
2932    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
2933    Tmp1 = DAG.getNode(ISD::BSWAP, NVT, Tmp1);
2934    Result = DAG.getNode(ISD::SRL, NVT, Tmp1,
2935                         DAG.getConstant(getSizeInBits(NVT) - getSizeInBits(VT),
2936                                         TLI.getShiftAmountTy()));
2937    break;
2938  case ISD::CTPOP:
2939  case ISD::CTTZ:
2940  case ISD::CTLZ:
2941    // Zero extend the argument
2942    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
2943    // Perform the larger operation, then subtract if needed.
2944    Tmp1 = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2945    switch(Node->getOpcode()) {
2946    case ISD::CTPOP:
2947      Result = Tmp1;
2948      break;
2949    case ISD::CTTZ:
2950      // if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
2951      Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
2952                          DAG.getConstant(getSizeInBits(NVT), NVT), ISD::SETEQ);
2953      Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
2954                           DAG.getConstant(getSizeInBits(VT), NVT), Tmp1);
2955      break;
2956    case ISD::CTLZ:
2957      //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
2958      Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
2959                           DAG.getConstant(getSizeInBits(NVT) -
2960                                           getSizeInBits(VT), NVT));
2961      break;
2962    }
2963    break;
2964  case ISD::VEXTRACT_VECTOR_ELT:
2965    Result = PromoteOp(LowerVEXTRACT_VECTOR_ELT(Op));
2966    break;
2967  }
2968
2969  assert(Result.Val && "Didn't set a result!");
2970
2971  // Make sure the result is itself legal.
2972  Result = LegalizeOp(Result);
2973
2974  // Remember that we promoted this!
2975  AddPromotedOperand(Op, Result);
2976  return Result;
2977}
2978
2979/// LowerVEXTRACT_VECTOR_ELT - Lower a VEXTRACT_VECTOR_ELT operation into a
2980/// EXTRACT_VECTOR_ELT operation, to memory operations, or to scalar code based
2981/// on the vector type.  The return type of this matches the element type of the
2982/// vector, which may not be legal for the target.
2983SDOperand SelectionDAGLegalize::LowerVEXTRACT_VECTOR_ELT(SDOperand Op) {
2984  // We know that operand #0 is the Vec vector.  If the index is a constant
2985  // or if the invec is a supported hardware type, we can use it.  Otherwise,
2986  // lower to a store then an indexed load.
2987  SDOperand Vec = Op.getOperand(0);
2988  SDOperand Idx = LegalizeOp(Op.getOperand(1));
2989
2990  SDNode *InVal = Vec.Val;
2991  unsigned NumElems = cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
2992  MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
2993
2994  // Figure out if there is a Packed type corresponding to this Vector
2995  // type.  If so, convert to the packed type.
2996  MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
2997  if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
2998    // Turn this into a packed extract_vector_elt operation.
2999    Vec = PackVectorOp(Vec, TVT);
3000    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Op.getValueType(), Vec, Idx);
3001  } else if (NumElems == 1) {
3002    // This must be an access of the only element.  Return it.
3003    return PackVectorOp(Vec, EVT);
3004  } else if (ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
3005    SDOperand Lo, Hi;
3006    SplitVectorOp(Vec, Lo, Hi);
3007    if (CIdx->getValue() < NumElems/2) {
3008      Vec = Lo;
3009    } else {
3010      Vec = Hi;
3011      Idx = DAG.getConstant(CIdx->getValue() - NumElems/2, Idx.getValueType());
3012    }
3013
3014    // It's now an extract from the appropriate high or low part.  Recurse.
3015    Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
3016    return LowerVEXTRACT_VECTOR_ELT(Op);
3017  } else {
3018    // Variable index case for extract element.
3019    // FIXME: IMPLEMENT STORE/LOAD lowering.  Need alignment of stack slot!!
3020    assert(0 && "unimp!");
3021    return SDOperand();
3022  }
3023}
3024
3025
3026/// LegalizeSetCCOperands - Attempts to create a legal LHS and RHS for a SETCC
3027/// with condition CC on the current target.  This usually involves legalizing
3028/// or promoting the arguments.  In the case where LHS and RHS must be expanded,
3029/// there may be no choice but to create a new SetCC node to represent the
3030/// legalized value of setcc lhs, rhs.  In this case, the value is returned in
3031/// LHS, and the SDOperand returned in RHS has a nil SDNode value.
3032void SelectionDAGLegalize::LegalizeSetCCOperands(SDOperand &LHS,
3033                                                 SDOperand &RHS,
3034                                                 SDOperand &CC) {
3035  SDOperand Tmp1, Tmp2, Result;
3036
3037  switch (getTypeAction(LHS.getValueType())) {
3038  case Legal:
3039    Tmp1 = LegalizeOp(LHS);   // LHS
3040    Tmp2 = LegalizeOp(RHS);   // RHS
3041    break;
3042  case Promote:
3043    Tmp1 = PromoteOp(LHS);   // LHS
3044    Tmp2 = PromoteOp(RHS);   // RHS
3045
3046    // If this is an FP compare, the operands have already been extended.
3047    if (MVT::isInteger(LHS.getValueType())) {
3048      MVT::ValueType VT = LHS.getValueType();
3049      MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
3050
3051      // Otherwise, we have to insert explicit sign or zero extends.  Note
3052      // that we could insert sign extends for ALL conditions, but zero extend
3053      // is cheaper on many machines (an AND instead of two shifts), so prefer
3054      // it.
3055      switch (cast<CondCodeSDNode>(CC)->get()) {
3056      default: assert(0 && "Unknown integer comparison!");
3057      case ISD::SETEQ:
3058      case ISD::SETNE:
3059      case ISD::SETUGE:
3060      case ISD::SETUGT:
3061      case ISD::SETULE:
3062      case ISD::SETULT:
3063        // ALL of these operations will work if we either sign or zero extend
3064        // the operands (including the unsigned comparisons!).  Zero extend is
3065        // usually a simpler/cheaper operation, so prefer it.
3066        Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
3067        Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
3068        break;
3069      case ISD::SETGE:
3070      case ISD::SETGT:
3071      case ISD::SETLT:
3072      case ISD::SETLE:
3073        Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
3074                           DAG.getValueType(VT));
3075        Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
3076                           DAG.getValueType(VT));
3077        break;
3078      }
3079    }
3080    break;
3081  case Expand:
3082    SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
3083    ExpandOp(LHS, LHSLo, LHSHi);
3084    ExpandOp(RHS, RHSLo, RHSHi);
3085    switch (cast<CondCodeSDNode>(CC)->get()) {
3086    case ISD::SETEQ:
3087    case ISD::SETNE:
3088      if (RHSLo == RHSHi)
3089        if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo))
3090          if (RHSCST->isAllOnesValue()) {
3091            // Comparison to -1.
3092            Tmp1 = DAG.getNode(ISD::AND, LHSLo.getValueType(), LHSLo, LHSHi);
3093            Tmp2 = RHSLo;
3094            break;
3095          }
3096
3097      Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
3098      Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
3099      Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
3100      Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
3101      break;
3102    default:
3103      // If this is a comparison of the sign bit, just look at the top part.
3104      // X > -1,  x < 0
3105      if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(RHS))
3106        if ((cast<CondCodeSDNode>(CC)->get() == ISD::SETLT &&
3107             CST->getValue() == 0) ||             // X < 0
3108            (cast<CondCodeSDNode>(CC)->get() == ISD::SETGT &&
3109             CST->isAllOnesValue())) {            // X > -1
3110          Tmp1 = LHSHi;
3111          Tmp2 = RHSHi;
3112          break;
3113        }
3114
3115      // FIXME: This generated code sucks.
3116      ISD::CondCode LowCC;
3117      switch (cast<CondCodeSDNode>(CC)->get()) {
3118      default: assert(0 && "Unknown integer setcc!");
3119      case ISD::SETLT:
3120      case ISD::SETULT: LowCC = ISD::SETULT; break;
3121      case ISD::SETGT:
3122      case ISD::SETUGT: LowCC = ISD::SETUGT; break;
3123      case ISD::SETLE:
3124      case ISD::SETULE: LowCC = ISD::SETULE; break;
3125      case ISD::SETGE:
3126      case ISD::SETUGE: LowCC = ISD::SETUGE; break;
3127      }
3128
3129      // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
3130      // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
3131      // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
3132
3133      // NOTE: on targets without efficient SELECT of bools, we can always use
3134      // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
3135      Tmp1 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSLo, RHSLo, LowCC);
3136      Tmp2 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(), LHSHi, RHSHi, CC);
3137      Result = DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, ISD::SETEQ);
3138      Result = LegalizeOp(DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
3139                                      Result, Tmp1, Tmp2));
3140      Tmp1 = Result;
3141      Tmp2 = SDOperand();
3142    }
3143  }
3144  LHS = Tmp1;
3145  RHS = Tmp2;
3146}
3147
3148/// ExpandBIT_CONVERT - Expand a BIT_CONVERT node into a store/load combination.
3149/// The resultant code need not be legal.  Note that SrcOp is the input operand
3150/// to the BIT_CONVERT, not the BIT_CONVERT node itself.
3151SDOperand SelectionDAGLegalize::ExpandBIT_CONVERT(MVT::ValueType DestVT,
3152                                                  SDOperand SrcOp) {
3153  // Create the stack frame object.
3154  SDOperand FIPtr = CreateStackTemporary(DestVT);
3155
3156  // Emit a store to the stack slot.
3157  SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3158                                SrcOp, FIPtr, DAG.getSrcValue(NULL));
3159  // Result is a load from the stack slot.
3160  return DAG.getLoad(DestVT, Store, FIPtr, DAG.getSrcValue(0));
3161}
3162
3163/// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
3164/// support the operation, but do support the resultant packed vector type.
3165SDOperand SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
3166
3167  // If the only non-undef value is the low element, turn this into a
3168  // SCALAR_TO_VECTOR node.  If this is { X, X, X, X }, determine X.
3169  unsigned NumElems = Node->getNumOperands();
3170  bool isOnlyLowElement = true;
3171  SDOperand SplatValue = Node->getOperand(0);
3172  std::map<SDOperand, std::vector<unsigned> > Values;
3173  Values[SplatValue].push_back(0);
3174  bool isConstant = true;
3175  if (!isa<ConstantFPSDNode>(SplatValue) && !isa<ConstantSDNode>(SplatValue) &&
3176      SplatValue.getOpcode() != ISD::UNDEF)
3177    isConstant = false;
3178
3179  for (unsigned i = 1; i < NumElems; ++i) {
3180    SDOperand V = Node->getOperand(i);
3181    std::map<SDOperand, std::vector<unsigned> >::iterator I = Values.find(V);
3182    if (I != Values.end())
3183      I->second.push_back(i);
3184    else
3185      Values[V].push_back(i);
3186    if (V.getOpcode() != ISD::UNDEF)
3187      isOnlyLowElement = false;
3188    if (SplatValue != V)
3189      SplatValue = SDOperand(0,0);
3190
3191    // If this isn't a constant element or an undef, we can't use a constant
3192    // pool load.
3193    if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V) &&
3194        V.getOpcode() != ISD::UNDEF)
3195      isConstant = false;
3196  }
3197
3198  if (isOnlyLowElement) {
3199    // If the low element is an undef too, then this whole things is an undef.
3200    if (Node->getOperand(0).getOpcode() == ISD::UNDEF)
3201      return DAG.getNode(ISD::UNDEF, Node->getValueType(0));
3202    // Otherwise, turn this into a scalar_to_vector node.
3203    return DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0),
3204                       Node->getOperand(0));
3205  }
3206
3207  // If all elements are constants, create a load from the constant pool.
3208  if (isConstant) {
3209    MVT::ValueType VT = Node->getValueType(0);
3210    const Type *OpNTy =
3211      MVT::getTypeForValueType(Node->getOperand(0).getValueType());
3212    std::vector<Constant*> CV;
3213    for (unsigned i = 0, e = NumElems; i != e; ++i) {
3214      if (ConstantFPSDNode *V =
3215          dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
3216        CV.push_back(ConstantFP::get(OpNTy, V->getValue()));
3217      } else if (ConstantSDNode *V =
3218                 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
3219        CV.push_back(ConstantUInt::get(OpNTy, V->getValue()));
3220      } else {
3221        assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
3222        CV.push_back(UndefValue::get(OpNTy));
3223      }
3224    }
3225    Constant *CP = ConstantPacked::get(CV);
3226    SDOperand CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
3227    return DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
3228                       DAG.getSrcValue(NULL));
3229  }
3230
3231  if (SplatValue.Val) {   // Splat of one value?
3232    // Build the shuffle constant vector: <0, 0, 0, 0>
3233    MVT::ValueType MaskVT =
3234      MVT::getIntVectorWithNumElements(NumElems);
3235    SDOperand Zero = DAG.getConstant(0, MVT::getVectorBaseType(MaskVT));
3236    std::vector<SDOperand> ZeroVec(NumElems, Zero);
3237    SDOperand SplatMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, ZeroVec);
3238
3239    // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
3240    if (TLI.isShuffleLegal(Node->getValueType(0), SplatMask)) {
3241      // Get the splatted value into the low element of a vector register.
3242      SDOperand LowValVec =
3243        DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0), SplatValue);
3244
3245      // Return shuffle(LowValVec, undef, <0,0,0,0>)
3246      return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), LowValVec,
3247                         DAG.getNode(ISD::UNDEF, Node->getValueType(0)),
3248                         SplatMask);
3249    }
3250  }
3251
3252  // If there are only two unique elements, we may be able to turn this into a
3253  // vector shuffle.
3254  if (Values.size() == 2) {
3255    // Build the shuffle constant vector: e.g. <0, 4, 0, 4>
3256    MVT::ValueType MaskVT =
3257      MVT::getIntVectorWithNumElements(NumElems);
3258    std::vector<SDOperand> MaskVec(NumElems);
3259    unsigned i = 0;
3260    for (std::map<SDOperand,std::vector<unsigned> >::iterator I=Values.begin(),
3261           E = Values.end(); I != E; ++I) {
3262      for (std::vector<unsigned>::iterator II = I->second.begin(),
3263             EE = I->second.end(); II != EE; ++II)
3264        MaskVec[*II] = DAG.getConstant(i, MVT::getVectorBaseType(MaskVT));
3265      i += NumElems;
3266    }
3267    SDOperand ShuffleMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
3268
3269    // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
3270    if (TLI.isShuffleLegal(Node->getValueType(0), ShuffleMask) &&
3271        TLI.isOperationLegal(ISD::SCALAR_TO_VECTOR, Node->getValueType(0))) {
3272      std::vector<SDOperand> Ops;
3273      for(std::map<SDOperand,std::vector<unsigned> >::iterator I=Values.begin(),
3274            E = Values.end(); I != E; ++I) {
3275        SDOperand Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0),
3276                                   I->first);
3277        Ops.push_back(Op);
3278      }
3279      Ops.push_back(ShuffleMask);
3280
3281      // Return shuffle(LoValVec, HiValVec, <0,1,0,1>)
3282      return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), Ops);
3283    }
3284  }
3285
3286  // Otherwise, we can't handle this case efficiently.  Allocate a sufficiently
3287  // aligned object on the stack, store each element into it, then load
3288  // the result as a vector.
3289  MVT::ValueType VT = Node->getValueType(0);
3290  // Create the stack frame object.
3291  SDOperand FIPtr = CreateStackTemporary(VT);
3292
3293  // Emit a store of each element to the stack slot.
3294  std::vector<SDOperand> Stores;
3295  unsigned TypeByteSize =
3296    MVT::getSizeInBits(Node->getOperand(0).getValueType())/8;
3297  unsigned VectorSize = MVT::getSizeInBits(VT)/8;
3298  // Store (in the right endianness) the elements to memory.
3299  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
3300    // Ignore undef elements.
3301    if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
3302
3303    unsigned Offset = TypeByteSize*i;
3304
3305    SDOperand Idx = DAG.getConstant(Offset, FIPtr.getValueType());
3306    Idx = DAG.getNode(ISD::ADD, FIPtr.getValueType(), FIPtr, Idx);
3307
3308    Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3309                                 Node->getOperand(i), Idx,
3310                                 DAG.getSrcValue(NULL)));
3311  }
3312
3313  SDOperand StoreChain;
3314  if (!Stores.empty())    // Not all undef elements?
3315    StoreChain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores);
3316  else
3317    StoreChain = DAG.getEntryNode();
3318
3319  // Result is a load from the stack slot.
3320  return DAG.getLoad(VT, StoreChain, FIPtr, DAG.getSrcValue(0));
3321}
3322
3323/// CreateStackTemporary - Create a stack temporary, suitable for holding the
3324/// specified value type.
3325SDOperand SelectionDAGLegalize::CreateStackTemporary(MVT::ValueType VT) {
3326  MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
3327  unsigned ByteSize = MVT::getSizeInBits(VT)/8;
3328  int FrameIdx = FrameInfo->CreateStackObject(ByteSize, ByteSize);
3329  return DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
3330}
3331
3332void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
3333                                            SDOperand Op, SDOperand Amt,
3334                                            SDOperand &Lo, SDOperand &Hi) {
3335  // Expand the subcomponents.
3336  SDOperand LHSL, LHSH;
3337  ExpandOp(Op, LHSL, LHSH);
3338
3339  std::vector<SDOperand> Ops;
3340  Ops.push_back(LHSL);
3341  Ops.push_back(LHSH);
3342  Ops.push_back(Amt);
3343  std::vector<MVT::ValueType> VTs(2, LHSL.getValueType());
3344  Lo = DAG.getNode(NodeOp, VTs, Ops);
3345  Hi = Lo.getValue(1);
3346}
3347
3348
3349/// ExpandShift - Try to find a clever way to expand this shift operation out to
3350/// smaller elements.  If we can't find a way that is more efficient than a
3351/// libcall on this target, return false.  Otherwise, return true with the
3352/// low-parts expanded into Lo and Hi.
3353bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDOperand Op,SDOperand Amt,
3354                                       SDOperand &Lo, SDOperand &Hi) {
3355  assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
3356         "This is not a shift!");
3357
3358  MVT::ValueType NVT = TLI.getTypeToTransformTo(Op.getValueType());
3359  SDOperand ShAmt = LegalizeOp(Amt);
3360  MVT::ValueType ShTy = ShAmt.getValueType();
3361  unsigned VTBits = MVT::getSizeInBits(Op.getValueType());
3362  unsigned NVTBits = MVT::getSizeInBits(NVT);
3363
3364  // Handle the case when Amt is an immediate.  Other cases are currently broken
3365  // and are disabled.
3366  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Amt.Val)) {
3367    unsigned Cst = CN->getValue();
3368    // Expand the incoming operand to be shifted, so that we have its parts
3369    SDOperand InL, InH;
3370    ExpandOp(Op, InL, InH);
3371    switch(Opc) {
3372    case ISD::SHL:
3373      if (Cst > VTBits) {
3374        Lo = DAG.getConstant(0, NVT);
3375        Hi = DAG.getConstant(0, NVT);
3376      } else if (Cst > NVTBits) {
3377        Lo = DAG.getConstant(0, NVT);
3378        Hi = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst-NVTBits,ShTy));
3379      } else if (Cst == NVTBits) {
3380        Lo = DAG.getConstant(0, NVT);
3381        Hi = InL;
3382      } else {
3383        Lo = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst, ShTy));
3384        Hi = DAG.getNode(ISD::OR, NVT,
3385           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(Cst, ShTy)),
3386           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(NVTBits-Cst, ShTy)));
3387      }
3388      return true;
3389    case ISD::SRL:
3390      if (Cst > VTBits) {
3391        Lo = DAG.getConstant(0, NVT);
3392        Hi = DAG.getConstant(0, NVT);
3393      } else if (Cst > NVTBits) {
3394        Lo = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst-NVTBits,ShTy));
3395        Hi = DAG.getConstant(0, NVT);
3396      } else if (Cst == NVTBits) {
3397        Lo = InH;
3398        Hi = DAG.getConstant(0, NVT);
3399      } else {
3400        Lo = DAG.getNode(ISD::OR, NVT,
3401           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
3402           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
3403        Hi = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst, ShTy));
3404      }
3405      return true;
3406    case ISD::SRA:
3407      if (Cst > VTBits) {
3408        Hi = Lo = DAG.getNode(ISD::SRA, NVT, InH,
3409                              DAG.getConstant(NVTBits-1, ShTy));
3410      } else if (Cst > NVTBits) {
3411        Lo = DAG.getNode(ISD::SRA, NVT, InH,
3412                           DAG.getConstant(Cst-NVTBits, ShTy));
3413        Hi = DAG.getNode(ISD::SRA, NVT, InH,
3414                              DAG.getConstant(NVTBits-1, ShTy));
3415      } else if (Cst == NVTBits) {
3416        Lo = InH;
3417        Hi = DAG.getNode(ISD::SRA, NVT, InH,
3418                              DAG.getConstant(NVTBits-1, ShTy));
3419      } else {
3420        Lo = DAG.getNode(ISD::OR, NVT,
3421           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
3422           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
3423        Hi = DAG.getNode(ISD::SRA, NVT, InH, DAG.getConstant(Cst, ShTy));
3424      }
3425      return true;
3426    }
3427  }
3428  return false;
3429}
3430
3431
3432// ExpandLibCall - Expand a node into a call to a libcall.  If the result value
3433// does not fit into a register, return the lo part and set the hi part to the
3434// by-reg argument.  If it does fit into a single register, return the result
3435// and leave the Hi part unset.
3436SDOperand SelectionDAGLegalize::ExpandLibCall(const char *Name, SDNode *Node,
3437                                              SDOperand &Hi) {
3438  assert(!IsLegalizingCall && "Cannot overlap legalization of calls!");
3439  // The input chain to this libcall is the entry node of the function.
3440  // Legalizing the call will automatically add the previous call to the
3441  // dependence.
3442  SDOperand InChain = DAG.getEntryNode();
3443
3444  TargetLowering::ArgListTy Args;
3445  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
3446    MVT::ValueType ArgVT = Node->getOperand(i).getValueType();
3447    const Type *ArgTy = MVT::getTypeForValueType(ArgVT);
3448    Args.push_back(std::make_pair(Node->getOperand(i), ArgTy));
3449  }
3450  SDOperand Callee = DAG.getExternalSymbol(Name, TLI.getPointerTy());
3451
3452  // Splice the libcall in wherever FindInputOutputChains tells us to.
3453  const Type *RetTy = MVT::getTypeForValueType(Node->getValueType(0));
3454  std::pair<SDOperand,SDOperand> CallInfo =
3455    TLI.LowerCallTo(InChain, RetTy, false, CallingConv::C, false,
3456                    Callee, Args, DAG);
3457
3458  // Legalize the call sequence, starting with the chain.  This will advance
3459  // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
3460  // was added by LowerCallTo (guaranteeing proper serialization of calls).
3461  LegalizeOp(CallInfo.second);
3462  SDOperand Result;
3463  switch (getTypeAction(CallInfo.first.getValueType())) {
3464  default: assert(0 && "Unknown thing");
3465  case Legal:
3466    Result = CallInfo.first;
3467    break;
3468  case Expand:
3469    ExpandOp(CallInfo.first, Result, Hi);
3470    break;
3471  }
3472  return Result;
3473}
3474
3475
3476/// ExpandIntToFP - Expand a [US]INT_TO_FP operation, assuming that the
3477/// destination type is legal.
3478SDOperand SelectionDAGLegalize::
3479ExpandIntToFP(bool isSigned, MVT::ValueType DestTy, SDOperand Source) {
3480  assert(isTypeLegal(DestTy) && "Destination type is not legal!");
3481  assert(getTypeAction(Source.getValueType()) == Expand &&
3482         "This is not an expansion!");
3483  assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
3484
3485  if (!isSigned) {
3486    assert(Source.getValueType() == MVT::i64 &&
3487           "This only works for 64-bit -> FP");
3488    // The 64-bit value loaded will be incorrectly if the 'sign bit' of the
3489    // incoming integer is set.  To handle this, we dynamically test to see if
3490    // it is set, and, if so, add a fudge factor.
3491    SDOperand Lo, Hi;
3492    ExpandOp(Source, Lo, Hi);
3493
3494    // If this is unsigned, and not supported, first perform the conversion to
3495    // signed, then adjust the result if the sign bit is set.
3496    SDOperand SignedConv = ExpandIntToFP(true, DestTy,
3497                   DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), Lo, Hi));
3498
3499    SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Hi,
3500                                     DAG.getConstant(0, Hi.getValueType()),
3501                                     ISD::SETLT);
3502    SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
3503    SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
3504                                      SignSet, Four, Zero);
3505    uint64_t FF = 0x5f800000ULL;
3506    if (TLI.isLittleEndian()) FF <<= 32;
3507    static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
3508
3509    SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
3510    CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
3511    SDOperand FudgeInReg;
3512    if (DestTy == MVT::f32)
3513      FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
3514                               DAG.getSrcValue(NULL));
3515    else {
3516      assert(DestTy == MVT::f64 && "Unexpected conversion");
3517      FudgeInReg = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
3518                                  CPIdx, DAG.getSrcValue(NULL), MVT::f32);
3519    }
3520    return DAG.getNode(ISD::FADD, DestTy, SignedConv, FudgeInReg);
3521  }
3522
3523  // Check to see if the target has a custom way to lower this.  If so, use it.
3524  switch (TLI.getOperationAction(ISD::SINT_TO_FP, Source.getValueType())) {
3525  default: assert(0 && "This action not implemented for this operation!");
3526  case TargetLowering::Legal:
3527  case TargetLowering::Expand:
3528    break;   // This case is handled below.
3529  case TargetLowering::Custom: {
3530    SDOperand NV = TLI.LowerOperation(DAG.getNode(ISD::SINT_TO_FP, DestTy,
3531                                                  Source), DAG);
3532    if (NV.Val)
3533      return LegalizeOp(NV);
3534    break;   // The target decided this was legal after all
3535  }
3536  }
3537
3538  // Expand the source, then glue it back together for the call.  We must expand
3539  // the source in case it is shared (this pass of legalize must traverse it).
3540  SDOperand SrcLo, SrcHi;
3541  ExpandOp(Source, SrcLo, SrcHi);
3542  Source = DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), SrcLo, SrcHi);
3543
3544  const char *FnName = 0;
3545  if (DestTy == MVT::f32)
3546    FnName = "__floatdisf";
3547  else {
3548    assert(DestTy == MVT::f64 && "Unknown fp value type!");
3549    FnName = "__floatdidf";
3550  }
3551
3552  Source = DAG.getNode(ISD::SINT_TO_FP, DestTy, Source);
3553  SDOperand UnusedHiPart;
3554  return ExpandLibCall(FnName, Source.Val, UnusedHiPart);
3555}
3556
3557/// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
3558/// INT_TO_FP operation of the specified operand when the target requests that
3559/// we expand it.  At this point, we know that the result and operand types are
3560/// legal for the target.
3561SDOperand SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
3562                                                     SDOperand Op0,
3563                                                     MVT::ValueType DestVT) {
3564  if (Op0.getValueType() == MVT::i32) {
3565    // simple 32-bit [signed|unsigned] integer to float/double expansion
3566
3567    // get the stack frame index of a 8 byte buffer
3568    MachineFunction &MF = DAG.getMachineFunction();
3569    int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
3570    // get address of 8 byte buffer
3571    SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3572    // word offset constant for Hi/Lo address computation
3573    SDOperand WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
3574    // set up Hi and Lo (into buffer) address based on endian
3575    SDOperand Hi = StackSlot;
3576    SDOperand Lo = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot,WordOff);
3577    if (TLI.isLittleEndian())
3578      std::swap(Hi, Lo);
3579
3580    // if signed map to unsigned space
3581    SDOperand Op0Mapped;
3582    if (isSigned) {
3583      // constant used to invert sign bit (signed to unsigned mapping)
3584      SDOperand SignBit = DAG.getConstant(0x80000000u, MVT::i32);
3585      Op0Mapped = DAG.getNode(ISD::XOR, MVT::i32, Op0, SignBit);
3586    } else {
3587      Op0Mapped = Op0;
3588    }
3589    // store the lo of the constructed double - based on integer input
3590    SDOperand Store1 = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3591                                   Op0Mapped, Lo, DAG.getSrcValue(NULL));
3592    // initial hi portion of constructed double
3593    SDOperand InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
3594    // store the hi of the constructed double - biased exponent
3595    SDOperand Store2 = DAG.getNode(ISD::STORE, MVT::Other, Store1,
3596                                   InitialHi, Hi, DAG.getSrcValue(NULL));
3597    // load the constructed double
3598    SDOperand Load = DAG.getLoad(MVT::f64, Store2, StackSlot,
3599                               DAG.getSrcValue(NULL));
3600    // FP constant to bias correct the final result
3601    SDOperand Bias = DAG.getConstantFP(isSigned ?
3602                                            BitsToDouble(0x4330000080000000ULL)
3603                                          : BitsToDouble(0x4330000000000000ULL),
3604                                     MVT::f64);
3605    // subtract the bias
3606    SDOperand Sub = DAG.getNode(ISD::FSUB, MVT::f64, Load, Bias);
3607    // final result
3608    SDOperand Result;
3609    // handle final rounding
3610    if (DestVT == MVT::f64) {
3611      // do nothing
3612      Result = Sub;
3613    } else {
3614     // if f32 then cast to f32
3615      Result = DAG.getNode(ISD::FP_ROUND, MVT::f32, Sub);
3616    }
3617    return Result;
3618  }
3619  assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
3620  SDOperand Tmp1 = DAG.getNode(ISD::SINT_TO_FP, DestVT, Op0);
3621
3622  SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Op0,
3623                                   DAG.getConstant(0, Op0.getValueType()),
3624                                   ISD::SETLT);
3625  SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
3626  SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
3627                                    SignSet, Four, Zero);
3628
3629  // If the sign bit of the integer is set, the large number will be treated
3630  // as a negative number.  To counteract this, the dynamic code adds an
3631  // offset depending on the data type.
3632  uint64_t FF;
3633  switch (Op0.getValueType()) {
3634  default: assert(0 && "Unsupported integer type!");
3635  case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
3636  case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
3637  case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
3638  case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
3639  }
3640  if (TLI.isLittleEndian()) FF <<= 32;
3641  static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
3642
3643  SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
3644  CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
3645  SDOperand FudgeInReg;
3646  if (DestVT == MVT::f32)
3647    FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
3648                             DAG.getSrcValue(NULL));
3649  else {
3650    assert(DestVT == MVT::f64 && "Unexpected conversion");
3651    FudgeInReg = LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, MVT::f64,
3652                                           DAG.getEntryNode(), CPIdx,
3653                                           DAG.getSrcValue(NULL), MVT::f32));
3654  }
3655
3656  return DAG.getNode(ISD::FADD, DestVT, Tmp1, FudgeInReg);
3657}
3658
3659/// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
3660/// *INT_TO_FP operation of the specified operand when the target requests that
3661/// we promote it.  At this point, we know that the result and operand types are
3662/// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
3663/// operation that takes a larger input.
3664SDOperand SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDOperand LegalOp,
3665                                                      MVT::ValueType DestVT,
3666                                                      bool isSigned) {
3667  // First step, figure out the appropriate *INT_TO_FP operation to use.
3668  MVT::ValueType NewInTy = LegalOp.getValueType();
3669
3670  unsigned OpToUse = 0;
3671
3672  // Scan for the appropriate larger type to use.
3673  while (1) {
3674    NewInTy = (MVT::ValueType)(NewInTy+1);
3675    assert(MVT::isInteger(NewInTy) && "Ran out of possibilities!");
3676
3677    // If the target supports SINT_TO_FP of this type, use it.
3678    switch (TLI.getOperationAction(ISD::SINT_TO_FP, NewInTy)) {
3679      default: break;
3680      case TargetLowering::Legal:
3681        if (!TLI.isTypeLegal(NewInTy))
3682          break;  // Can't use this datatype.
3683        // FALL THROUGH.
3684      case TargetLowering::Custom:
3685        OpToUse = ISD::SINT_TO_FP;
3686        break;
3687    }
3688    if (OpToUse) break;
3689    if (isSigned) continue;
3690
3691    // If the target supports UINT_TO_FP of this type, use it.
3692    switch (TLI.getOperationAction(ISD::UINT_TO_FP, NewInTy)) {
3693      default: break;
3694      case TargetLowering::Legal:
3695        if (!TLI.isTypeLegal(NewInTy))
3696          break;  // Can't use this datatype.
3697        // FALL THROUGH.
3698      case TargetLowering::Custom:
3699        OpToUse = ISD::UINT_TO_FP;
3700        break;
3701    }
3702    if (OpToUse) break;
3703
3704    // Otherwise, try a larger type.
3705  }
3706
3707  // Okay, we found the operation and type to use.  Zero extend our input to the
3708  // desired type then run the operation on it.
3709  return DAG.getNode(OpToUse, DestVT,
3710                     DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
3711                                 NewInTy, LegalOp));
3712}
3713
3714/// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
3715/// FP_TO_*INT operation of the specified operand when the target requests that
3716/// we promote it.  At this point, we know that the result and operand types are
3717/// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
3718/// operation that returns a larger result.
3719SDOperand SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDOperand LegalOp,
3720                                                      MVT::ValueType DestVT,
3721                                                      bool isSigned) {
3722  // First step, figure out the appropriate FP_TO*INT operation to use.
3723  MVT::ValueType NewOutTy = DestVT;
3724
3725  unsigned OpToUse = 0;
3726
3727  // Scan for the appropriate larger type to use.
3728  while (1) {
3729    NewOutTy = (MVT::ValueType)(NewOutTy+1);
3730    assert(MVT::isInteger(NewOutTy) && "Ran out of possibilities!");
3731
3732    // If the target supports FP_TO_SINT returning this type, use it.
3733    switch (TLI.getOperationAction(ISD::FP_TO_SINT, NewOutTy)) {
3734    default: break;
3735    case TargetLowering::Legal:
3736      if (!TLI.isTypeLegal(NewOutTy))
3737        break;  // Can't use this datatype.
3738      // FALL THROUGH.
3739    case TargetLowering::Custom:
3740      OpToUse = ISD::FP_TO_SINT;
3741      break;
3742    }
3743    if (OpToUse) break;
3744
3745    // If the target supports FP_TO_UINT of this type, use it.
3746    switch (TLI.getOperationAction(ISD::FP_TO_UINT, NewOutTy)) {
3747    default: break;
3748    case TargetLowering::Legal:
3749      if (!TLI.isTypeLegal(NewOutTy))
3750        break;  // Can't use this datatype.
3751      // FALL THROUGH.
3752    case TargetLowering::Custom:
3753      OpToUse = ISD::FP_TO_UINT;
3754      break;
3755    }
3756    if (OpToUse) break;
3757
3758    // Otherwise, try a larger type.
3759  }
3760
3761  // Okay, we found the operation and type to use.  Truncate the result of the
3762  // extended FP_TO_*INT operation to the desired size.
3763  return DAG.getNode(ISD::TRUNCATE, DestVT,
3764                     DAG.getNode(OpToUse, NewOutTy, LegalOp));
3765}
3766
3767/// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
3768///
3769SDOperand SelectionDAGLegalize::ExpandBSWAP(SDOperand Op) {
3770  MVT::ValueType VT = Op.getValueType();
3771  MVT::ValueType SHVT = TLI.getShiftAmountTy();
3772  SDOperand Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
3773  switch (VT) {
3774  default: assert(0 && "Unhandled Expand type in BSWAP!"); abort();
3775  case MVT::i16:
3776    Tmp2 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
3777    Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
3778    return DAG.getNode(ISD::OR, VT, Tmp1, Tmp2);
3779  case MVT::i32:
3780    Tmp4 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
3781    Tmp3 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
3782    Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
3783    Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
3784    Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
3785    Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(0xFF00, VT));
3786    Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
3787    Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
3788    return DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
3789  case MVT::i64:
3790    Tmp8 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(56, SHVT));
3791    Tmp7 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(40, SHVT));
3792    Tmp6 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
3793    Tmp5 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
3794    Tmp4 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
3795    Tmp3 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
3796    Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(40, SHVT));
3797    Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(56, SHVT));
3798    Tmp7 = DAG.getNode(ISD::AND, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
3799    Tmp6 = DAG.getNode(ISD::AND, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
3800    Tmp5 = DAG.getNode(ISD::AND, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
3801    Tmp4 = DAG.getNode(ISD::AND, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
3802    Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
3803    Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
3804    Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp7);
3805    Tmp6 = DAG.getNode(ISD::OR, VT, Tmp6, Tmp5);
3806    Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
3807    Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
3808    Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp6);
3809    Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
3810    return DAG.getNode(ISD::OR, VT, Tmp8, Tmp4);
3811  }
3812}
3813
3814/// ExpandBitCount - Expand the specified bitcount instruction into operations.
3815///
3816SDOperand SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDOperand Op) {
3817  switch (Opc) {
3818  default: assert(0 && "Cannot expand this yet!");
3819  case ISD::CTPOP: {
3820    static const uint64_t mask[6] = {
3821      0x5555555555555555ULL, 0x3333333333333333ULL,
3822      0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
3823      0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
3824    };
3825    MVT::ValueType VT = Op.getValueType();
3826    MVT::ValueType ShVT = TLI.getShiftAmountTy();
3827    unsigned len = getSizeInBits(VT);
3828    for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
3829      //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
3830      SDOperand Tmp2 = DAG.getConstant(mask[i], VT);
3831      SDOperand Tmp3 = DAG.getConstant(1ULL << i, ShVT);
3832      Op = DAG.getNode(ISD::ADD, VT, DAG.getNode(ISD::AND, VT, Op, Tmp2),
3833                       DAG.getNode(ISD::AND, VT,
3834                                   DAG.getNode(ISD::SRL, VT, Op, Tmp3),Tmp2));
3835    }
3836    return Op;
3837  }
3838  case ISD::CTLZ: {
3839    // for now, we do this:
3840    // x = x | (x >> 1);
3841    // x = x | (x >> 2);
3842    // ...
3843    // x = x | (x >>16);
3844    // x = x | (x >>32); // for 64-bit input
3845    // return popcount(~x);
3846    //
3847    // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
3848    MVT::ValueType VT = Op.getValueType();
3849    MVT::ValueType ShVT = TLI.getShiftAmountTy();
3850    unsigned len = getSizeInBits(VT);
3851    for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
3852      SDOperand Tmp3 = DAG.getConstant(1ULL << i, ShVT);
3853      Op = DAG.getNode(ISD::OR, VT, Op, DAG.getNode(ISD::SRL, VT, Op, Tmp3));
3854    }
3855    Op = DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(~0ULL, VT));
3856    return DAG.getNode(ISD::CTPOP, VT, Op);
3857  }
3858  case ISD::CTTZ: {
3859    // for now, we use: { return popcount(~x & (x - 1)); }
3860    // unless the target has ctlz but not ctpop, in which case we use:
3861    // { return 32 - nlz(~x & (x-1)); }
3862    // see also http://www.hackersdelight.org/HDcode/ntz.cc
3863    MVT::ValueType VT = Op.getValueType();
3864    SDOperand Tmp2 = DAG.getConstant(~0ULL, VT);
3865    SDOperand Tmp3 = DAG.getNode(ISD::AND, VT,
3866                       DAG.getNode(ISD::XOR, VT, Op, Tmp2),
3867                       DAG.getNode(ISD::SUB, VT, Op, DAG.getConstant(1, VT)));
3868    // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
3869    if (!TLI.isOperationLegal(ISD::CTPOP, VT) &&
3870        TLI.isOperationLegal(ISD::CTLZ, VT))
3871      return DAG.getNode(ISD::SUB, VT,
3872                         DAG.getConstant(getSizeInBits(VT), VT),
3873                         DAG.getNode(ISD::CTLZ, VT, Tmp3));
3874    return DAG.getNode(ISD::CTPOP, VT, Tmp3);
3875  }
3876  }
3877}
3878
3879
3880/// ExpandOp - Expand the specified SDOperand into its two component pieces
3881/// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
3882/// LegalizeNodes map is filled in for any results that are not expanded, the
3883/// ExpandedNodes map is filled in for any results that are expanded, and the
3884/// Lo/Hi values are returned.
3885void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
3886  MVT::ValueType VT = Op.getValueType();
3887  MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
3888  SDNode *Node = Op.Val;
3889  assert(getTypeAction(VT) == Expand && "Not an expanded type!");
3890  assert((MVT::isInteger(VT) || VT == MVT::Vector) &&
3891         "Cannot expand FP values!");
3892  assert(((MVT::isInteger(NVT) && NVT < VT) || VT == MVT::Vector) &&
3893         "Cannot expand to FP value or to larger int value!");
3894
3895  // See if we already expanded it.
3896  std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
3897    = ExpandedNodes.find(Op);
3898  if (I != ExpandedNodes.end()) {
3899    Lo = I->second.first;
3900    Hi = I->second.second;
3901    return;
3902  }
3903
3904  switch (Node->getOpcode()) {
3905  case ISD::CopyFromReg:
3906    assert(0 && "CopyFromReg must be legal!");
3907  default:
3908    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
3909    assert(0 && "Do not know how to expand this operator!");
3910    abort();
3911  case ISD::UNDEF:
3912    Lo = DAG.getNode(ISD::UNDEF, NVT);
3913    Hi = DAG.getNode(ISD::UNDEF, NVT);
3914    break;
3915  case ISD::Constant: {
3916    uint64_t Cst = cast<ConstantSDNode>(Node)->getValue();
3917    Lo = DAG.getConstant(Cst, NVT);
3918    Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
3919    break;
3920  }
3921  case ISD::BUILD_PAIR:
3922    // Return the operands.
3923    Lo = Node->getOperand(0);
3924    Hi = Node->getOperand(1);
3925    break;
3926
3927  case ISD::SIGN_EXTEND_INREG:
3928    ExpandOp(Node->getOperand(0), Lo, Hi);
3929    // Sign extend the lo-part.
3930    Hi = DAG.getNode(ISD::SRA, NVT, Lo,
3931                     DAG.getConstant(MVT::getSizeInBits(NVT)-1,
3932                                     TLI.getShiftAmountTy()));
3933    // sext_inreg the low part if needed.
3934    Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Lo, Node->getOperand(1));
3935    break;
3936
3937  case ISD::BSWAP: {
3938    ExpandOp(Node->getOperand(0), Lo, Hi);
3939    SDOperand TempLo = DAG.getNode(ISD::BSWAP, NVT, Hi);
3940    Hi = DAG.getNode(ISD::BSWAP, NVT, Lo);
3941    Lo = TempLo;
3942    break;
3943  }
3944
3945  case ISD::CTPOP:
3946    ExpandOp(Node->getOperand(0), Lo, Hi);
3947    Lo = DAG.getNode(ISD::ADD, NVT,          // ctpop(HL) -> ctpop(H)+ctpop(L)
3948                     DAG.getNode(ISD::CTPOP, NVT, Lo),
3949                     DAG.getNode(ISD::CTPOP, NVT, Hi));
3950    Hi = DAG.getConstant(0, NVT);
3951    break;
3952
3953  case ISD::CTLZ: {
3954    // ctlz (HL) -> ctlz(H) != 32 ? ctlz(H) : (ctlz(L)+32)
3955    ExpandOp(Node->getOperand(0), Lo, Hi);
3956    SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
3957    SDOperand HLZ = DAG.getNode(ISD::CTLZ, NVT, Hi);
3958    SDOperand TopNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), HLZ, BitsC,
3959                                        ISD::SETNE);
3960    SDOperand LowPart = DAG.getNode(ISD::CTLZ, NVT, Lo);
3961    LowPart = DAG.getNode(ISD::ADD, NVT, LowPart, BitsC);
3962
3963    Lo = DAG.getNode(ISD::SELECT, NVT, TopNotZero, HLZ, LowPart);
3964    Hi = DAG.getConstant(0, NVT);
3965    break;
3966  }
3967
3968  case ISD::CTTZ: {
3969    // cttz (HL) -> cttz(L) != 32 ? cttz(L) : (cttz(H)+32)
3970    ExpandOp(Node->getOperand(0), Lo, Hi);
3971    SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
3972    SDOperand LTZ = DAG.getNode(ISD::CTTZ, NVT, Lo);
3973    SDOperand BotNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), LTZ, BitsC,
3974                                        ISD::SETNE);
3975    SDOperand HiPart = DAG.getNode(ISD::CTTZ, NVT, Hi);
3976    HiPart = DAG.getNode(ISD::ADD, NVT, HiPart, BitsC);
3977
3978    Lo = DAG.getNode(ISD::SELECT, NVT, BotNotZero, LTZ, HiPart);
3979    Hi = DAG.getConstant(0, NVT);
3980    break;
3981  }
3982
3983  case ISD::VAARG: {
3984    SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
3985    SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
3986    Lo = DAG.getVAArg(NVT, Ch, Ptr, Node->getOperand(2));
3987    Hi = DAG.getVAArg(NVT, Lo.getValue(1), Ptr, Node->getOperand(2));
3988
3989    // Remember that we legalized the chain.
3990    Hi = LegalizeOp(Hi);
3991    AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
3992    if (!TLI.isLittleEndian())
3993      std::swap(Lo, Hi);
3994    break;
3995  }
3996
3997  case ISD::LOAD: {
3998    SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
3999    SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
4000    Lo = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
4001
4002    // Increment the pointer to the other half.
4003    unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
4004    Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4005                      getIntPtrConstant(IncrementSize));
4006    // FIXME: This creates a bogus srcvalue!
4007    Hi = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
4008
4009    // Build a factor node to remember that this load is independent of the
4010    // other one.
4011    SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
4012                               Hi.getValue(1));
4013
4014    // Remember that we legalized the chain.
4015    AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
4016    if (!TLI.isLittleEndian())
4017      std::swap(Lo, Hi);
4018    break;
4019  }
4020  case ISD::AND:
4021  case ISD::OR:
4022  case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
4023    SDOperand LL, LH, RL, RH;
4024    ExpandOp(Node->getOperand(0), LL, LH);
4025    ExpandOp(Node->getOperand(1), RL, RH);
4026    Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
4027    Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
4028    break;
4029  }
4030  case ISD::SELECT: {
4031    SDOperand LL, LH, RL, RH;
4032    ExpandOp(Node->getOperand(1), LL, LH);
4033    ExpandOp(Node->getOperand(2), RL, RH);
4034    Lo = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LL, RL);
4035    Hi = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LH, RH);
4036    break;
4037  }
4038  case ISD::SELECT_CC: {
4039    SDOperand TL, TH, FL, FH;
4040    ExpandOp(Node->getOperand(2), TL, TH);
4041    ExpandOp(Node->getOperand(3), FL, FH);
4042    Lo = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
4043                     Node->getOperand(1), TL, FL, Node->getOperand(4));
4044    Hi = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
4045                     Node->getOperand(1), TH, FH, Node->getOperand(4));
4046    break;
4047  }
4048  case ISD::SEXTLOAD: {
4049    SDOperand Chain = Node->getOperand(0);
4050    SDOperand Ptr   = Node->getOperand(1);
4051    MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
4052
4053    if (EVT == NVT)
4054      Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
4055    else
4056      Lo = DAG.getExtLoad(ISD::SEXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
4057                          EVT);
4058
4059    // Remember that we legalized the chain.
4060    AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
4061
4062    // The high part is obtained by SRA'ing all but one of the bits of the lo
4063    // part.
4064    unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
4065    Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1,
4066                                                       TLI.getShiftAmountTy()));
4067    break;
4068  }
4069  case ISD::ZEXTLOAD: {
4070    SDOperand Chain = Node->getOperand(0);
4071    SDOperand Ptr   = Node->getOperand(1);
4072    MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
4073
4074    if (EVT == NVT)
4075      Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
4076    else
4077      Lo = DAG.getExtLoad(ISD::ZEXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
4078                          EVT);
4079
4080    // Remember that we legalized the chain.
4081    AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
4082
4083    // The high part is just a zero.
4084    Hi = DAG.getConstant(0, NVT);
4085    break;
4086  }
4087  case ISD::EXTLOAD: {
4088    SDOperand Chain = Node->getOperand(0);
4089    SDOperand Ptr   = Node->getOperand(1);
4090    MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
4091
4092    if (EVT == NVT)
4093      Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
4094    else
4095      Lo = DAG.getExtLoad(ISD::EXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
4096                          EVT);
4097
4098    // Remember that we legalized the chain.
4099    AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
4100
4101    // The high part is undefined.
4102    Hi = DAG.getNode(ISD::UNDEF, NVT);
4103    break;
4104  }
4105  case ISD::ANY_EXTEND:
4106    // The low part is any extension of the input (which degenerates to a copy).
4107    Lo = DAG.getNode(ISD::ANY_EXTEND, NVT, Node->getOperand(0));
4108    // The high part is undefined.
4109    Hi = DAG.getNode(ISD::UNDEF, NVT);
4110    break;
4111  case ISD::SIGN_EXTEND: {
4112    // The low part is just a sign extension of the input (which degenerates to
4113    // a copy).
4114    Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, Node->getOperand(0));
4115
4116    // The high part is obtained by SRA'ing all but one of the bits of the lo
4117    // part.
4118    unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
4119    Hi = DAG.getNode(ISD::SRA, NVT, Lo,
4120                     DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
4121    break;
4122  }
4123  case ISD::ZERO_EXTEND:
4124    // The low part is just a zero extension of the input (which degenerates to
4125    // a copy).
4126    Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
4127
4128    // The high part is just a zero.
4129    Hi = DAG.getConstant(0, NVT);
4130    break;
4131
4132  case ISD::BIT_CONVERT: {
4133    SDOperand Tmp = ExpandBIT_CONVERT(Node->getValueType(0),
4134                                      Node->getOperand(0));
4135    ExpandOp(Tmp, Lo, Hi);
4136    break;
4137  }
4138
4139  case ISD::READCYCLECOUNTER:
4140    assert(TLI.getOperationAction(ISD::READCYCLECOUNTER, VT) ==
4141                 TargetLowering::Custom &&
4142           "Must custom expand ReadCycleCounter");
4143    Lo = TLI.LowerOperation(Op, DAG);
4144    assert(Lo.Val && "Node must be custom expanded!");
4145    Hi = Lo.getValue(1);
4146    AddLegalizedOperand(SDOperand(Node, 1), // Remember we legalized the chain.
4147                        LegalizeOp(Lo.getValue(2)));
4148    break;
4149
4150    // These operators cannot be expanded directly, emit them as calls to
4151    // library functions.
4152  case ISD::FP_TO_SINT:
4153    if (TLI.getOperationAction(ISD::FP_TO_SINT, VT) == TargetLowering::Custom) {
4154      SDOperand Op;
4155      switch (getTypeAction(Node->getOperand(0).getValueType())) {
4156      case Expand: assert(0 && "cannot expand FP!");
4157      case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
4158      case Promote: Op = PromoteOp (Node->getOperand(0)); break;
4159      }
4160
4161      Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_SINT, VT, Op), DAG);
4162
4163      // Now that the custom expander is done, expand the result, which is still
4164      // VT.
4165      if (Op.Val) {
4166        ExpandOp(Op, Lo, Hi);
4167        break;
4168      }
4169    }
4170
4171    if (Node->getOperand(0).getValueType() == MVT::f32)
4172      Lo = ExpandLibCall("__fixsfdi", Node, Hi);
4173    else
4174      Lo = ExpandLibCall("__fixdfdi", Node, Hi);
4175    break;
4176
4177  case ISD::FP_TO_UINT:
4178    if (TLI.getOperationAction(ISD::FP_TO_UINT, VT) == TargetLowering::Custom) {
4179      SDOperand Op;
4180      switch (getTypeAction(Node->getOperand(0).getValueType())) {
4181        case Expand: assert(0 && "cannot expand FP!");
4182        case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
4183        case Promote: Op = PromoteOp (Node->getOperand(0)); break;
4184      }
4185
4186      Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_UINT, VT, Op), DAG);
4187
4188      // Now that the custom expander is done, expand the result.
4189      if (Op.Val) {
4190        ExpandOp(Op, Lo, Hi);
4191        break;
4192      }
4193    }
4194
4195    if (Node->getOperand(0).getValueType() == MVT::f32)
4196      Lo = ExpandLibCall("__fixunssfdi", Node, Hi);
4197    else
4198      Lo = ExpandLibCall("__fixunsdfdi", Node, Hi);
4199    break;
4200
4201  case ISD::SHL: {
4202    // If the target wants custom lowering, do so.
4203    SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
4204    if (TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Custom) {
4205      SDOperand Op = DAG.getNode(ISD::SHL, VT, Node->getOperand(0), ShiftAmt);
4206      Op = TLI.LowerOperation(Op, DAG);
4207      if (Op.Val) {
4208        // Now that the custom expander is done, expand the result, which is
4209        // still VT.
4210        ExpandOp(Op, Lo, Hi);
4211        break;
4212      }
4213    }
4214
4215    // If we can emit an efficient shift operation, do so now.
4216    if (ExpandShift(ISD::SHL, Node->getOperand(0), ShiftAmt, Lo, Hi))
4217      break;
4218
4219    // If this target supports SHL_PARTS, use it.
4220    TargetLowering::LegalizeAction Action =
4221      TLI.getOperationAction(ISD::SHL_PARTS, NVT);
4222    if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
4223        Action == TargetLowering::Custom) {
4224      ExpandShiftParts(ISD::SHL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
4225      break;
4226    }
4227
4228    // Otherwise, emit a libcall.
4229    Lo = ExpandLibCall("__ashldi3", Node, Hi);
4230    break;
4231  }
4232
4233  case ISD::SRA: {
4234    // If the target wants custom lowering, do so.
4235    SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
4236    if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Custom) {
4237      SDOperand Op = DAG.getNode(ISD::SRA, VT, Node->getOperand(0), ShiftAmt);
4238      Op = TLI.LowerOperation(Op, DAG);
4239      if (Op.Val) {
4240        // Now that the custom expander is done, expand the result, which is
4241        // still VT.
4242        ExpandOp(Op, Lo, Hi);
4243        break;
4244      }
4245    }
4246
4247    // If we can emit an efficient shift operation, do so now.
4248    if (ExpandShift(ISD::SRA, Node->getOperand(0), ShiftAmt, Lo, Hi))
4249      break;
4250
4251    // If this target supports SRA_PARTS, use it.
4252    TargetLowering::LegalizeAction Action =
4253      TLI.getOperationAction(ISD::SRA_PARTS, NVT);
4254    if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
4255        Action == TargetLowering::Custom) {
4256      ExpandShiftParts(ISD::SRA_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
4257      break;
4258    }
4259
4260    // Otherwise, emit a libcall.
4261    Lo = ExpandLibCall("__ashrdi3", Node, Hi);
4262    break;
4263  }
4264
4265  case ISD::SRL: {
4266    // If the target wants custom lowering, do so.
4267    SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
4268    if (TLI.getOperationAction(ISD::SRL, VT) == TargetLowering::Custom) {
4269      SDOperand Op = DAG.getNode(ISD::SRL, VT, Node->getOperand(0), ShiftAmt);
4270      Op = TLI.LowerOperation(Op, DAG);
4271      if (Op.Val) {
4272        // Now that the custom expander is done, expand the result, which is
4273        // still VT.
4274        ExpandOp(Op, Lo, Hi);
4275        break;
4276      }
4277    }
4278
4279    // If we can emit an efficient shift operation, do so now.
4280    if (ExpandShift(ISD::SRL, Node->getOperand(0), ShiftAmt, Lo, Hi))
4281      break;
4282
4283    // If this target supports SRL_PARTS, use it.
4284    TargetLowering::LegalizeAction Action =
4285      TLI.getOperationAction(ISD::SRL_PARTS, NVT);
4286    if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
4287        Action == TargetLowering::Custom) {
4288      ExpandShiftParts(ISD::SRL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
4289      break;
4290    }
4291
4292    // Otherwise, emit a libcall.
4293    Lo = ExpandLibCall("__lshrdi3", Node, Hi);
4294    break;
4295  }
4296
4297  case ISD::ADD:
4298  case ISD::SUB: {
4299    // If the target wants to custom expand this, let them.
4300    if (TLI.getOperationAction(Node->getOpcode(), VT) ==
4301            TargetLowering::Custom) {
4302      Op = TLI.LowerOperation(Op, DAG);
4303      if (Op.Val) {
4304        ExpandOp(Op, Lo, Hi);
4305        break;
4306      }
4307    }
4308
4309    // Expand the subcomponents.
4310    SDOperand LHSL, LHSH, RHSL, RHSH;
4311    ExpandOp(Node->getOperand(0), LHSL, LHSH);
4312    ExpandOp(Node->getOperand(1), RHSL, RHSH);
4313    std::vector<MVT::ValueType> VTs;
4314    std::vector<SDOperand> LoOps, HiOps;
4315    VTs.push_back(LHSL.getValueType());
4316    VTs.push_back(MVT::Flag);
4317    LoOps.push_back(LHSL);
4318    LoOps.push_back(RHSL);
4319    HiOps.push_back(LHSH);
4320    HiOps.push_back(RHSH);
4321    if (Node->getOpcode() == ISD::ADD) {
4322      Lo = DAG.getNode(ISD::ADDC, VTs, LoOps);
4323      HiOps.push_back(Lo.getValue(1));
4324      Hi = DAG.getNode(ISD::ADDE, VTs, HiOps);
4325    } else {
4326      Lo = DAG.getNode(ISD::SUBC, VTs, LoOps);
4327      HiOps.push_back(Lo.getValue(1));
4328      Hi = DAG.getNode(ISD::SUBE, VTs, HiOps);
4329    }
4330    break;
4331  }
4332  case ISD::MUL: {
4333    if (TLI.isOperationLegal(ISD::MULHU, NVT)) {
4334      SDOperand LL, LH, RL, RH;
4335      ExpandOp(Node->getOperand(0), LL, LH);
4336      ExpandOp(Node->getOperand(1), RL, RH);
4337      unsigned SH = MVT::getSizeInBits(RH.getValueType())-1;
4338      // MULHS implicitly sign extends its inputs.  Check to see if ExpandOp
4339      // extended the sign bit of the low half through the upper half, and if so
4340      // emit a MULHS instead of the alternate sequence that is valid for any
4341      // i64 x i64 multiply.
4342      if (TLI.isOperationLegal(ISD::MULHS, NVT) &&
4343          // is RH an extension of the sign bit of RL?
4344          RH.getOpcode() == ISD::SRA && RH.getOperand(0) == RL &&
4345          RH.getOperand(1).getOpcode() == ISD::Constant &&
4346          cast<ConstantSDNode>(RH.getOperand(1))->getValue() == SH &&
4347          // is LH an extension of the sign bit of LL?
4348          LH.getOpcode() == ISD::SRA && LH.getOperand(0) == LL &&
4349          LH.getOperand(1).getOpcode() == ISD::Constant &&
4350          cast<ConstantSDNode>(LH.getOperand(1))->getValue() == SH) {
4351        Hi = DAG.getNode(ISD::MULHS, NVT, LL, RL);
4352      } else {
4353        Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
4354        RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
4355        LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
4356        Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
4357        Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
4358      }
4359      Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
4360    } else {
4361      Lo = ExpandLibCall("__muldi3" , Node, Hi);
4362    }
4363    break;
4364  }
4365  case ISD::SDIV: Lo = ExpandLibCall("__divdi3" , Node, Hi); break;
4366  case ISD::UDIV: Lo = ExpandLibCall("__udivdi3", Node, Hi); break;
4367  case ISD::SREM: Lo = ExpandLibCall("__moddi3" , Node, Hi); break;
4368  case ISD::UREM: Lo = ExpandLibCall("__umoddi3", Node, Hi); break;
4369  }
4370
4371  // Make sure the resultant values have been legalized themselves, unless this
4372  // is a type that requires multi-step expansion.
4373  if (getTypeAction(NVT) != Expand && NVT != MVT::isVoid) {
4374    Lo = LegalizeOp(Lo);
4375    Hi = LegalizeOp(Hi);
4376  }
4377
4378  // Remember in a map if the values will be reused later.
4379  bool isNew =
4380    ExpandedNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
4381  assert(isNew && "Value already expanded?!?");
4382}
4383
4384/// SplitVectorOp - Given an operand of MVT::Vector type, break it down into
4385/// two smaller values of MVT::Vector type.
4386void SelectionDAGLegalize::SplitVectorOp(SDOperand Op, SDOperand &Lo,
4387                                         SDOperand &Hi) {
4388  assert(Op.getValueType() == MVT::Vector && "Cannot split non-vector type!");
4389  SDNode *Node = Op.Val;
4390  unsigned NumElements = cast<ConstantSDNode>(*(Node->op_end()-2))->getValue();
4391  assert(NumElements > 1 && "Cannot split a single element vector!");
4392  unsigned NewNumElts = NumElements/2;
4393  SDOperand NewNumEltsNode = DAG.getConstant(NewNumElts, MVT::i32);
4394  SDOperand TypeNode = *(Node->op_end()-1);
4395
4396  // See if we already split it.
4397  std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
4398    = SplitNodes.find(Op);
4399  if (I != SplitNodes.end()) {
4400    Lo = I->second.first;
4401    Hi = I->second.second;
4402    return;
4403  }
4404
4405  switch (Node->getOpcode()) {
4406  default: Node->dump(); assert(0 && "Unknown vector operation!");
4407  case ISD::VBUILD_VECTOR: {
4408    std::vector<SDOperand> LoOps(Node->op_begin(), Node->op_begin()+NewNumElts);
4409    LoOps.push_back(NewNumEltsNode);
4410    LoOps.push_back(TypeNode);
4411    Lo = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, LoOps);
4412
4413    std::vector<SDOperand> HiOps(Node->op_begin()+NewNumElts, Node->op_end()-2);
4414    HiOps.push_back(NewNumEltsNode);
4415    HiOps.push_back(TypeNode);
4416    Hi = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, HiOps);
4417    break;
4418  }
4419  case ISD::VADD:
4420  case ISD::VSUB:
4421  case ISD::VMUL:
4422  case ISD::VSDIV:
4423  case ISD::VUDIV:
4424  case ISD::VAND:
4425  case ISD::VOR:
4426  case ISD::VXOR: {
4427    SDOperand LL, LH, RL, RH;
4428    SplitVectorOp(Node->getOperand(0), LL, LH);
4429    SplitVectorOp(Node->getOperand(1), RL, RH);
4430
4431    Lo = DAG.getNode(Node->getOpcode(), MVT::Vector, LL, RL,
4432                     NewNumEltsNode, TypeNode);
4433    Hi = DAG.getNode(Node->getOpcode(), MVT::Vector, LH, RH,
4434                     NewNumEltsNode, TypeNode);
4435    break;
4436  }
4437  case ISD::VLOAD: {
4438    SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
4439    SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
4440    MVT::ValueType EVT = cast<VTSDNode>(TypeNode)->getVT();
4441
4442    Lo = DAG.getVecLoad(NewNumElts, EVT, Ch, Ptr, Node->getOperand(2));
4443    unsigned IncrementSize = NewNumElts * MVT::getSizeInBits(EVT)/8;
4444    Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4445                      getIntPtrConstant(IncrementSize));
4446    // FIXME: This creates a bogus srcvalue!
4447    Hi = DAG.getVecLoad(NewNumElts, EVT, Ch, Ptr, Node->getOperand(2));
4448
4449    // Build a factor node to remember that this load is independent of the
4450    // other one.
4451    SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
4452                               Hi.getValue(1));
4453
4454    // Remember that we legalized the chain.
4455    AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
4456    break;
4457  }
4458  case ISD::VBIT_CONVERT: {
4459    // We know the result is a vector.  The input may be either a vector or a
4460    // scalar value.
4461    if (Op.getOperand(0).getValueType() != MVT::Vector) {
4462      // Lower to a store/load.  FIXME: this could be improved probably.
4463      SDOperand Ptr = CreateStackTemporary(Op.getOperand(0).getValueType());
4464
4465      SDOperand St = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
4466                                 Op.getOperand(0), Ptr, DAG.getSrcValue(0));
4467      MVT::ValueType EVT = cast<VTSDNode>(TypeNode)->getVT();
4468      St = DAG.getVecLoad(NumElements, EVT, St, Ptr, DAG.getSrcValue(0));
4469      SplitVectorOp(St, Lo, Hi);
4470    } else {
4471      // If the input is a vector type, we have to either scalarize it, pack it
4472      // or convert it based on whether the input vector type is legal.
4473      SDNode *InVal = Node->getOperand(0).Val;
4474      unsigned NumElems =
4475        cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
4476      MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
4477
4478      // If the input is from a single element vector, scalarize the vector,
4479      // then treat like a scalar.
4480      if (NumElems == 1) {
4481        SDOperand Scalar = PackVectorOp(Op.getOperand(0), EVT);
4482        Scalar = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Scalar,
4483                             Op.getOperand(1), Op.getOperand(2));
4484        SplitVectorOp(Scalar, Lo, Hi);
4485      } else {
4486        // Split the input vector.
4487        SplitVectorOp(Op.getOperand(0), Lo, Hi);
4488
4489        // Convert each of the pieces now.
4490        Lo = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Lo,
4491                         NewNumEltsNode, TypeNode);
4492        Hi = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Hi,
4493                         NewNumEltsNode, TypeNode);
4494      }
4495      break;
4496    }
4497  }
4498  }
4499
4500  // Remember in a map if the values will be reused later.
4501  bool isNew =
4502    SplitNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
4503  assert(isNew && "Value already expanded?!?");
4504}
4505
4506
4507/// PackVectorOp - Given an operand of MVT::Vector type, convert it into the
4508/// equivalent operation that returns a scalar (e.g. F32) or packed value
4509/// (e.g. MVT::V4F32).  When this is called, we know that PackedVT is the right
4510/// type for the result.
4511SDOperand SelectionDAGLegalize::PackVectorOp(SDOperand Op,
4512                                             MVT::ValueType NewVT) {
4513  assert(Op.getValueType() == MVT::Vector && "Bad PackVectorOp invocation!");
4514  SDNode *Node = Op.Val;
4515
4516  // See if we already packed it.
4517  std::map<SDOperand, SDOperand>::iterator I = PackedNodes.find(Op);
4518  if (I != PackedNodes.end()) return I->second;
4519
4520  SDOperand Result;
4521  switch (Node->getOpcode()) {
4522  default:
4523    Node->dump(); std::cerr << "\n";
4524    assert(0 && "Unknown vector operation in PackVectorOp!");
4525  case ISD::VADD:
4526  case ISD::VSUB:
4527  case ISD::VMUL:
4528  case ISD::VSDIV:
4529  case ISD::VUDIV:
4530  case ISD::VAND:
4531  case ISD::VOR:
4532  case ISD::VXOR:
4533    Result = DAG.getNode(getScalarizedOpcode(Node->getOpcode(), NewVT),
4534                         NewVT,
4535                         PackVectorOp(Node->getOperand(0), NewVT),
4536                         PackVectorOp(Node->getOperand(1), NewVT));
4537    break;
4538  case ISD::VLOAD: {
4539    SDOperand Ch = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
4540    SDOperand Ptr = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
4541
4542    Result = DAG.getLoad(NewVT, Ch, Ptr, Node->getOperand(2));
4543
4544    // Remember that we legalized the chain.
4545    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4546    break;
4547  }
4548  case ISD::VBUILD_VECTOR:
4549    if (Node->getOperand(0).getValueType() == NewVT) {
4550      // Returning a scalar?
4551      Result = Node->getOperand(0);
4552    } else {
4553      // Returning a BUILD_VECTOR?
4554      std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end()-2);
4555      Result = DAG.getNode(ISD::BUILD_VECTOR, NewVT, Ops);
4556    }
4557    break;
4558  case ISD::VINSERT_VECTOR_ELT:
4559    if (!MVT::isVector(NewVT)) {
4560      // Returning a scalar?  Must be the inserted element.
4561      Result = Node->getOperand(1);
4562    } else {
4563      Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, NewVT,
4564                           PackVectorOp(Node->getOperand(0), NewVT),
4565                           Node->getOperand(1), Node->getOperand(2));
4566    }
4567    break;
4568  case ISD::VVECTOR_SHUFFLE:
4569    if (!MVT::isVector(NewVT)) {
4570      // Returning a scalar?  Figure out if it is the LHS or RHS and return it.
4571      SDOperand EltNum = Node->getOperand(2).getOperand(0);
4572      if (cast<ConstantSDNode>(EltNum)->getValue())
4573        Result = PackVectorOp(Node->getOperand(1), NewVT);
4574      else
4575        Result = PackVectorOp(Node->getOperand(0), NewVT);
4576    } else {
4577      // Otherwise, return a VECTOR_SHUFFLE node.  First convert the index
4578      // vector from a VBUILD_VECTOR to a BUILD_VECTOR.
4579      std::vector<SDOperand> BuildVecIdx(Node->getOperand(2).Val->op_begin(),
4580                                         Node->getOperand(2).Val->op_end()-2);
4581      MVT::ValueType BVT = MVT::getIntVectorWithNumElements(BuildVecIdx.size());
4582      SDOperand BV = DAG.getNode(ISD::BUILD_VECTOR, BVT, BuildVecIdx);
4583
4584      Result = DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT,
4585                           PackVectorOp(Node->getOperand(0), NewVT),
4586                           PackVectorOp(Node->getOperand(1), NewVT), BV);
4587    }
4588    break;
4589  case ISD::VBIT_CONVERT:
4590    if (Op.getOperand(0).getValueType() != MVT::Vector)
4591      Result = DAG.getNode(ISD::BIT_CONVERT, NewVT, Op.getOperand(0));
4592    else {
4593      // If the input is a vector type, we have to either scalarize it, pack it
4594      // or convert it based on whether the input vector type is legal.
4595      SDNode *InVal = Node->getOperand(0).Val;
4596      unsigned NumElems =
4597        cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
4598      MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
4599
4600      // Figure out if there is a Packed type corresponding to this Vector
4601      // type.  If so, convert to the packed type.
4602      MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
4603      if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
4604        // Turn this into a bit convert of the packed input.
4605        Result = DAG.getNode(ISD::BIT_CONVERT, NewVT,
4606                             PackVectorOp(Node->getOperand(0), TVT));
4607        break;
4608      } else if (NumElems == 1) {
4609        // Turn this into a bit convert of the scalar input.
4610        Result = DAG.getNode(ISD::BIT_CONVERT, NewVT,
4611                             PackVectorOp(Node->getOperand(0), EVT));
4612        break;
4613      } else {
4614        // FIXME: UNIMP!
4615        assert(0 && "Cast from unsupported vector type not implemented yet!");
4616      }
4617    }
4618  }
4619
4620  if (TLI.isTypeLegal(NewVT))
4621    Result = LegalizeOp(Result);
4622  bool isNew = PackedNodes.insert(std::make_pair(Op, Result)).second;
4623  assert(isNew && "Value already packed?");
4624  return Result;
4625}
4626
4627
4628// SelectionDAG::Legalize - This is the entry point for the file.
4629//
4630void SelectionDAG::Legalize() {
4631  /// run - This is the main entry point to this class.
4632  ///
4633  SelectionDAGLegalize(*this).LegalizeDAG();
4634}
4635
4636