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