LegalizeDAG.cpp revision 02659d23637f69f90640bfa3e66919517103c57a
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/MachineConstantPool.h"
16#include "llvm/CodeGen/MachineFunction.h"
17#include "llvm/CodeGen/MachineFrameInfo.h"
18#include "llvm/Support/MathExtras.h"
19#include "llvm/Target/TargetLowering.h"
20#include "llvm/Target/TargetData.h"
21#include "llvm/Target/TargetOptions.h"
22#include "llvm/CallingConv.h"
23#include "llvm/Constants.h"
24#include <iostream>
25#include <set>
26using namespace llvm;
27
28//===----------------------------------------------------------------------===//
29/// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
30/// hacks on it until the target machine can handle it.  This involves
31/// eliminating value sizes the machine cannot handle (promoting small sizes to
32/// large sizes or splitting up large values into small values) as well as
33/// eliminating operations the machine cannot handle.
34///
35/// This code also does a small amount of optimization and recognition of idioms
36/// as part of its processing.  For example, if a target does not support a
37/// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
38/// will attempt merge setcc and brc instructions into brcc's.
39///
40namespace {
41class SelectionDAGLegalize {
42  TargetLowering &TLI;
43  SelectionDAG &DAG;
44
45  /// LegalizeAction - This enum indicates what action we should take for each
46  /// value type the can occur in the program.
47  enum LegalizeAction {
48    Legal,            // The target natively supports this value type.
49    Promote,          // This should be promoted to the next larger type.
50    Expand,           // This integer type should be broken into smaller pieces.
51  };
52
53  /// ValueTypeActions - This is a bitvector that contains two bits for each
54  /// value type, where the two bits correspond to the LegalizeAction enum.
55  /// This can be queried with "getTypeAction(VT)".
56  unsigned ValueTypeActions;
57
58  /// NeedsAnotherIteration - This is set when we expand a large integer
59  /// operation into smaller integer operations, but the smaller operations are
60  /// not set.  This occurs only rarely in practice, for targets that don't have
61  /// 32-bit or larger integer registers.
62  bool NeedsAnotherIteration;
63
64  /// LegalizedNodes - For nodes that are of legal width, and that have more
65  /// than one use, this map indicates what regularized operand to use.  This
66  /// allows us to avoid legalizing the same thing more than once.
67  std::map<SDOperand, SDOperand> LegalizedNodes;
68
69  /// PromotedNodes - For nodes that are below legal width, and that have more
70  /// than one use, this map indicates what promoted value to use.  This allows
71  /// us to avoid promoting the same thing more than once.
72  std::map<SDOperand, SDOperand> PromotedNodes;
73
74  /// ExpandedNodes - For nodes that need to be expanded, and which have more
75  /// than one use, this map indicates which which operands are the expanded
76  /// version of the input.  This allows us to avoid expanding the same node
77  /// more than once.
78  std::map<SDOperand, std::pair<SDOperand, SDOperand> > ExpandedNodes;
79
80  void AddLegalizedOperand(SDOperand From, SDOperand To) {
81    bool isNew = LegalizedNodes.insert(std::make_pair(From, To)).second;
82    assert(isNew && "Got into the map somehow?");
83  }
84  void AddPromotedOperand(SDOperand From, SDOperand To) {
85    bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
86    assert(isNew && "Got into the map somehow?");
87  }
88
89public:
90
91  SelectionDAGLegalize(SelectionDAG &DAG);
92
93  /// Run - While there is still lowering to do, perform a pass over the DAG.
94  /// Most regularization can be done in a single pass, but targets that require
95  /// large values to be split into registers multiple times (e.g. i64 -> 4x
96  /// i16) require iteration for these values (the first iteration will demote
97  /// to i32, the second will demote to i16).
98  void Run() {
99    do {
100      NeedsAnotherIteration = false;
101      LegalizeDAG();
102    } while (NeedsAnotherIteration);
103  }
104
105  /// getTypeAction - Return how we should legalize values of this type, either
106  /// it is already legal or we need to expand it into multiple registers of
107  /// smaller integer type, or we need to promote it to a larger type.
108  LegalizeAction getTypeAction(MVT::ValueType VT) const {
109    return (LegalizeAction)((ValueTypeActions >> (2*VT)) & 3);
110  }
111
112  /// isTypeLegal - Return true if this type is legal on this target.
113  ///
114  bool isTypeLegal(MVT::ValueType VT) const {
115    return getTypeAction(VT) == Legal;
116  }
117
118private:
119  void LegalizeDAG();
120
121  SDOperand LegalizeOp(SDOperand O);
122  void ExpandOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
123  SDOperand PromoteOp(SDOperand O);
124
125  SDOperand ExpandLibCall(const char *Name, SDNode *Node,
126                          SDOperand &Hi);
127  SDOperand ExpandIntToFP(bool isSigned, MVT::ValueType DestTy,
128                          SDOperand Source);
129
130  SDOperand ExpandLegalINT_TO_FP(bool isSigned,
131                                 SDOperand LegalOp,
132                                 MVT::ValueType DestVT);
133  SDOperand PromoteLegalINT_TO_FP(SDOperand LegalOp, MVT::ValueType DestVT,
134                                  bool isSigned);
135  SDOperand PromoteLegalFP_TO_INT(SDOperand LegalOp, MVT::ValueType DestVT,
136                                  bool isSigned);
137
138  bool ExpandShift(unsigned Opc, SDOperand Op, SDOperand Amt,
139                   SDOperand &Lo, SDOperand &Hi);
140  void ExpandShiftParts(unsigned NodeOp, SDOperand Op, SDOperand Amt,
141                        SDOperand &Lo, SDOperand &Hi);
142  void ExpandByParts(unsigned NodeOp, SDOperand LHS, SDOperand RHS,
143                     SDOperand &Lo, SDOperand &Hi);
144
145  void SpliceCallInto(const SDOperand &CallResult, SDNode *OutChain);
146
147  SDOperand getIntPtrConstant(uint64_t Val) {
148    return DAG.getConstant(Val, TLI.getPointerTy());
149  }
150};
151}
152
153
154SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag)
155  : TLI(dag.getTargetLoweringInfo()), DAG(dag),
156    ValueTypeActions(TLI.getValueTypeActions()) {
157  assert(MVT::LAST_VALUETYPE <= 16 &&
158         "Too many value types for ValueTypeActions to hold!");
159}
160
161/// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
162/// INT_TO_FP operation of the specified operand when the target requests that
163/// we expand it.  At this point, we know that the result and operand types are
164/// legal for the target.
165SDOperand SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
166                                                     SDOperand Op0,
167                                                     MVT::ValueType DestVT) {
168  if (Op0.getValueType() == MVT::i32) {
169    // simple 32-bit [signed|unsigned] integer to float/double expansion
170
171    // get the stack frame index of a 8 byte buffer
172    MachineFunction &MF = DAG.getMachineFunction();
173    int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
174    // get address of 8 byte buffer
175    SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
176    // word offset constant for Hi/Lo address computation
177    SDOperand WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
178    // set up Hi and Lo (into buffer) address based on endian
179    SDOperand Hi, Lo;
180    if (TLI.isLittleEndian()) {
181      Hi = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot, WordOff);
182      Lo = StackSlot;
183    } else {
184      Hi = StackSlot;
185      Lo = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot, WordOff);
186    }
187    // if signed map to unsigned space
188    SDOperand Op0Mapped;
189    if (isSigned) {
190      // constant used to invert sign bit (signed to unsigned mapping)
191      SDOperand SignBit = DAG.getConstant(0x80000000u, MVT::i32);
192      Op0Mapped = DAG.getNode(ISD::XOR, MVT::i32, Op0, SignBit);
193    } else {
194      Op0Mapped = Op0;
195    }
196    // store the lo of the constructed double - based on integer input
197    SDOperand Store1 = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
198                                   Op0Mapped, Lo, DAG.getSrcValue(NULL));
199    // initial hi portion of constructed double
200    SDOperand InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
201    // store the hi of the constructed double - biased exponent
202    SDOperand Store2 = DAG.getNode(ISD::STORE, MVT::Other, Store1,
203                                   InitialHi, Hi, DAG.getSrcValue(NULL));
204    // load the constructed double
205    SDOperand Load = DAG.getLoad(MVT::f64, Store2, StackSlot,
206                               DAG.getSrcValue(NULL));
207    // FP constant to bias correct the final result
208    SDOperand Bias = DAG.getConstantFP(isSigned ?
209                                            BitsToDouble(0x4330000080000000ULL)
210                                          : BitsToDouble(0x4330000000000000ULL),
211                                     MVT::f64);
212    // subtract the bias
213    SDOperand Sub = DAG.getNode(ISD::SUB, MVT::f64, Load, Bias);
214    // final result
215    SDOperand Result;
216    // handle final rounding
217    if (DestVT == MVT::f64) {
218      // do nothing
219      Result = Sub;
220    } else {
221     // if f32 then cast to f32
222      Result = DAG.getNode(ISD::FP_ROUND, MVT::f32, Sub);
223    }
224    NeedsAnotherIteration = true;
225    return Result;
226  }
227  assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
228  SDOperand Tmp1 = DAG.getNode(ISD::SINT_TO_FP, DestVT, Op0);
229
230  SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Op0,
231                                   DAG.getConstant(0, Op0.getValueType()),
232                                   ISD::SETLT);
233  SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
234  SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
235                                    SignSet, Four, Zero);
236
237  // If the sign bit of the integer is set, the large number will be treated
238  // as a negative number.  To counteract this, the dynamic code adds an
239  // offset depending on the data type.
240  uint64_t FF;
241  switch (Op0.getValueType()) {
242  default: assert(0 && "Unsupported integer type!");
243  case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
244  case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
245  case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
246  case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
247  }
248  if (TLI.isLittleEndian()) FF <<= 32;
249  static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
250
251  MachineConstantPool *CP = DAG.getMachineFunction().getConstantPool();
252  SDOperand CPIdx = DAG.getConstantPool(CP->getConstantPoolIndex(FudgeFactor),
253                                        TLI.getPointerTy());
254  CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
255  SDOperand FudgeInReg;
256  if (DestVT == MVT::f32)
257    FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
258                             DAG.getSrcValue(NULL));
259  else {
260    assert(DestVT == MVT::f64 && "Unexpected conversion");
261    FudgeInReg = LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, MVT::f64,
262                                           DAG.getEntryNode(), CPIdx,
263                                           DAG.getSrcValue(NULL), MVT::f32));
264  }
265
266  NeedsAnotherIteration = true;
267  return DAG.getNode(ISD::ADD, DestVT, Tmp1, FudgeInReg);
268}
269
270/// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
271/// *INT_TO_FP operation of the specified operand when the target requests that
272/// we promote it.  At this point, we know that the result and operand types are
273/// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
274/// operation that takes a larger input.
275SDOperand SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDOperand LegalOp,
276                                                      MVT::ValueType DestVT,
277                                                      bool isSigned) {
278  // First step, figure out the appropriate *INT_TO_FP operation to use.
279  MVT::ValueType NewInTy = LegalOp.getValueType();
280
281  unsigned OpToUse = 0;
282
283  // Scan for the appropriate larger type to use.
284  while (1) {
285    NewInTy = (MVT::ValueType)(NewInTy+1);
286    assert(MVT::isInteger(NewInTy) && "Ran out of possibilities!");
287
288    // If the target supports SINT_TO_FP of this type, use it.
289    switch (TLI.getOperationAction(ISD::SINT_TO_FP, NewInTy)) {
290      default: break;
291      case TargetLowering::Legal:
292        if (!TLI.hasNativeSupportFor(NewInTy))
293          break;  // Can't use this datatype.
294        // FALL THROUGH.
295      case TargetLowering::Custom:
296        OpToUse = ISD::SINT_TO_FP;
297        break;
298    }
299    if (OpToUse) break;
300    if (isSigned) continue;
301
302    // If the target supports UINT_TO_FP of this type, use it.
303    switch (TLI.getOperationAction(ISD::UINT_TO_FP, NewInTy)) {
304      default: break;
305      case TargetLowering::Legal:
306        if (!TLI.hasNativeSupportFor(NewInTy))
307          break;  // Can't use this datatype.
308        // FALL THROUGH.
309      case TargetLowering::Custom:
310        OpToUse = ISD::UINT_TO_FP;
311        break;
312    }
313    if (OpToUse) break;
314
315    // Otherwise, try a larger type.
316  }
317
318  // Make sure to legalize any nodes we create here in the next pass.
319  NeedsAnotherIteration = true;
320
321  // Okay, we found the operation and type to use.  Zero extend our input to the
322  // desired type then run the operation on it.
323  return DAG.getNode(OpToUse, DestVT,
324                     DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
325                                 NewInTy, LegalOp));
326}
327
328/// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
329/// FP_TO_*INT operation of the specified operand when the target requests that
330/// we promote it.  At this point, we know that the result and operand types are
331/// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
332/// operation that returns a larger result.
333SDOperand SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDOperand LegalOp,
334                                                      MVT::ValueType DestVT,
335                                                      bool isSigned) {
336  // First step, figure out the appropriate FP_TO*INT operation to use.
337  MVT::ValueType NewOutTy = DestVT;
338
339  unsigned OpToUse = 0;
340
341  // Scan for the appropriate larger type to use.
342  while (1) {
343    NewOutTy = (MVT::ValueType)(NewOutTy+1);
344    assert(MVT::isInteger(NewOutTy) && "Ran out of possibilities!");
345
346    // If the target supports FP_TO_SINT returning this type, use it.
347    switch (TLI.getOperationAction(ISD::FP_TO_SINT, NewOutTy)) {
348    default: break;
349    case TargetLowering::Legal:
350      if (!TLI.hasNativeSupportFor(NewOutTy))
351        break;  // Can't use this datatype.
352      // FALL THROUGH.
353    case TargetLowering::Custom:
354      OpToUse = ISD::FP_TO_SINT;
355      break;
356    }
357    if (OpToUse) break;
358
359    // If the target supports FP_TO_UINT of this type, use it.
360    switch (TLI.getOperationAction(ISD::FP_TO_UINT, NewOutTy)) {
361    default: break;
362    case TargetLowering::Legal:
363      if (!TLI.hasNativeSupportFor(NewOutTy))
364        break;  // Can't use this datatype.
365      // FALL THROUGH.
366    case TargetLowering::Custom:
367      OpToUse = ISD::FP_TO_UINT;
368      break;
369    }
370    if (OpToUse) break;
371
372    // Otherwise, try a larger type.
373  }
374
375  // Make sure to legalize any nodes we create here in the next pass.
376  NeedsAnotherIteration = true;
377
378  // Okay, we found the operation and type to use.  Truncate the result of the
379  // extended FP_TO_*INT operation to the desired size.
380  return DAG.getNode(ISD::TRUNCATE, DestVT,
381                     DAG.getNode(OpToUse, NewOutTy, LegalOp));
382}
383
384
385void SelectionDAGLegalize::LegalizeDAG() {
386  SDOperand OldRoot = DAG.getRoot();
387  SDOperand NewRoot = LegalizeOp(OldRoot);
388  DAG.setRoot(NewRoot);
389
390  ExpandedNodes.clear();
391  LegalizedNodes.clear();
392  PromotedNodes.clear();
393
394  // Remove dead nodes now.
395  DAG.RemoveDeadNodes(OldRoot.Val);
396}
397
398SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
399  assert(getTypeAction(Op.getValueType()) == Legal &&
400         "Caller should expand or promote operands that are not legal!");
401  SDNode *Node = Op.Val;
402
403  // If this operation defines any values that cannot be represented in a
404  // register on this target, make sure to expand or promote them.
405  if (Node->getNumValues() > 1) {
406    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
407      switch (getTypeAction(Node->getValueType(i))) {
408      case Legal: break;  // Nothing to do.
409      case Expand: {
410        SDOperand T1, T2;
411        ExpandOp(Op.getValue(i), T1, T2);
412        assert(LegalizedNodes.count(Op) &&
413               "Expansion didn't add legal operands!");
414        return LegalizedNodes[Op];
415      }
416      case Promote:
417        PromoteOp(Op.getValue(i));
418        assert(LegalizedNodes.count(Op) &&
419               "Expansion didn't add legal operands!");
420        return LegalizedNodes[Op];
421      }
422  }
423
424  // Note that LegalizeOp may be reentered even from single-use nodes, which
425  // means that we always must cache transformed nodes.
426  std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
427  if (I != LegalizedNodes.end()) return I->second;
428
429  SDOperand Tmp1, Tmp2, Tmp3, Tmp4;
430
431  SDOperand Result = Op;
432
433  switch (Node->getOpcode()) {
434  default:
435    if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
436      // If this is a target node, legalize it by legalizing the operands then
437      // passing it through.
438      std::vector<SDOperand> Ops;
439      bool Changed = false;
440      for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
441        Ops.push_back(LegalizeOp(Node->getOperand(i)));
442        Changed = Changed || Node->getOperand(i) != Ops.back();
443      }
444      if (Changed)
445        if (Node->getNumValues() == 1)
446          Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Ops);
447        else {
448          std::vector<MVT::ValueType> VTs(Node->value_begin(),
449                                          Node->value_end());
450          Result = DAG.getNode(Node->getOpcode(), VTs, Ops);
451        }
452
453      for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
454        AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
455      return Result.getValue(Op.ResNo);
456    }
457    // Otherwise this is an unhandled builtin node.  splat.
458    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
459    assert(0 && "Do not know how to legalize this operator!");
460    abort();
461  case ISD::EntryToken:
462  case ISD::FrameIndex:
463  case ISD::GlobalAddress:
464  case ISD::ExternalSymbol:
465  case ISD::ConstantPool:           // Nothing to do.
466    assert(getTypeAction(Node->getValueType(0)) == Legal &&
467           "This must be legal!");
468    break;
469  case ISD::CopyFromReg:
470    Tmp1 = LegalizeOp(Node->getOperand(0));
471    if (Tmp1 != Node->getOperand(0))
472      Result = DAG.getCopyFromReg(Tmp1,
473                            cast<RegisterSDNode>(Node->getOperand(1))->getReg(),
474                                  Node->getValueType(0));
475    else
476      Result = Op.getValue(0);
477
478    // Since CopyFromReg produces two values, make sure to remember that we
479    // legalized both of them.
480    AddLegalizedOperand(Op.getValue(0), Result);
481    AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
482    return Result.getValue(Op.ResNo);
483  case ISD::ImplicitDef:
484    Tmp1 = LegalizeOp(Node->getOperand(0));
485    if (Tmp1 != Node->getOperand(0))
486      Result = DAG.getNode(ISD::ImplicitDef, MVT::Other,
487                           Tmp1, Node->getOperand(1));
488    break;
489  case ISD::UNDEF: {
490    MVT::ValueType VT = Op.getValueType();
491    switch (TLI.getOperationAction(ISD::UNDEF, VT)) {
492    default: assert(0 && "This action is not supported yet!");
493    case TargetLowering::Expand:
494    case TargetLowering::Promote:
495      if (MVT::isInteger(VT))
496        Result = DAG.getConstant(0, VT);
497      else if (MVT::isFloatingPoint(VT))
498        Result = DAG.getConstantFP(0, VT);
499      else
500        assert(0 && "Unknown value type!");
501      break;
502    case TargetLowering::Legal:
503      break;
504    }
505    break;
506  }
507  case ISD::Constant:
508    // We know we don't need to expand constants here, constants only have one
509    // value and we check that it is fine above.
510
511    // FIXME: Maybe we should handle things like targets that don't support full
512    // 32-bit immediates?
513    break;
514  case ISD::ConstantFP: {
515    // Spill FP immediates to the constant pool if the target cannot directly
516    // codegen them.  Targets often have some immediate values that can be
517    // efficiently generated into an FP register without a load.  We explicitly
518    // leave these constants as ConstantFP nodes for the target to deal with.
519
520    ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
521
522    // Check to see if this FP immediate is already legal.
523    bool isLegal = false;
524    for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
525           E = TLI.legal_fpimm_end(); I != E; ++I)
526      if (CFP->isExactlyValue(*I)) {
527        isLegal = true;
528        break;
529      }
530
531    if (!isLegal) {
532      // Otherwise we need to spill the constant to memory.
533      MachineConstantPool *CP = DAG.getMachineFunction().getConstantPool();
534
535      bool Extend = false;
536
537      // If a FP immediate is precise when represented as a float, we put it
538      // into the constant pool as a float, even if it's is statically typed
539      // as a double.
540      MVT::ValueType VT = CFP->getValueType(0);
541      bool isDouble = VT == MVT::f64;
542      ConstantFP *LLVMC = ConstantFP::get(isDouble ? Type::DoubleTy :
543                                             Type::FloatTy, CFP->getValue());
544      if (isDouble && CFP->isExactlyValue((float)CFP->getValue()) &&
545          // Only do this if the target has a native EXTLOAD instruction from
546          // f32.
547          TLI.getOperationAction(ISD::EXTLOAD,
548                                 MVT::f32) == TargetLowering::Legal) {
549        LLVMC = cast<ConstantFP>(ConstantExpr::getCast(LLVMC, Type::FloatTy));
550        VT = MVT::f32;
551        Extend = true;
552      }
553
554      SDOperand CPIdx = DAG.getConstantPool(CP->getConstantPoolIndex(LLVMC),
555                                            TLI.getPointerTy());
556      if (Extend) {
557        Result = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
558                                CPIdx, DAG.getSrcValue(NULL), MVT::f32);
559      } else {
560        Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
561                             DAG.getSrcValue(NULL));
562      }
563    }
564    break;
565  }
566  case ISD::TokenFactor: {
567    std::vector<SDOperand> Ops;
568    bool Changed = false;
569    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
570      SDOperand Op = Node->getOperand(i);
571      // Fold single-use TokenFactor nodes into this token factor as we go.
572      // FIXME: This is something that the DAGCombiner should do!!
573      if (Op.getOpcode() == ISD::TokenFactor && Op.hasOneUse()) {
574        Changed = true;
575        for (unsigned j = 0, e = Op.getNumOperands(); j != e; ++j)
576          Ops.push_back(LegalizeOp(Op.getOperand(j)));
577      } else {
578        Ops.push_back(LegalizeOp(Op));  // Legalize the operands
579        Changed |= Ops[i] != Op;
580      }
581    }
582    if (Changed)
583      Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Ops);
584    break;
585  }
586
587  case ISD::CALLSEQ_START:
588  case ISD::CALLSEQ_END:
589    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
590    // Do not try to legalize the target-specific arguments (#1+)
591    Tmp2 = Node->getOperand(0);
592    if (Tmp1 != Tmp2) {
593      Node->setAdjCallChain(Tmp1);
594
595      // If moving the operand from pointing to Tmp2 dropped its use count to 1,
596      // this will cause the maps used to memoize results to get confused.
597      // Create and add a dummy use, just to increase its use count.  This will
598      // be removed at the end of legalize when dead nodes are removed.
599      if (Tmp2.Val->hasOneUse())
600        DAG.getNode(ISD::PCMARKER, MVT::Other, Tmp2,
601                    DAG.getConstant(0, MVT::i32));
602    }
603    // Note that we do not create new CALLSEQ_DOWN/UP nodes here.  These
604    // nodes are treated specially and are mutated in place.  This makes the dag
605    // legalization process more efficient and also makes libcall insertion
606    // easier.
607    break;
608  case ISD::DYNAMIC_STACKALLOC:
609    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
610    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
611    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
612    if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
613        Tmp3 != Node->getOperand(2)) {
614      std::vector<MVT::ValueType> VTs(Node->value_begin(), Node->value_end());
615      std::vector<SDOperand> Ops;
616      Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
617      Result = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
618    } else
619      Result = Op.getValue(0);
620
621    // Since this op produces two values, make sure to remember that we
622    // legalized both of them.
623    AddLegalizedOperand(SDOperand(Node, 0), Result);
624    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
625    return Result.getValue(Op.ResNo);
626
627  case ISD::TAILCALL:
628  case ISD::CALL: {
629    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
630    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
631
632    bool Changed = false;
633    std::vector<SDOperand> Ops;
634    for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i) {
635      Ops.push_back(LegalizeOp(Node->getOperand(i)));
636      Changed |= Ops.back() != Node->getOperand(i);
637    }
638
639    if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) || Changed) {
640      std::vector<MVT::ValueType> RetTyVTs;
641      RetTyVTs.reserve(Node->getNumValues());
642      for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
643        RetTyVTs.push_back(Node->getValueType(i));
644      Result = SDOperand(DAG.getCall(RetTyVTs, Tmp1, Tmp2, Ops,
645                                     Node->getOpcode() == ISD::TAILCALL), 0);
646    } else {
647      Result = Result.getValue(0);
648    }
649    // Since calls produce multiple values, make sure to remember that we
650    // legalized all of them.
651    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
652      AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
653    return Result.getValue(Op.ResNo);
654  }
655  case ISD::BR:
656    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
657    if (Tmp1 != Node->getOperand(0))
658      Result = DAG.getNode(ISD::BR, MVT::Other, Tmp1, Node->getOperand(1));
659    break;
660
661  case ISD::BRCOND:
662    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
663
664    switch (getTypeAction(Node->getOperand(1).getValueType())) {
665    case Expand: assert(0 && "It's impossible to expand bools");
666    case Legal:
667      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
668      break;
669    case Promote:
670      Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
671      break;
672    }
673
674    switch (TLI.getOperationAction(ISD::BRCOND, MVT::Other)) {
675    default: assert(0 && "This action is not supported yet!");
676    case TargetLowering::Expand:
677      // Expand brcond's setcc into its constituent parts and create a BR_CC
678      // Node.
679      if (Tmp2.getOpcode() == ISD::SETCC) {
680        Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Tmp2.getOperand(2),
681                             Tmp2.getOperand(0), Tmp2.getOperand(1),
682                             Node->getOperand(2));
683      } else {
684        Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1,
685                             DAG.getCondCode(ISD::SETNE), Tmp2,
686                             DAG.getConstant(0, Tmp2.getValueType()),
687                             Node->getOperand(2));
688      }
689      break;
690    case TargetLowering::Legal:
691      // Basic block destination (Op#2) is always legal.
692      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
693        Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
694                             Node->getOperand(2));
695        break;
696    }
697    break;
698  case ISD::BR_CC:
699    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
700
701    if (getTypeAction(Node->getOperand(2).getValueType()) == Legal) {
702      Tmp2 = LegalizeOp(Node->getOperand(2));   // LHS
703      Tmp3 = LegalizeOp(Node->getOperand(3));   // RHS
704      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(2) ||
705          Tmp3 != Node->getOperand(3)) {
706        Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Node->getOperand(1),
707                             Tmp2, Tmp3, Node->getOperand(4));
708      }
709      break;
710    } else {
711      Tmp2 = LegalizeOp(DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),
712                                    Node->getOperand(2),  // LHS
713                                    Node->getOperand(3),  // RHS
714                                    Node->getOperand(1)));
715      // If we get a SETCC back from legalizing the SETCC node we just
716      // created, then use its LHS, RHS, and CC directly in creating a new
717      // node.  Otherwise, select between the true and false value based on
718      // comparing the result of the legalized with zero.
719      if (Tmp2.getOpcode() == ISD::SETCC) {
720        Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Tmp2.getOperand(2),
721                             Tmp2.getOperand(0), Tmp2.getOperand(1),
722                             Node->getOperand(4));
723      } else {
724        Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1,
725                             DAG.getCondCode(ISD::SETNE),
726                             Tmp2, DAG.getConstant(0, Tmp2.getValueType()),
727                             Node->getOperand(4));
728      }
729    }
730    break;
731  case ISD::BRCONDTWOWAY:
732    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
733    switch (getTypeAction(Node->getOperand(1).getValueType())) {
734    case Expand: assert(0 && "It's impossible to expand bools");
735    case Legal:
736      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
737      break;
738    case Promote:
739      Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
740      break;
741    }
742    // If this target does not support BRCONDTWOWAY, lower it to a BRCOND/BR
743    // pair.
744    switch (TLI.getOperationAction(ISD::BRCONDTWOWAY, MVT::Other)) {
745    case TargetLowering::Promote:
746    default: assert(0 && "This action is not supported yet!");
747    case TargetLowering::Legal:
748      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1)) {
749        std::vector<SDOperand> Ops;
750        Ops.push_back(Tmp1);
751        Ops.push_back(Tmp2);
752        Ops.push_back(Node->getOperand(2));
753        Ops.push_back(Node->getOperand(3));
754        Result = DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops);
755      }
756      break;
757    case TargetLowering::Expand:
758      // If BRTWOWAY_CC is legal for this target, then simply expand this node
759      // to that.  Otherwise, skip BRTWOWAY_CC and expand directly to a
760      // BRCOND/BR pair.
761      if (TLI.getOperationAction(ISD::BRTWOWAY_CC, MVT::Other) ==
762          TargetLowering::Legal) {
763        if (Tmp2.getOpcode() == ISD::SETCC) {
764          Result = DAG.getBR2Way_CC(Tmp1, Tmp2.getOperand(2),
765                                    Tmp2.getOperand(0), Tmp2.getOperand(1),
766                                    Node->getOperand(2), Node->getOperand(3));
767        } else {
768          Result = DAG.getBR2Way_CC(Tmp1, DAG.getCondCode(ISD::SETNE), Tmp2,
769                                    DAG.getConstant(0, Tmp2.getValueType()),
770                                    Node->getOperand(2), Node->getOperand(3));
771        }
772      } else {
773        Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
774                           Node->getOperand(2));
775        Result = DAG.getNode(ISD::BR, MVT::Other, Result, Node->getOperand(3));
776      }
777      break;
778    }
779    break;
780  case ISD::BRTWOWAY_CC:
781    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
782    if (getTypeAction(Node->getOperand(2).getValueType()) == Legal) {
783      Tmp2 = LegalizeOp(Node->getOperand(2));   // LHS
784      Tmp3 = LegalizeOp(Node->getOperand(3));   // RHS
785      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(2) ||
786          Tmp3 != Node->getOperand(3)) {
787        Result = DAG.getBR2Way_CC(Tmp1, Node->getOperand(1), Tmp2, Tmp3,
788                                  Node->getOperand(4), Node->getOperand(5));
789      }
790      break;
791    } else {
792      Tmp2 = LegalizeOp(DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),
793                                    Node->getOperand(2),  // LHS
794                                    Node->getOperand(3),  // RHS
795                                    Node->getOperand(1)));
796      // If this target does not support BRTWOWAY_CC, lower it to a BRCOND/BR
797      // pair.
798      switch (TLI.getOperationAction(ISD::BRTWOWAY_CC, MVT::Other)) {
799      default: assert(0 && "This action is not supported yet!");
800      case TargetLowering::Legal:
801        // If we get a SETCC back from legalizing the SETCC node we just
802        // created, then use its LHS, RHS, and CC directly in creating a new
803        // node.  Otherwise, select between the true and false value based on
804        // comparing the result of the legalized with zero.
805        if (Tmp2.getOpcode() == ISD::SETCC) {
806          Result = DAG.getBR2Way_CC(Tmp1, Tmp2.getOperand(2),
807                                    Tmp2.getOperand(0), Tmp2.getOperand(1),
808                                    Node->getOperand(4), Node->getOperand(5));
809        } else {
810          Result = DAG.getBR2Way_CC(Tmp1, DAG.getCondCode(ISD::SETNE), Tmp2,
811                                    DAG.getConstant(0, Tmp2.getValueType()),
812                                    Node->getOperand(4), Node->getOperand(5));
813        }
814        break;
815      case TargetLowering::Expand:
816        Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
817                             Node->getOperand(4));
818        Result = DAG.getNode(ISD::BR, MVT::Other, Result, Node->getOperand(5));
819        break;
820      }
821    }
822    break;
823  case ISD::LOAD:
824    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
825    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
826
827    if (Tmp1 != Node->getOperand(0) ||
828        Tmp2 != Node->getOperand(1))
829      Result = DAG.getLoad(Node->getValueType(0), Tmp1, Tmp2,
830                           Node->getOperand(2));
831    else
832      Result = SDOperand(Node, 0);
833
834    // Since loads produce two values, make sure to remember that we legalized
835    // both of them.
836    AddLegalizedOperand(SDOperand(Node, 0), Result);
837    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
838    return Result.getValue(Op.ResNo);
839
840  case ISD::EXTLOAD:
841  case ISD::SEXTLOAD:
842  case ISD::ZEXTLOAD: {
843    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
844    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
845
846    MVT::ValueType SrcVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
847    switch (TLI.getOperationAction(Node->getOpcode(), SrcVT)) {
848    default: assert(0 && "This action is not supported yet!");
849    case TargetLowering::Promote:
850      assert(SrcVT == MVT::i1 && "Can only promote EXTLOAD from i1 -> i8!");
851      Result = DAG.getExtLoad(Node->getOpcode(), Node->getValueType(0),
852                              Tmp1, Tmp2, Node->getOperand(2), MVT::i8);
853      // Since loads produce two values, make sure to remember that we legalized
854      // both of them.
855      AddLegalizedOperand(SDOperand(Node, 0), Result);
856      AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
857      return Result.getValue(Op.ResNo);
858
859    case TargetLowering::Legal:
860      if (Tmp1 != Node->getOperand(0) ||
861          Tmp2 != Node->getOperand(1))
862        Result = DAG.getExtLoad(Node->getOpcode(), Node->getValueType(0),
863                                Tmp1, Tmp2, Node->getOperand(2), SrcVT);
864      else
865        Result = SDOperand(Node, 0);
866
867      // Since loads produce two values, make sure to remember that we legalized
868      // both of them.
869      AddLegalizedOperand(SDOperand(Node, 0), Result);
870      AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
871      return Result.getValue(Op.ResNo);
872    case TargetLowering::Expand:
873      //f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
874      if (SrcVT == MVT::f32 && Node->getValueType(0) == MVT::f64) {
875        SDOperand Load = DAG.getLoad(SrcVT, Tmp1, Tmp2, Node->getOperand(2));
876        Result = DAG.getNode(ISD::FP_EXTEND, Node->getValueType(0), Load);
877        if (Op.ResNo)
878          return Load.getValue(1);
879        return Result;
880      }
881      assert(Node->getOpcode() != ISD::EXTLOAD &&
882             "EXTLOAD should always be supported!");
883      // Turn the unsupported load into an EXTLOAD followed by an explicit
884      // zero/sign extend inreg.
885      Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
886                              Tmp1, Tmp2, Node->getOperand(2), SrcVT);
887      SDOperand ValRes;
888      if (Node->getOpcode() == ISD::SEXTLOAD)
889        ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
890                             Result, DAG.getValueType(SrcVT));
891      else
892        ValRes = DAG.getZeroExtendInReg(Result, SrcVT);
893      AddLegalizedOperand(SDOperand(Node, 0), ValRes);
894      AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
895      if (Op.ResNo)
896        return Result.getValue(1);
897      return ValRes;
898    }
899    assert(0 && "Unreachable");
900  }
901  case ISD::EXTRACT_ELEMENT:
902    // Get both the low and high parts.
903    ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
904    if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
905      Result = Tmp2;  // 1 -> Hi
906    else
907      Result = Tmp1;  // 0 -> Lo
908    break;
909
910  case ISD::CopyToReg:
911    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
912
913    assert(getTypeAction(Node->getOperand(2).getValueType()) == Legal &&
914           "Register type must be legal!");
915    // Legalize the incoming value (must be legal).
916    Tmp2 = LegalizeOp(Node->getOperand(2));
917    if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(2))
918      Result = DAG.getNode(ISD::CopyToReg, MVT::Other, Tmp1,
919                           Node->getOperand(1), Tmp2);
920    break;
921
922  case ISD::RET:
923    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
924    switch (Node->getNumOperands()) {
925    case 2:  // ret val
926      switch (getTypeAction(Node->getOperand(1).getValueType())) {
927      case Legal:
928        Tmp2 = LegalizeOp(Node->getOperand(1));
929        if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
930          Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
931        break;
932      case Expand: {
933        SDOperand Lo, Hi;
934        ExpandOp(Node->getOperand(1), Lo, Hi);
935        Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
936        break;
937      }
938      case Promote:
939        Tmp2 = PromoteOp(Node->getOperand(1));
940        Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
941        break;
942      }
943      break;
944    case 1:  // ret void
945      if (Tmp1 != Node->getOperand(0))
946        Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1);
947      break;
948    default: { // ret <values>
949      std::vector<SDOperand> NewValues;
950      NewValues.push_back(Tmp1);
951      for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
952        switch (getTypeAction(Node->getOperand(i).getValueType())) {
953        case Legal:
954          NewValues.push_back(LegalizeOp(Node->getOperand(i)));
955          break;
956        case Expand: {
957          SDOperand Lo, Hi;
958          ExpandOp(Node->getOperand(i), Lo, Hi);
959          NewValues.push_back(Lo);
960          NewValues.push_back(Hi);
961          break;
962        }
963        case Promote:
964          assert(0 && "Can't promote multiple return value yet!");
965        }
966      Result = DAG.getNode(ISD::RET, MVT::Other, NewValues);
967      break;
968    }
969    }
970    break;
971  case ISD::STORE:
972    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
973    Tmp2 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
974
975    // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
976    if (ConstantFPSDNode *CFP =dyn_cast<ConstantFPSDNode>(Node->getOperand(1))){
977      if (CFP->getValueType(0) == MVT::f32) {
978        union {
979          unsigned I;
980          float    F;
981        } V;
982        V.F = CFP->getValue();
983        Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
984                             DAG.getConstant(V.I, MVT::i32), Tmp2,
985                             Node->getOperand(3));
986      } else {
987        assert(CFP->getValueType(0) == MVT::f64 && "Unknown FP type!");
988        union {
989          uint64_t I;
990          double   F;
991        } V;
992        V.F = CFP->getValue();
993        Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
994                             DAG.getConstant(V.I, MVT::i64), Tmp2,
995                             Node->getOperand(3));
996      }
997      Node = Result.Val;
998    }
999
1000    switch (getTypeAction(Node->getOperand(1).getValueType())) {
1001    case Legal: {
1002      SDOperand Val = LegalizeOp(Node->getOperand(1));
1003      if (Val != Node->getOperand(1) || Tmp1 != Node->getOperand(0) ||
1004          Tmp2 != Node->getOperand(2))
1005        Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Val, Tmp2,
1006                             Node->getOperand(3));
1007      break;
1008    }
1009    case Promote:
1010      // Truncate the value and store the result.
1011      Tmp3 = PromoteOp(Node->getOperand(1));
1012      Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp3, Tmp2,
1013                           Node->getOperand(3),
1014                          DAG.getValueType(Node->getOperand(1).getValueType()));
1015      break;
1016
1017    case Expand:
1018      SDOperand Lo, Hi;
1019      ExpandOp(Node->getOperand(1), Lo, Hi);
1020
1021      if (!TLI.isLittleEndian())
1022        std::swap(Lo, Hi);
1023
1024      Lo = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Lo, Tmp2,
1025                       Node->getOperand(3));
1026      unsigned IncrementSize = MVT::getSizeInBits(Hi.getValueType())/8;
1027      Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
1028                         getIntPtrConstant(IncrementSize));
1029      assert(isTypeLegal(Tmp2.getValueType()) &&
1030             "Pointers must be legal!");
1031      //Again, claiming both parts of the store came form the same Instr
1032      Hi = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Hi, Tmp2,
1033                       Node->getOperand(3));
1034      Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
1035      break;
1036    }
1037    break;
1038  case ISD::PCMARKER:
1039    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1040    if (Tmp1 != Node->getOperand(0))
1041      Result = DAG.getNode(ISD::PCMARKER, MVT::Other, Tmp1,Node->getOperand(1));
1042    break;
1043  case ISD::TRUNCSTORE:
1044    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1045    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
1046
1047    switch (getTypeAction(Node->getOperand(1).getValueType())) {
1048    case Legal:
1049      Tmp2 = LegalizeOp(Node->getOperand(1));
1050      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1051          Tmp3 != Node->getOperand(2))
1052        Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
1053                             Node->getOperand(3), Node->getOperand(4));
1054      break;
1055    case Promote:
1056    case Expand:
1057      assert(0 && "Cannot handle illegal TRUNCSTORE yet!");
1058    }
1059    break;
1060  case ISD::SELECT:
1061    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1062    case Expand: assert(0 && "It's impossible to expand bools");
1063    case Legal:
1064      Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
1065      break;
1066    case Promote:
1067      Tmp1 = PromoteOp(Node->getOperand(0));  // Promote the condition.
1068      break;
1069    }
1070    Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
1071    Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
1072
1073    switch (TLI.getOperationAction(Node->getOpcode(), Tmp2.getValueType())) {
1074    default: assert(0 && "This action is not supported yet!");
1075    case TargetLowering::Expand:
1076      if (Tmp1.getOpcode() == ISD::SETCC) {
1077        Result = DAG.getSelectCC(Tmp1.getOperand(0), Tmp1.getOperand(1),
1078                              Tmp2, Tmp3,
1079                              cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
1080      } else {
1081        Result = DAG.getSelectCC(Tmp1,
1082                                 DAG.getConstant(0, Tmp1.getValueType()),
1083                                 Tmp2, Tmp3, ISD::SETNE);
1084      }
1085      break;
1086    case TargetLowering::Legal:
1087      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1088          Tmp3 != Node->getOperand(2))
1089        Result = DAG.getNode(ISD::SELECT, Node->getValueType(0),
1090                             Tmp1, Tmp2, Tmp3);
1091      break;
1092    case TargetLowering::Promote: {
1093      MVT::ValueType NVT =
1094        TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
1095      unsigned ExtOp, TruncOp;
1096      if (MVT::isInteger(Tmp2.getValueType())) {
1097        ExtOp = ISD::ZERO_EXTEND;
1098        TruncOp  = ISD::TRUNCATE;
1099      } else {
1100        ExtOp = ISD::FP_EXTEND;
1101        TruncOp  = ISD::FP_ROUND;
1102      }
1103      // Promote each of the values to the new type.
1104      Tmp2 = DAG.getNode(ExtOp, NVT, Tmp2);
1105      Tmp3 = DAG.getNode(ExtOp, NVT, Tmp3);
1106      // Perform the larger operation, then round down.
1107      Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2,Tmp3);
1108      Result = DAG.getNode(TruncOp, Node->getValueType(0), Result);
1109      break;
1110    }
1111    }
1112    break;
1113  case ISD::SELECT_CC:
1114    Tmp3 = LegalizeOp(Node->getOperand(2));   // True
1115    Tmp4 = LegalizeOp(Node->getOperand(3));   // False
1116
1117    if (getTypeAction(Node->getOperand(0).getValueType()) == Legal) {
1118      Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
1119      Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
1120      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1121          Tmp3 != Node->getOperand(2) || Tmp4 != Node->getOperand(3)) {
1122        Result = DAG.getNode(ISD::SELECT_CC, Node->getValueType(0), Tmp1, Tmp2,
1123                             Tmp3, Tmp4, Node->getOperand(4));
1124      }
1125      break;
1126    } else {
1127      Tmp1 = LegalizeOp(DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),
1128                                    Node->getOperand(0),  // LHS
1129                                    Node->getOperand(1),  // RHS
1130                                    Node->getOperand(4)));
1131      // If we get a SETCC back from legalizing the SETCC node we just
1132      // created, then use its LHS, RHS, and CC directly in creating a new
1133      // node.  Otherwise, select between the true and false value based on
1134      // comparing the result of the legalized with zero.
1135      if (Tmp1.getOpcode() == ISD::SETCC) {
1136        Result = DAG.getNode(ISD::SELECT_CC, Tmp3.getValueType(),
1137                             Tmp1.getOperand(0), Tmp1.getOperand(1),
1138                             Tmp3, Tmp4, Tmp1.getOperand(2));
1139      } else {
1140        Result = DAG.getSelectCC(Tmp1,
1141                                 DAG.getConstant(0, Tmp1.getValueType()),
1142                                 Tmp3, Tmp4, ISD::SETNE);
1143      }
1144    }
1145    break;
1146  case ISD::SETCC:
1147    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1148    case Legal:
1149      Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
1150      Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
1151      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
1152        Result = DAG.getNode(ISD::SETCC, Node->getValueType(0), Tmp1, Tmp2,
1153                             Node->getOperand(2));
1154      break;
1155    case Promote:
1156      Tmp1 = PromoteOp(Node->getOperand(0));   // LHS
1157      Tmp2 = PromoteOp(Node->getOperand(1));   // RHS
1158
1159      // If this is an FP compare, the operands have already been extended.
1160      if (MVT::isInteger(Node->getOperand(0).getValueType())) {
1161        MVT::ValueType VT = Node->getOperand(0).getValueType();
1162        MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
1163
1164        // Otherwise, we have to insert explicit sign or zero extends.  Note
1165        // that we could insert sign extends for ALL conditions, but zero extend
1166        // is cheaper on many machines (an AND instead of two shifts), so prefer
1167        // it.
1168        switch (cast<CondCodeSDNode>(Node->getOperand(2))->get()) {
1169        default: assert(0 && "Unknown integer comparison!");
1170        case ISD::SETEQ:
1171        case ISD::SETNE:
1172        case ISD::SETUGE:
1173        case ISD::SETUGT:
1174        case ISD::SETULE:
1175        case ISD::SETULT:
1176          // ALL of these operations will work if we either sign or zero extend
1177          // the operands (including the unsigned comparisons!).  Zero extend is
1178          // usually a simpler/cheaper operation, so prefer it.
1179          Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
1180          Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
1181          break;
1182        case ISD::SETGE:
1183        case ISD::SETGT:
1184        case ISD::SETLT:
1185        case ISD::SETLE:
1186          Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
1187                             DAG.getValueType(VT));
1188          Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
1189                             DAG.getValueType(VT));
1190          break;
1191        }
1192
1193      }
1194      Result = DAG.getNode(ISD::SETCC, Node->getValueType(0), Tmp1, Tmp2,
1195                           Node->getOperand(2));
1196      break;
1197    case Expand:
1198      SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
1199      ExpandOp(Node->getOperand(0), LHSLo, LHSHi);
1200      ExpandOp(Node->getOperand(1), RHSLo, RHSHi);
1201      switch (cast<CondCodeSDNode>(Node->getOperand(2))->get()) {
1202      case ISD::SETEQ:
1203      case ISD::SETNE:
1204        if (RHSLo == RHSHi)
1205          if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo))
1206            if (RHSCST->isAllOnesValue()) {
1207              // Comparison to -1.
1208              Tmp1 = DAG.getNode(ISD::AND, LHSLo.getValueType(), LHSLo, LHSHi);
1209              Result = DAG.getNode(ISD::SETCC, Node->getValueType(0), Tmp1,
1210                                   RHSLo, Node->getOperand(2));
1211              break;
1212            }
1213
1214        Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
1215        Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
1216        Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
1217        Result = DAG.getNode(ISD::SETCC, Node->getValueType(0), Tmp1,
1218                             DAG.getConstant(0, Tmp1.getValueType()),
1219                             Node->getOperand(2));
1220        break;
1221      default:
1222        // If this is a comparison of the sign bit, just look at the top part.
1223        // X > -1,  x < 0
1224        if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Node->getOperand(1)))
1225          if ((cast<CondCodeSDNode>(Node->getOperand(2))->get() == ISD::SETLT &&
1226               CST->getValue() == 0) ||              // X < 0
1227              (cast<CondCodeSDNode>(Node->getOperand(2))->get() == ISD::SETGT &&
1228               (CST->isAllOnesValue())))             // X > -1
1229            return DAG.getNode(ISD::SETCC, Node->getValueType(0), LHSHi, RHSHi,
1230                               Node->getOperand(2));
1231
1232        // FIXME: This generated code sucks.
1233        ISD::CondCode LowCC;
1234        switch (cast<CondCodeSDNode>(Node->getOperand(2))->get()) {
1235        default: assert(0 && "Unknown integer setcc!");
1236        case ISD::SETLT:
1237        case ISD::SETULT: LowCC = ISD::SETULT; break;
1238        case ISD::SETGT:
1239        case ISD::SETUGT: LowCC = ISD::SETUGT; break;
1240        case ISD::SETLE:
1241        case ISD::SETULE: LowCC = ISD::SETULE; break;
1242        case ISD::SETGE:
1243        case ISD::SETUGE: LowCC = ISD::SETUGE; break;
1244        }
1245
1246        // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
1247        // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
1248        // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
1249
1250        // NOTE: on targets without efficient SELECT of bools, we can always use
1251        // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
1252        Tmp1 = DAG.getSetCC(Node->getValueType(0), LHSLo, RHSLo, LowCC);
1253        Tmp2 = DAG.getNode(ISD::SETCC, Node->getValueType(0), LHSHi, RHSHi,
1254                           Node->getOperand(2));
1255        Result = DAG.getSetCC(Node->getValueType(0), LHSHi, RHSHi, ISD::SETEQ);
1256        Result = DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
1257                             Result, Tmp1, Tmp2);
1258        break;
1259      }
1260    }
1261    break;
1262
1263  case ISD::MEMSET:
1264  case ISD::MEMCPY:
1265  case ISD::MEMMOVE: {
1266    Tmp1 = LegalizeOp(Node->getOperand(0));      // Chain
1267    Tmp2 = LegalizeOp(Node->getOperand(1));      // Pointer
1268
1269    if (Node->getOpcode() == ISD::MEMSET) {      // memset = ubyte
1270      switch (getTypeAction(Node->getOperand(2).getValueType())) {
1271      case Expand: assert(0 && "Cannot expand a byte!");
1272      case Legal:
1273        Tmp3 = LegalizeOp(Node->getOperand(2));
1274        break;
1275      case Promote:
1276        Tmp3 = PromoteOp(Node->getOperand(2));
1277        break;
1278      }
1279    } else {
1280      Tmp3 = LegalizeOp(Node->getOperand(2));    // memcpy/move = pointer,
1281    }
1282
1283    SDOperand Tmp4;
1284    switch (getTypeAction(Node->getOperand(3).getValueType())) {
1285    case Expand: {
1286      // Length is too big, just take the lo-part of the length.
1287      SDOperand HiPart;
1288      ExpandOp(Node->getOperand(3), HiPart, Tmp4);
1289      break;
1290    }
1291    case Legal:
1292      Tmp4 = LegalizeOp(Node->getOperand(3));
1293      break;
1294    case Promote:
1295      Tmp4 = PromoteOp(Node->getOperand(3));
1296      break;
1297    }
1298
1299    SDOperand Tmp5;
1300    switch (getTypeAction(Node->getOperand(4).getValueType())) {  // uint
1301    case Expand: assert(0 && "Cannot expand this yet!");
1302    case Legal:
1303      Tmp5 = LegalizeOp(Node->getOperand(4));
1304      break;
1305    case Promote:
1306      Tmp5 = PromoteOp(Node->getOperand(4));
1307      break;
1308    }
1309
1310    switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
1311    default: assert(0 && "This action not implemented for this operation!");
1312    case TargetLowering::Legal:
1313      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1314          Tmp3 != Node->getOperand(2) || Tmp4 != Node->getOperand(3) ||
1315          Tmp5 != Node->getOperand(4)) {
1316        std::vector<SDOperand> Ops;
1317        Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
1318        Ops.push_back(Tmp4); Ops.push_back(Tmp5);
1319        Result = DAG.getNode(Node->getOpcode(), MVT::Other, Ops);
1320      }
1321      break;
1322    case TargetLowering::Expand: {
1323      // Otherwise, the target does not support this operation.  Lower the
1324      // operation to an explicit libcall as appropriate.
1325      MVT::ValueType IntPtr = TLI.getPointerTy();
1326      const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
1327      std::vector<std::pair<SDOperand, const Type*> > Args;
1328
1329      const char *FnName = 0;
1330      if (Node->getOpcode() == ISD::MEMSET) {
1331        Args.push_back(std::make_pair(Tmp2, IntPtrTy));
1332        // Extend the ubyte argument to be an int value for the call.
1333        Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Tmp3);
1334        Args.push_back(std::make_pair(Tmp3, Type::IntTy));
1335        Args.push_back(std::make_pair(Tmp4, IntPtrTy));
1336
1337        FnName = "memset";
1338      } else if (Node->getOpcode() == ISD::MEMCPY ||
1339                 Node->getOpcode() == ISD::MEMMOVE) {
1340        Args.push_back(std::make_pair(Tmp2, IntPtrTy));
1341        Args.push_back(std::make_pair(Tmp3, IntPtrTy));
1342        Args.push_back(std::make_pair(Tmp4, IntPtrTy));
1343        FnName = Node->getOpcode() == ISD::MEMMOVE ? "memmove" : "memcpy";
1344      } else {
1345        assert(0 && "Unknown op!");
1346      }
1347
1348      std::pair<SDOperand,SDOperand> CallResult =
1349        TLI.LowerCallTo(Tmp1, Type::VoidTy, false, CallingConv::C, false,
1350                        DAG.getExternalSymbol(FnName, IntPtr), Args, DAG);
1351      Result = CallResult.second;
1352      NeedsAnotherIteration = true;
1353      break;
1354    }
1355    case TargetLowering::Custom:
1356      std::vector<SDOperand> Ops;
1357      Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
1358      Ops.push_back(Tmp4); Ops.push_back(Tmp5);
1359      Result = DAG.getNode(Node->getOpcode(), MVT::Other, Ops);
1360      Result = TLI.LowerOperation(Result, DAG);
1361      Result = LegalizeOp(Result);
1362      break;
1363    }
1364    break;
1365  }
1366
1367  case ISD::READPORT:
1368    Tmp1 = LegalizeOp(Node->getOperand(0));
1369    Tmp2 = LegalizeOp(Node->getOperand(1));
1370
1371    if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1)) {
1372      std::vector<MVT::ValueType> VTs(Node->value_begin(), Node->value_end());
1373      std::vector<SDOperand> Ops;
1374      Ops.push_back(Tmp1);
1375      Ops.push_back(Tmp2);
1376      Result = DAG.getNode(ISD::READPORT, VTs, Ops);
1377    } else
1378      Result = SDOperand(Node, 0);
1379    // Since these produce two values, make sure to remember that we legalized
1380    // both of them.
1381    AddLegalizedOperand(SDOperand(Node, 0), Result);
1382    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1383    return Result.getValue(Op.ResNo);
1384  case ISD::WRITEPORT:
1385    Tmp1 = LegalizeOp(Node->getOperand(0));
1386    Tmp2 = LegalizeOp(Node->getOperand(1));
1387    Tmp3 = LegalizeOp(Node->getOperand(2));
1388    if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1389        Tmp3 != Node->getOperand(2))
1390      Result = DAG.getNode(Node->getOpcode(), MVT::Other, Tmp1, Tmp2, Tmp3);
1391    break;
1392
1393  case ISD::READIO:
1394    Tmp1 = LegalizeOp(Node->getOperand(0));
1395    Tmp2 = LegalizeOp(Node->getOperand(1));
1396
1397    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1398    case TargetLowering::Custom:
1399    default: assert(0 && "This action not implemented for this operation!");
1400    case TargetLowering::Legal:
1401      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1)) {
1402        std::vector<MVT::ValueType> VTs(Node->value_begin(), Node->value_end());
1403        std::vector<SDOperand> Ops;
1404        Ops.push_back(Tmp1);
1405        Ops.push_back(Tmp2);
1406        Result = DAG.getNode(ISD::READPORT, VTs, Ops);
1407      } else
1408        Result = SDOperand(Node, 0);
1409      break;
1410    case TargetLowering::Expand:
1411      // Replace this with a load from memory.
1412      Result = DAG.getLoad(Node->getValueType(0), Node->getOperand(0),
1413                           Node->getOperand(1), DAG.getSrcValue(NULL));
1414      Result = LegalizeOp(Result);
1415      break;
1416    }
1417
1418    // Since these produce two values, make sure to remember that we legalized
1419    // both of them.
1420    AddLegalizedOperand(SDOperand(Node, 0), Result);
1421    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1422    return Result.getValue(Op.ResNo);
1423
1424  case ISD::WRITEIO:
1425    Tmp1 = LegalizeOp(Node->getOperand(0));
1426    Tmp2 = LegalizeOp(Node->getOperand(1));
1427    Tmp3 = LegalizeOp(Node->getOperand(2));
1428
1429    switch (TLI.getOperationAction(Node->getOpcode(),
1430                                   Node->getOperand(1).getValueType())) {
1431    case TargetLowering::Custom:
1432    default: assert(0 && "This action not implemented for this operation!");
1433    case TargetLowering::Legal:
1434      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1435          Tmp3 != Node->getOperand(2))
1436        Result = DAG.getNode(Node->getOpcode(), MVT::Other, Tmp1, Tmp2, Tmp3);
1437      break;
1438    case TargetLowering::Expand:
1439      // Replace this with a store to memory.
1440      Result = DAG.getNode(ISD::STORE, MVT::Other, Node->getOperand(0),
1441                           Node->getOperand(1), Node->getOperand(2),
1442                           DAG.getSrcValue(NULL));
1443      Result = LegalizeOp(Result);
1444      break;
1445    }
1446    break;
1447
1448  case ISD::ADD_PARTS:
1449  case ISD::SUB_PARTS:
1450  case ISD::SHL_PARTS:
1451  case ISD::SRA_PARTS:
1452  case ISD::SRL_PARTS: {
1453    std::vector<SDOperand> Ops;
1454    bool Changed = false;
1455    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1456      Ops.push_back(LegalizeOp(Node->getOperand(i)));
1457      Changed |= Ops.back() != Node->getOperand(i);
1458    }
1459    if (Changed) {
1460      std::vector<MVT::ValueType> VTs(Node->value_begin(), Node->value_end());
1461      Result = DAG.getNode(Node->getOpcode(), VTs, Ops);
1462    }
1463
1464    // Since these produce multiple values, make sure to remember that we
1465    // legalized all of them.
1466    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
1467      AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
1468    return Result.getValue(Op.ResNo);
1469  }
1470
1471    // Binary operators
1472  case ISD::ADD:
1473  case ISD::SUB:
1474  case ISD::MUL:
1475  case ISD::MULHS:
1476  case ISD::MULHU:
1477  case ISD::UDIV:
1478  case ISD::SDIV:
1479  case ISD::AND:
1480  case ISD::OR:
1481  case ISD::XOR:
1482  case ISD::SHL:
1483  case ISD::SRL:
1484  case ISD::SRA:
1485    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
1486    switch (getTypeAction(Node->getOperand(1).getValueType())) {
1487    case Expand: assert(0 && "Not possible");
1488    case Legal:
1489      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
1490      break;
1491    case Promote:
1492      Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
1493      break;
1494    }
1495    if (Tmp1 != Node->getOperand(0) ||
1496        Tmp2 != Node->getOperand(1))
1497      Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,Tmp2);
1498    break;
1499
1500  case ISD::UREM:
1501  case ISD::SREM:
1502    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
1503    Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
1504    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1505    case TargetLowering::Legal:
1506      if (Tmp1 != Node->getOperand(0) ||
1507          Tmp2 != Node->getOperand(1))
1508        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
1509                             Tmp2);
1510      break;
1511    case TargetLowering::Promote:
1512    case TargetLowering::Custom:
1513      assert(0 && "Cannot promote/custom handle this yet!");
1514    case TargetLowering::Expand:
1515      if (MVT::isInteger(Node->getValueType(0))) {
1516        MVT::ValueType VT = Node->getValueType(0);
1517        unsigned Opc = (Node->getOpcode() == ISD::UREM) ? ISD::UDIV : ISD::SDIV;
1518        Result = DAG.getNode(Opc, VT, Tmp1, Tmp2);
1519        Result = DAG.getNode(ISD::MUL, VT, Result, Tmp2);
1520        Result = DAG.getNode(ISD::SUB, VT, Tmp1, Result);
1521      } else {
1522        // Floating point mod -> fmod libcall.
1523        const char *FnName = Node->getValueType(0) == MVT::f32 ? "fmodf":"fmod";
1524        SDOperand Dummy;
1525        Result = ExpandLibCall(FnName, Node, Dummy);
1526      }
1527      break;
1528    }
1529    break;
1530
1531  case ISD::CTPOP:
1532  case ISD::CTTZ:
1533  case ISD::CTLZ:
1534    Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
1535    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1536    case TargetLowering::Legal:
1537      if (Tmp1 != Node->getOperand(0))
1538        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1539      break;
1540    case TargetLowering::Promote: {
1541      MVT::ValueType OVT = Tmp1.getValueType();
1542      MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
1543
1544      // Zero extend the argument.
1545      Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
1546      // Perform the larger operation, then subtract if needed.
1547      Tmp1 = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1548      switch(Node->getOpcode())
1549      {
1550      case ISD::CTPOP:
1551        Result = Tmp1;
1552        break;
1553      case ISD::CTTZ:
1554        //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
1555        Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
1556                            DAG.getConstant(getSizeInBits(NVT), NVT),
1557                            ISD::SETEQ);
1558        Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
1559                           DAG.getConstant(getSizeInBits(OVT),NVT), Tmp1);
1560        break;
1561      case ISD::CTLZ:
1562        //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
1563        Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
1564                             DAG.getConstant(getSizeInBits(NVT) -
1565                                             getSizeInBits(OVT), NVT));
1566        break;
1567      }
1568      break;
1569    }
1570    case TargetLowering::Custom:
1571      assert(0 && "Cannot custom handle this yet!");
1572    case TargetLowering::Expand:
1573      switch(Node->getOpcode())
1574      {
1575      case ISD::CTPOP: {
1576        static const uint64_t mask[6] = {
1577          0x5555555555555555ULL, 0x3333333333333333ULL,
1578          0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
1579          0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
1580        };
1581        MVT::ValueType VT = Tmp1.getValueType();
1582        MVT::ValueType ShVT = TLI.getShiftAmountTy();
1583        unsigned len = getSizeInBits(VT);
1584        for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
1585          //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
1586          Tmp2 = DAG.getConstant(mask[i], VT);
1587          Tmp3 = DAG.getConstant(1ULL << i, ShVT);
1588          Tmp1 = DAG.getNode(ISD::ADD, VT,
1589                             DAG.getNode(ISD::AND, VT, Tmp1, Tmp2),
1590                             DAG.getNode(ISD::AND, VT,
1591                                         DAG.getNode(ISD::SRL, VT, Tmp1, Tmp3),
1592                                         Tmp2));
1593        }
1594        Result = Tmp1;
1595        break;
1596      }
1597      case ISD::CTLZ: {
1598        /* for now, we do this:
1599           x = x | (x >> 1);
1600           x = x | (x >> 2);
1601           ...
1602           x = x | (x >>16);
1603           x = x | (x >>32); // for 64-bit input
1604           return popcount(~x);
1605
1606           but see also: http://www.hackersdelight.org/HDcode/nlz.cc */
1607        MVT::ValueType VT = Tmp1.getValueType();
1608        MVT::ValueType ShVT = TLI.getShiftAmountTy();
1609        unsigned len = getSizeInBits(VT);
1610        for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
1611          Tmp3 = DAG.getConstant(1ULL << i, ShVT);
1612          Tmp1 = DAG.getNode(ISD::OR, VT, Tmp1,
1613                             DAG.getNode(ISD::SRL, VT, Tmp1, Tmp3));
1614        }
1615        Tmp3 = DAG.getNode(ISD::XOR, VT, Tmp1, DAG.getConstant(~0ULL, VT));
1616        Result = LegalizeOp(DAG.getNode(ISD::CTPOP, VT, Tmp3));
1617        break;
1618      }
1619      case ISD::CTTZ: {
1620        // for now, we use: { return popcount(~x & (x - 1)); }
1621        // unless the target has ctlz but not ctpop, in which case we use:
1622        // { return 32 - nlz(~x & (x-1)); }
1623        // see also http://www.hackersdelight.org/HDcode/ntz.cc
1624        MVT::ValueType VT = Tmp1.getValueType();
1625        Tmp2 = DAG.getConstant(~0ULL, VT);
1626        Tmp3 = DAG.getNode(ISD::AND, VT,
1627                           DAG.getNode(ISD::XOR, VT, Tmp1, Tmp2),
1628                           DAG.getNode(ISD::SUB, VT, Tmp1,
1629                                       DAG.getConstant(1, VT)));
1630        // If ISD::CTLZ is legal and CTPOP isn't, then do that instead
1631        if (TLI.getOperationAction(ISD::CTPOP, VT) != TargetLowering::Legal &&
1632            TLI.getOperationAction(ISD::CTLZ, VT) == TargetLowering::Legal) {
1633          Result = LegalizeOp(DAG.getNode(ISD::SUB, VT,
1634                                        DAG.getConstant(getSizeInBits(VT), VT),
1635                                        DAG.getNode(ISD::CTLZ, VT, Tmp3)));
1636        } else {
1637          Result = LegalizeOp(DAG.getNode(ISD::CTPOP, VT, Tmp3));
1638        }
1639        break;
1640      }
1641      default:
1642        assert(0 && "Cannot expand this yet!");
1643        break;
1644      }
1645      break;
1646    }
1647    break;
1648
1649    // Unary operators
1650  case ISD::FABS:
1651  case ISD::FNEG:
1652  case ISD::FSQRT:
1653  case ISD::FSIN:
1654  case ISD::FCOS:
1655    Tmp1 = LegalizeOp(Node->getOperand(0));
1656    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1657    case TargetLowering::Legal:
1658      if (Tmp1 != Node->getOperand(0))
1659        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1660      break;
1661    case TargetLowering::Promote:
1662    case TargetLowering::Custom:
1663      assert(0 && "Cannot promote/custom handle this yet!");
1664    case TargetLowering::Expand:
1665      switch(Node->getOpcode()) {
1666      case ISD::FNEG: {
1667        // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
1668        Tmp2 = DAG.getConstantFP(-0.0, Node->getValueType(0));
1669        Result = LegalizeOp(DAG.getNode(ISD::SUB, Node->getValueType(0),
1670                                        Tmp2, Tmp1));
1671        break;
1672      }
1673      case ISD::FABS: {
1674        // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
1675        MVT::ValueType VT = Node->getValueType(0);
1676        Tmp2 = DAG.getConstantFP(0.0, VT);
1677        Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1, Tmp2, ISD::SETUGT);
1678        Tmp3 = DAG.getNode(ISD::FNEG, VT, Tmp1);
1679        Result = DAG.getNode(ISD::SELECT, VT, Tmp2, Tmp1, Tmp3);
1680        Result = LegalizeOp(Result);
1681        break;
1682      }
1683      case ISD::FSQRT:
1684      case ISD::FSIN:
1685      case ISD::FCOS: {
1686        MVT::ValueType VT = Node->getValueType(0);
1687        const char *FnName = 0;
1688        switch(Node->getOpcode()) {
1689        case ISD::FSQRT: FnName = VT == MVT::f32 ? "sqrtf" : "sqrt"; break;
1690        case ISD::FSIN:  FnName = VT == MVT::f32 ? "sinf"  : "sin"; break;
1691        case ISD::FCOS:  FnName = VT == MVT::f32 ? "cosf"  : "cos"; break;
1692        default: assert(0 && "Unreachable!");
1693        }
1694        SDOperand Dummy;
1695        Result = ExpandLibCall(FnName, Node, Dummy);
1696        break;
1697      }
1698      default:
1699        assert(0 && "Unreachable!");
1700      }
1701      break;
1702    }
1703    break;
1704
1705    // Conversion operators.  The source and destination have different types.
1706  case ISD::SINT_TO_FP:
1707  case ISD::UINT_TO_FP: {
1708    bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
1709    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1710    case Legal:
1711      switch (TLI.getOperationAction(Node->getOpcode(),
1712                                     Node->getOperand(0).getValueType())) {
1713      default: assert(0 && "Unknown operation action!");
1714      case TargetLowering::Expand:
1715        Result = ExpandLegalINT_TO_FP(isSigned,
1716                                      LegalizeOp(Node->getOperand(0)),
1717                                      Node->getValueType(0));
1718        AddLegalizedOperand(Op, Result);
1719        return Result;
1720      case TargetLowering::Promote:
1721        Result = PromoteLegalINT_TO_FP(LegalizeOp(Node->getOperand(0)),
1722                                       Node->getValueType(0),
1723                                       isSigned);
1724        AddLegalizedOperand(Op, Result);
1725        return Result;
1726      case TargetLowering::Legal:
1727        break;
1728      }
1729
1730      Tmp1 = LegalizeOp(Node->getOperand(0));
1731      if (Tmp1 != Node->getOperand(0))
1732        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1733      break;
1734    case Expand:
1735      Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP,
1736                             Node->getValueType(0), Node->getOperand(0));
1737      break;
1738    case Promote:
1739      if (isSigned) {
1740        Result = PromoteOp(Node->getOperand(0));
1741        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1742                 Result, DAG.getValueType(Node->getOperand(0).getValueType()));
1743        Result = DAG.getNode(ISD::SINT_TO_FP, Op.getValueType(), Result);
1744      } else {
1745        Result = PromoteOp(Node->getOperand(0));
1746        Result = DAG.getZeroExtendInReg(Result,
1747                                        Node->getOperand(0).getValueType());
1748        Result = DAG.getNode(ISD::UINT_TO_FP, Op.getValueType(), Result);
1749      }
1750      break;
1751    }
1752    break;
1753  }
1754  case ISD::TRUNCATE:
1755    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1756    case Legal:
1757      Tmp1 = LegalizeOp(Node->getOperand(0));
1758      if (Tmp1 != Node->getOperand(0))
1759        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1760      break;
1761    case Expand:
1762      ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
1763
1764      // Since the result is legal, we should just be able to truncate the low
1765      // part of the source.
1766      Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
1767      break;
1768    case Promote:
1769      Result = PromoteOp(Node->getOperand(0));
1770      Result = DAG.getNode(ISD::TRUNCATE, Op.getValueType(), Result);
1771      break;
1772    }
1773    break;
1774
1775  case ISD::FP_TO_SINT:
1776  case ISD::FP_TO_UINT:
1777    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1778    case Legal:
1779      Tmp1 = LegalizeOp(Node->getOperand(0));
1780
1781      switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))){
1782      default: assert(0 && "Unknown operation action!");
1783      case TargetLowering::Expand:
1784        if (Node->getOpcode() == ISD::FP_TO_UINT) {
1785          SDOperand True, False;
1786          MVT::ValueType VT =  Node->getOperand(0).getValueType();
1787          MVT::ValueType NVT = Node->getValueType(0);
1788          unsigned ShiftAmt = MVT::getSizeInBits(Node->getValueType(0))-1;
1789          Tmp2 = DAG.getConstantFP((double)(1ULL << ShiftAmt), VT);
1790          Tmp3 = DAG.getSetCC(TLI.getSetCCResultTy(),
1791                            Node->getOperand(0), Tmp2, ISD::SETLT);
1792          True = DAG.getNode(ISD::FP_TO_SINT, NVT, Node->getOperand(0));
1793          False = DAG.getNode(ISD::FP_TO_SINT, NVT,
1794                              DAG.getNode(ISD::SUB, VT, Node->getOperand(0),
1795                                          Tmp2));
1796          False = DAG.getNode(ISD::XOR, NVT, False,
1797                              DAG.getConstant(1ULL << ShiftAmt, NVT));
1798          Result = LegalizeOp(DAG.getNode(ISD::SELECT, NVT, Tmp3, True, False));
1799          return Result;
1800        } else {
1801          assert(0 && "Do not know how to expand FP_TO_SINT yet!");
1802        }
1803        break;
1804      case TargetLowering::Promote:
1805        Result = PromoteLegalFP_TO_INT(Tmp1, Node->getValueType(0),
1806                                       Node->getOpcode() == ISD::FP_TO_SINT);
1807        AddLegalizedOperand(Op, Result);
1808        return Result;
1809      case TargetLowering::Legal:
1810        break;
1811      case TargetLowering::Custom:
1812        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1813        Result = TLI.LowerOperation(Result, DAG);
1814        AddLegalizedOperand(Op, Result);
1815        NeedsAnotherIteration = true;
1816        return Result;
1817      }
1818
1819      if (Tmp1 != Node->getOperand(0))
1820        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1821      break;
1822    case Expand:
1823      assert(0 && "Shouldn't need to expand other operators here!");
1824    case Promote:
1825      Result = PromoteOp(Node->getOperand(0));
1826      Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
1827      break;
1828    }
1829    break;
1830
1831  case ISD::ZERO_EXTEND:
1832  case ISD::SIGN_EXTEND:
1833  case ISD::FP_EXTEND:
1834  case ISD::FP_ROUND:
1835    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1836    case Legal:
1837      Tmp1 = LegalizeOp(Node->getOperand(0));
1838      if (Tmp1 != Node->getOperand(0))
1839        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1840      break;
1841    case Expand:
1842      assert(0 && "Shouldn't need to expand other operators here!");
1843
1844    case Promote:
1845      switch (Node->getOpcode()) {
1846      case ISD::ZERO_EXTEND:
1847        Result = PromoteOp(Node->getOperand(0));
1848        // NOTE: Any extend would work here...
1849        Result = DAG.getNode(ISD::ZERO_EXTEND, Op.getValueType(), Result);
1850        Result = DAG.getZeroExtendInReg(Result,
1851                                        Node->getOperand(0).getValueType());
1852        break;
1853      case ISD::SIGN_EXTEND:
1854        Result = PromoteOp(Node->getOperand(0));
1855        // NOTE: Any extend would work here...
1856        Result = DAG.getNode(ISD::ZERO_EXTEND, Op.getValueType(), Result);
1857        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1858                             Result,
1859                          DAG.getValueType(Node->getOperand(0).getValueType()));
1860        break;
1861      case ISD::FP_EXTEND:
1862        Result = PromoteOp(Node->getOperand(0));
1863        if (Result.getValueType() != Op.getValueType())
1864          // Dynamically dead while we have only 2 FP types.
1865          Result = DAG.getNode(ISD::FP_EXTEND, Op.getValueType(), Result);
1866        break;
1867      case ISD::FP_ROUND:
1868        Result = PromoteOp(Node->getOperand(0));
1869        Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
1870        break;
1871      }
1872    }
1873    break;
1874  case ISD::FP_ROUND_INREG:
1875  case ISD::SIGN_EXTEND_INREG: {
1876    Tmp1 = LegalizeOp(Node->getOperand(0));
1877    MVT::ValueType ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
1878
1879    // If this operation is not supported, convert it to a shl/shr or load/store
1880    // pair.
1881    switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
1882    default: assert(0 && "This action not supported for this op yet!");
1883    case TargetLowering::Legal:
1884      if (Tmp1 != Node->getOperand(0))
1885        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
1886                             DAG.getValueType(ExtraVT));
1887      break;
1888    case TargetLowering::Expand:
1889      // If this is an integer extend and shifts are supported, do that.
1890      if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
1891        // NOTE: we could fall back on load/store here too for targets without
1892        // SAR.  However, it is doubtful that any exist.
1893        unsigned BitsDiff = MVT::getSizeInBits(Node->getValueType(0)) -
1894                            MVT::getSizeInBits(ExtraVT);
1895        SDOperand ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
1896        Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
1897                             Node->getOperand(0), ShiftCst);
1898        Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
1899                             Result, ShiftCst);
1900      } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
1901        // The only way we can lower this is to turn it into a STORETRUNC,
1902        // EXTLOAD pair, targetting a temporary location (a stack slot).
1903
1904        // NOTE: there is a choice here between constantly creating new stack
1905        // slots and always reusing the same one.  We currently always create
1906        // new ones, as reuse may inhibit scheduling.
1907        const Type *Ty = MVT::getTypeForValueType(ExtraVT);
1908        unsigned TySize = (unsigned)TLI.getTargetData().getTypeSize(Ty);
1909        unsigned Align  = TLI.getTargetData().getTypeAlignment(Ty);
1910        MachineFunction &MF = DAG.getMachineFunction();
1911        int SSFI =
1912          MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
1913        SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
1914        Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, DAG.getEntryNode(),
1915                             Node->getOperand(0), StackSlot,
1916                             DAG.getSrcValue(NULL), DAG.getValueType(ExtraVT));
1917        Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
1918                                Result, StackSlot, DAG.getSrcValue(NULL),
1919                                ExtraVT);
1920      } else {
1921        assert(0 && "Unknown op");
1922      }
1923      Result = LegalizeOp(Result);
1924      break;
1925    }
1926    break;
1927  }
1928  }
1929
1930  // Note that LegalizeOp may be reentered even from single-use nodes, which
1931  // means that we always must cache transformed nodes.
1932  AddLegalizedOperand(Op, Result);
1933  return Result;
1934}
1935
1936/// PromoteOp - Given an operation that produces a value in an invalid type,
1937/// promote it to compute the value into a larger type.  The produced value will
1938/// have the correct bits for the low portion of the register, but no guarantee
1939/// is made about the top bits: it may be zero, sign-extended, or garbage.
1940SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
1941  MVT::ValueType VT = Op.getValueType();
1942  MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
1943  assert(getTypeAction(VT) == Promote &&
1944         "Caller should expand or legalize operands that are not promotable!");
1945  assert(NVT > VT && MVT::isInteger(NVT) == MVT::isInteger(VT) &&
1946         "Cannot promote to smaller type!");
1947
1948  SDOperand Tmp1, Tmp2, Tmp3;
1949
1950  SDOperand Result;
1951  SDNode *Node = Op.Val;
1952
1953  if (!Node->hasOneUse()) {
1954    std::map<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
1955    if (I != PromotedNodes.end()) return I->second;
1956  } else {
1957    assert(!PromotedNodes.count(Op) && "Repromoted this node??");
1958  }
1959
1960  // Promotion needs an optimization step to clean up after it, and is not
1961  // careful to avoid operations the target does not support.  Make sure that
1962  // all generated operations are legalized in the next iteration.
1963  NeedsAnotherIteration = true;
1964
1965  switch (Node->getOpcode()) {
1966  case ISD::CopyFromReg:
1967    assert(0 && "CopyFromReg must be legal!");
1968  default:
1969    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
1970    assert(0 && "Do not know how to promote this operator!");
1971    abort();
1972  case ISD::UNDEF:
1973    Result = DAG.getNode(ISD::UNDEF, NVT);
1974    break;
1975  case ISD::Constant:
1976    Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
1977    assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
1978    break;
1979  case ISD::ConstantFP:
1980    Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
1981    assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
1982    break;
1983
1984  case ISD::SETCC:
1985    assert(getTypeAction(TLI.getSetCCResultTy()) == Legal &&
1986           "SetCC type is not legal??");
1987    Result = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),Node->getOperand(0),
1988                         Node->getOperand(1), Node->getOperand(2));
1989    Result = LegalizeOp(Result);
1990    break;
1991
1992  case ISD::TRUNCATE:
1993    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1994    case Legal:
1995      Result = LegalizeOp(Node->getOperand(0));
1996      assert(Result.getValueType() >= NVT &&
1997             "This truncation doesn't make sense!");
1998      if (Result.getValueType() > NVT)    // Truncate to NVT instead of VT
1999        Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
2000      break;
2001    case Promote:
2002      // The truncation is not required, because we don't guarantee anything
2003      // about high bits anyway.
2004      Result = PromoteOp(Node->getOperand(0));
2005      break;
2006    case Expand:
2007      ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
2008      // Truncate the low part of the expanded value to the result type
2009      Result = DAG.getNode(ISD::TRUNCATE, NVT, Tmp1);
2010    }
2011    break;
2012  case ISD::SIGN_EXTEND:
2013  case ISD::ZERO_EXTEND:
2014    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2015    case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
2016    case Legal:
2017      // Input is legal?  Just do extend all the way to the larger type.
2018      Result = LegalizeOp(Node->getOperand(0));
2019      Result = DAG.getNode(Node->getOpcode(), NVT, Result);
2020      break;
2021    case Promote:
2022      // Promote the reg if it's smaller.
2023      Result = PromoteOp(Node->getOperand(0));
2024      // The high bits are not guaranteed to be anything.  Insert an extend.
2025      if (Node->getOpcode() == ISD::SIGN_EXTEND)
2026        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
2027                         DAG.getValueType(Node->getOperand(0).getValueType()));
2028      else
2029        Result = DAG.getZeroExtendInReg(Result,
2030                                        Node->getOperand(0).getValueType());
2031      break;
2032    }
2033    break;
2034
2035  case ISD::FP_EXTEND:
2036    assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
2037  case ISD::FP_ROUND:
2038    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2039    case Expand: assert(0 && "BUG: Cannot expand FP regs!");
2040    case Promote:  assert(0 && "Unreachable with 2 FP types!");
2041    case Legal:
2042      // Input is legal?  Do an FP_ROUND_INREG.
2043      Result = LegalizeOp(Node->getOperand(0));
2044      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2045                           DAG.getValueType(VT));
2046      break;
2047    }
2048    break;
2049
2050  case ISD::SINT_TO_FP:
2051  case ISD::UINT_TO_FP:
2052    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2053    case Legal:
2054      Result = LegalizeOp(Node->getOperand(0));
2055      // No extra round required here.
2056      Result = DAG.getNode(Node->getOpcode(), NVT, Result);
2057      break;
2058
2059    case Promote:
2060      Result = PromoteOp(Node->getOperand(0));
2061      if (Node->getOpcode() == ISD::SINT_TO_FP)
2062        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2063                             Result,
2064                         DAG.getValueType(Node->getOperand(0).getValueType()));
2065      else
2066        Result = DAG.getZeroExtendInReg(Result,
2067                                        Node->getOperand(0).getValueType());
2068      // No extra round required here.
2069      Result = DAG.getNode(Node->getOpcode(), NVT, Result);
2070      break;
2071    case Expand:
2072      Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, NVT,
2073                             Node->getOperand(0));
2074      // Round if we cannot tolerate excess precision.
2075      if (NoExcessFPPrecision)
2076        Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2077                             DAG.getValueType(VT));
2078      break;
2079    }
2080    break;
2081
2082  case ISD::FP_TO_SINT:
2083  case ISD::FP_TO_UINT:
2084    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2085    case Legal:
2086      Tmp1 = LegalizeOp(Node->getOperand(0));
2087      break;
2088    case Promote:
2089      // The input result is prerounded, so we don't have to do anything
2090      // special.
2091      Tmp1 = PromoteOp(Node->getOperand(0));
2092      break;
2093    case Expand:
2094      assert(0 && "not implemented");
2095    }
2096    // If we're promoting a UINT to a larger size, check to see if the new node
2097    // will be legal.  If it isn't, check to see if FP_TO_SINT is legal, since
2098    // we can use that instead.  This allows us to generate better code for
2099    // FP_TO_UINT for small destination sizes on targets where FP_TO_UINT is not
2100    // legal, such as PowerPC.
2101    if (Node->getOpcode() == ISD::FP_TO_UINT &&
2102        TargetLowering::Legal != TLI.getOperationAction(ISD::FP_TO_UINT, NVT) &&
2103        TargetLowering::Legal == TLI.getOperationAction(ISD::FP_TO_SINT, NVT)) {
2104      Result = DAG.getNode(ISD::FP_TO_SINT, NVT, Tmp1);
2105    } else {
2106      Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2107    }
2108    break;
2109
2110  case ISD::FABS:
2111  case ISD::FNEG:
2112    Tmp1 = PromoteOp(Node->getOperand(0));
2113    assert(Tmp1.getValueType() == NVT);
2114    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2115    // NOTE: we do not have to do any extra rounding here for
2116    // NoExcessFPPrecision, because we know the input will have the appropriate
2117    // precision, and these operations don't modify precision at all.
2118    break;
2119
2120  case ISD::FSQRT:
2121  case ISD::FSIN:
2122  case ISD::FCOS:
2123    Tmp1 = PromoteOp(Node->getOperand(0));
2124    assert(Tmp1.getValueType() == NVT);
2125    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2126    if(NoExcessFPPrecision)
2127      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2128                           DAG.getValueType(VT));
2129    break;
2130
2131  case ISD::AND:
2132  case ISD::OR:
2133  case ISD::XOR:
2134  case ISD::ADD:
2135  case ISD::SUB:
2136  case ISD::MUL:
2137    // The input may have strange things in the top bits of the registers, but
2138    // these operations don't care.  They may have wierd bits going out, but
2139    // that too is okay if they are integer operations.
2140    Tmp1 = PromoteOp(Node->getOperand(0));
2141    Tmp2 = PromoteOp(Node->getOperand(1));
2142    assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
2143    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2144
2145    // However, if this is a floating point operation, they will give excess
2146    // precision that we may not be able to tolerate.  If we DO allow excess
2147    // precision, just leave it, otherwise excise it.
2148    // FIXME: Why would we need to round FP ops more than integer ones?
2149    //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
2150    if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
2151      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2152                           DAG.getValueType(VT));
2153    break;
2154
2155  case ISD::SDIV:
2156  case ISD::SREM:
2157    // These operators require that their input be sign extended.
2158    Tmp1 = PromoteOp(Node->getOperand(0));
2159    Tmp2 = PromoteOp(Node->getOperand(1));
2160    if (MVT::isInteger(NVT)) {
2161      Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
2162                         DAG.getValueType(VT));
2163      Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
2164                         DAG.getValueType(VT));
2165    }
2166    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2167
2168    // Perform FP_ROUND: this is probably overly pessimistic.
2169    if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
2170      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2171                           DAG.getValueType(VT));
2172    break;
2173
2174  case ISD::UDIV:
2175  case ISD::UREM:
2176    // These operators require that their input be zero extended.
2177    Tmp1 = PromoteOp(Node->getOperand(0));
2178    Tmp2 = PromoteOp(Node->getOperand(1));
2179    assert(MVT::isInteger(NVT) && "Operators don't apply to FP!");
2180    Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
2181    Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
2182    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2183    break;
2184
2185  case ISD::SHL:
2186    Tmp1 = PromoteOp(Node->getOperand(0));
2187    Tmp2 = LegalizeOp(Node->getOperand(1));
2188    Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Tmp2);
2189    break;
2190  case ISD::SRA:
2191    // The input value must be properly sign extended.
2192    Tmp1 = PromoteOp(Node->getOperand(0));
2193    Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
2194                       DAG.getValueType(VT));
2195    Tmp2 = LegalizeOp(Node->getOperand(1));
2196    Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Tmp2);
2197    break;
2198  case ISD::SRL:
2199    // The input value must be properly zero extended.
2200    Tmp1 = PromoteOp(Node->getOperand(0));
2201    Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
2202    Tmp2 = LegalizeOp(Node->getOperand(1));
2203    Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Tmp2);
2204    break;
2205  case ISD::LOAD:
2206    Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
2207    Tmp2 = LegalizeOp(Node->getOperand(1));   // Legalize the pointer.
2208    // FIXME: When the DAG combiner exists, change this to use EXTLOAD!
2209    if (MVT::isInteger(NVT))
2210      Result = DAG.getExtLoad(ISD::ZEXTLOAD, NVT, Tmp1, Tmp2,
2211                              Node->getOperand(2), VT);
2212    else
2213      Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Tmp1, Tmp2,
2214                              Node->getOperand(2), VT);
2215
2216    // Remember that we legalized the chain.
2217    AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
2218    break;
2219  case ISD::SELECT:
2220    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2221    case Expand: assert(0 && "It's impossible to expand bools");
2222    case Legal:
2223      Tmp1 = LegalizeOp(Node->getOperand(0));// Legalize the condition.
2224      break;
2225    case Promote:
2226      Tmp1 = PromoteOp(Node->getOperand(0)); // Promote the condition.
2227      break;
2228    }
2229    Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
2230    Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
2231    Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2, Tmp3);
2232    break;
2233  case ISD::SELECT_CC:
2234    Tmp2 = PromoteOp(Node->getOperand(2));   // True
2235    Tmp3 = PromoteOp(Node->getOperand(3));   // False
2236    Result = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
2237                         Node->getOperand(1), Tmp2, Tmp3,
2238                         Node->getOperand(4));
2239    break;
2240  case ISD::TAILCALL:
2241  case ISD::CALL: {
2242    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2243    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
2244
2245    std::vector<SDOperand> Ops;
2246    for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i)
2247      Ops.push_back(LegalizeOp(Node->getOperand(i)));
2248
2249    assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
2250           "Can only promote single result calls");
2251    std::vector<MVT::ValueType> RetTyVTs;
2252    RetTyVTs.reserve(2);
2253    RetTyVTs.push_back(NVT);
2254    RetTyVTs.push_back(MVT::Other);
2255    SDNode *NC = DAG.getCall(RetTyVTs, Tmp1, Tmp2, Ops,
2256                             Node->getOpcode() == ISD::TAILCALL);
2257    Result = SDOperand(NC, 0);
2258
2259    // Insert the new chain mapping.
2260    AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
2261    break;
2262  }
2263  case ISD::CTPOP:
2264  case ISD::CTTZ:
2265  case ISD::CTLZ:
2266    Tmp1 = Node->getOperand(0);
2267    //Zero extend the argument
2268    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
2269    // Perform the larger operation, then subtract if needed.
2270    Tmp1 = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2271    switch(Node->getOpcode())
2272    {
2273    case ISD::CTPOP:
2274      Result = Tmp1;
2275      break;
2276    case ISD::CTTZ:
2277      //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
2278      Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
2279                          DAG.getConstant(getSizeInBits(NVT), NVT), ISD::SETEQ);
2280      Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
2281                           DAG.getConstant(getSizeInBits(VT),NVT), Tmp1);
2282      break;
2283    case ISD::CTLZ:
2284      //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
2285      Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
2286                           DAG.getConstant(getSizeInBits(NVT) -
2287                                           getSizeInBits(VT), NVT));
2288      break;
2289    }
2290    break;
2291  }
2292
2293  assert(Result.Val && "Didn't set a result!");
2294  AddPromotedOperand(Op, Result);
2295  return Result;
2296}
2297
2298/// ExpandAddSub - Find a clever way to expand this add operation into
2299/// subcomponents.
2300void SelectionDAGLegalize::
2301ExpandByParts(unsigned NodeOp, SDOperand LHS, SDOperand RHS,
2302              SDOperand &Lo, SDOperand &Hi) {
2303  // Expand the subcomponents.
2304  SDOperand LHSL, LHSH, RHSL, RHSH;
2305  ExpandOp(LHS, LHSL, LHSH);
2306  ExpandOp(RHS, RHSL, RHSH);
2307
2308  // FIXME: this should be moved to the dag combiner someday.
2309  assert(NodeOp == ISD::ADD_PARTS || NodeOp == ISD::SUB_PARTS);
2310  if (LHSL.getValueType() == MVT::i32) {
2311    SDOperand LowEl;
2312    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHSL))
2313      if (C->getValue() == 0)
2314        LowEl = RHSL;
2315    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHSL))
2316      if (C->getValue() == 0)
2317        LowEl = LHSL;
2318    if (LowEl.Val) {
2319      // Turn this into an add/sub of the high part only.
2320      SDOperand HiEl =
2321        DAG.getNode(NodeOp == ISD::ADD_PARTS ? ISD::ADD : ISD::SUB,
2322                    LowEl.getValueType(), LHSH, RHSH);
2323      Lo = LowEl;
2324      Hi = HiEl;
2325      return;
2326    }
2327  }
2328
2329  std::vector<SDOperand> Ops;
2330  Ops.push_back(LHSL);
2331  Ops.push_back(LHSH);
2332  Ops.push_back(RHSL);
2333  Ops.push_back(RHSH);
2334
2335  std::vector<MVT::ValueType> VTs(2, LHSL.getValueType());
2336  Lo = DAG.getNode(NodeOp, VTs, Ops);
2337  Hi = Lo.getValue(1);
2338}
2339
2340void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
2341                                            SDOperand Op, SDOperand Amt,
2342                                            SDOperand &Lo, SDOperand &Hi) {
2343  // Expand the subcomponents.
2344  SDOperand LHSL, LHSH;
2345  ExpandOp(Op, LHSL, LHSH);
2346
2347  std::vector<SDOperand> Ops;
2348  Ops.push_back(LHSL);
2349  Ops.push_back(LHSH);
2350  Ops.push_back(Amt);
2351  std::vector<MVT::ValueType> VTs;
2352  VTs.push_back(LHSL.getValueType());
2353  VTs.push_back(LHSH.getValueType());
2354  VTs.push_back(Amt.getValueType());
2355  Lo = DAG.getNode(NodeOp, VTs, Ops);
2356  Hi = Lo.getValue(1);
2357}
2358
2359
2360/// ExpandShift - Try to find a clever way to expand this shift operation out to
2361/// smaller elements.  If we can't find a way that is more efficient than a
2362/// libcall on this target, return false.  Otherwise, return true with the
2363/// low-parts expanded into Lo and Hi.
2364bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDOperand Op,SDOperand Amt,
2365                                       SDOperand &Lo, SDOperand &Hi) {
2366  assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
2367         "This is not a shift!");
2368
2369  MVT::ValueType NVT = TLI.getTypeToTransformTo(Op.getValueType());
2370  SDOperand ShAmt = LegalizeOp(Amt);
2371  MVT::ValueType ShTy = ShAmt.getValueType();
2372  unsigned VTBits = MVT::getSizeInBits(Op.getValueType());
2373  unsigned NVTBits = MVT::getSizeInBits(NVT);
2374
2375  // Handle the case when Amt is an immediate.  Other cases are currently broken
2376  // and are disabled.
2377  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Amt.Val)) {
2378    unsigned Cst = CN->getValue();
2379    // Expand the incoming operand to be shifted, so that we have its parts
2380    SDOperand InL, InH;
2381    ExpandOp(Op, InL, InH);
2382    switch(Opc) {
2383    case ISD::SHL:
2384      if (Cst > VTBits) {
2385        Lo = DAG.getConstant(0, NVT);
2386        Hi = DAG.getConstant(0, NVT);
2387      } else if (Cst > NVTBits) {
2388        Lo = DAG.getConstant(0, NVT);
2389        Hi = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst-NVTBits,ShTy));
2390      } else if (Cst == NVTBits) {
2391        Lo = DAG.getConstant(0, NVT);
2392        Hi = InL;
2393      } else {
2394        Lo = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst, ShTy));
2395        Hi = DAG.getNode(ISD::OR, NVT,
2396           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(Cst, ShTy)),
2397           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(NVTBits-Cst, ShTy)));
2398      }
2399      return true;
2400    case ISD::SRL:
2401      if (Cst > VTBits) {
2402        Lo = DAG.getConstant(0, NVT);
2403        Hi = DAG.getConstant(0, NVT);
2404      } else if (Cst > NVTBits) {
2405        Lo = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst-NVTBits,ShTy));
2406        Hi = DAG.getConstant(0, NVT);
2407      } else if (Cst == NVTBits) {
2408        Lo = InH;
2409        Hi = DAG.getConstant(0, NVT);
2410      } else {
2411        Lo = DAG.getNode(ISD::OR, NVT,
2412           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
2413           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
2414        Hi = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst, ShTy));
2415      }
2416      return true;
2417    case ISD::SRA:
2418      if (Cst > VTBits) {
2419        Hi = Lo = DAG.getNode(ISD::SRA, NVT, InH,
2420                              DAG.getConstant(NVTBits-1, ShTy));
2421      } else if (Cst > NVTBits) {
2422        Lo = DAG.getNode(ISD::SRA, NVT, InH,
2423                           DAG.getConstant(Cst-NVTBits, ShTy));
2424        Hi = DAG.getNode(ISD::SRA, NVT, InH,
2425                              DAG.getConstant(NVTBits-1, ShTy));
2426      } else if (Cst == NVTBits) {
2427        Lo = InH;
2428        Hi = DAG.getNode(ISD::SRA, NVT, InH,
2429                              DAG.getConstant(NVTBits-1, ShTy));
2430      } else {
2431        Lo = DAG.getNode(ISD::OR, NVT,
2432           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
2433           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
2434        Hi = DAG.getNode(ISD::SRA, NVT, InH, DAG.getConstant(Cst, ShTy));
2435      }
2436      return true;
2437    }
2438  }
2439  // FIXME: The following code for expanding shifts using ISD::SELECT is buggy,
2440  // so disable it for now.  Currently targets are handling this via SHL_PARTS
2441  // and friends.
2442  return false;
2443
2444  // If we have an efficient select operation (or if the selects will all fold
2445  // away), lower to some complex code, otherwise just emit the libcall.
2446  if (TLI.getOperationAction(ISD::SELECT, NVT) != TargetLowering::Legal &&
2447      !isa<ConstantSDNode>(Amt))
2448    return false;
2449
2450  SDOperand InL, InH;
2451  ExpandOp(Op, InL, InH);
2452  SDOperand NAmt = DAG.getNode(ISD::SUB, ShTy,           // NAmt = 32-ShAmt
2453                               DAG.getConstant(NVTBits, ShTy), ShAmt);
2454
2455  // Compare the unmasked shift amount against 32.
2456  SDOperand Cond = DAG.getSetCC(TLI.getSetCCResultTy(), ShAmt,
2457                                DAG.getConstant(NVTBits, ShTy), ISD::SETGE);
2458
2459  if (TLI.getShiftAmountFlavor() != TargetLowering::Mask) {
2460    ShAmt = DAG.getNode(ISD::AND, ShTy, ShAmt,             // ShAmt &= 31
2461                        DAG.getConstant(NVTBits-1, ShTy));
2462    NAmt  = DAG.getNode(ISD::AND, ShTy, NAmt,              // NAmt &= 31
2463                        DAG.getConstant(NVTBits-1, ShTy));
2464  }
2465
2466  if (Opc == ISD::SHL) {
2467    SDOperand T1 = DAG.getNode(ISD::OR, NVT,// T1 = (Hi << Amt) | (Lo >> NAmt)
2468                               DAG.getNode(ISD::SHL, NVT, InH, ShAmt),
2469                               DAG.getNode(ISD::SRL, NVT, InL, NAmt));
2470    SDOperand T2 = DAG.getNode(ISD::SHL, NVT, InL, ShAmt); // T2 = Lo << Amt&31
2471
2472    Hi = DAG.getNode(ISD::SELECT, NVT, Cond, T2, T1);
2473    Lo = DAG.getNode(ISD::SELECT, NVT, Cond, DAG.getConstant(0, NVT), T2);
2474  } else {
2475    SDOperand HiLoPart = DAG.getNode(ISD::SELECT, NVT,
2476                                     DAG.getSetCC(TLI.getSetCCResultTy(), NAmt,
2477                                                  DAG.getConstant(32, ShTy),
2478                                                  ISD::SETEQ),
2479                                     DAG.getConstant(0, NVT),
2480                                     DAG.getNode(ISD::SHL, NVT, InH, NAmt));
2481    SDOperand T1 = DAG.getNode(ISD::OR, NVT,// T1 = (Hi << NAmt) | (Lo >> Amt)
2482                               HiLoPart,
2483                               DAG.getNode(ISD::SRL, NVT, InL, ShAmt));
2484    SDOperand T2 = DAG.getNode(Opc, NVT, InH, ShAmt);  // T2 = InH >> ShAmt&31
2485
2486    SDOperand HiPart;
2487    if (Opc == ISD::SRA)
2488      HiPart = DAG.getNode(ISD::SRA, NVT, InH,
2489                           DAG.getConstant(NVTBits-1, ShTy));
2490    else
2491      HiPart = DAG.getConstant(0, NVT);
2492    Lo = DAG.getNode(ISD::SELECT, NVT, Cond, T2, T1);
2493    Hi = DAG.getNode(ISD::SELECT, NVT, Cond, HiPart, T2);
2494  }
2495  return true;
2496}
2497
2498/// FindLatestCallSeqStart - Scan up the dag to find the latest (highest
2499/// NodeDepth) node that is an CallSeqStart operation and occurs later than
2500/// Found.
2501static void FindLatestCallSeqStart(SDNode *Node, SDNode *&Found) {
2502  if (Node->getNodeDepth() <= Found->getNodeDepth()) return;
2503
2504  // If we found an CALLSEQ_START, we already know this node occurs later
2505  // than the Found node. Just remember this node and return.
2506  if (Node->getOpcode() == ISD::CALLSEQ_START) {
2507    Found = Node;
2508    return;
2509  }
2510
2511  // Otherwise, scan the operands of Node to see if any of them is a call.
2512  assert(Node->getNumOperands() != 0 &&
2513         "All leaves should have depth equal to the entry node!");
2514  for (unsigned i = 0, e = Node->getNumOperands()-1; i != e; ++i)
2515    FindLatestCallSeqStart(Node->getOperand(i).Val, Found);
2516
2517  // Tail recurse for the last iteration.
2518  FindLatestCallSeqStart(Node->getOperand(Node->getNumOperands()-1).Val,
2519                             Found);
2520}
2521
2522
2523/// FindEarliestCallSeqEnd - Scan down the dag to find the earliest (lowest
2524/// NodeDepth) node that is an CallSeqEnd operation and occurs more recent
2525/// than Found.
2526static void FindEarliestCallSeqEnd(SDNode *Node, SDNode *&Found,
2527                                   std::set<SDNode*> &Visited) {
2528  if ((Found && Node->getNodeDepth() >= Found->getNodeDepth()) ||
2529      !Visited.insert(Node).second) return;
2530
2531  // If we found an CALLSEQ_END, we already know this node occurs earlier
2532  // than the Found node. Just remember this node and return.
2533  if (Node->getOpcode() == ISD::CALLSEQ_END) {
2534    Found = Node;
2535    return;
2536  }
2537
2538  // Otherwise, scan the operands of Node to see if any of them is a call.
2539  SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
2540  if (UI == E) return;
2541  for (--E; UI != E; ++UI)
2542    FindEarliestCallSeqEnd(*UI, Found, Visited);
2543
2544  // Tail recurse for the last iteration.
2545  FindEarliestCallSeqEnd(*UI, Found, Visited);
2546}
2547
2548/// FindCallSeqEnd - Given a chained node that is part of a call sequence,
2549/// find the CALLSEQ_END node that terminates the call sequence.
2550static SDNode *FindCallSeqEnd(SDNode *Node) {
2551  if (Node->getOpcode() == ISD::CALLSEQ_END)
2552    return Node;
2553  if (Node->use_empty())
2554    return 0;   // No CallSeqEnd
2555
2556  if (Node->hasOneUse())  // Simple case, only has one user to check.
2557    return FindCallSeqEnd(*Node->use_begin());
2558
2559  SDOperand TheChain(Node, Node->getNumValues()-1);
2560  if (TheChain.getValueType() != MVT::Other)
2561    TheChain = SDOperand(Node, 0);
2562  assert(TheChain.getValueType() == MVT::Other && "Is not a token chain!");
2563
2564  for (SDNode::use_iterator UI = Node->use_begin(),
2565         E = Node->use_end(); UI != E; ++UI) {
2566
2567    // Make sure to only follow users of our token chain.
2568    SDNode *User = *UI;
2569    for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
2570      if (User->getOperand(i) == TheChain)
2571        if (SDNode *Result = FindCallSeqEnd(User))
2572          return Result;
2573  }
2574  return 0;
2575}
2576
2577/// FindCallSeqStart - Given a chained node that is part of a call sequence,
2578/// find the CALLSEQ_START node that initiates the call sequence.
2579static SDNode *FindCallSeqStart(SDNode *Node) {
2580  assert(Node && "Didn't find callseq_start for a call??");
2581  if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
2582
2583  assert(Node->getOperand(0).getValueType() == MVT::Other &&
2584         "Node doesn't have a token chain argument!");
2585  return FindCallSeqStart(Node->getOperand(0).Val);
2586}
2587
2588
2589/// FindInputOutputChains - If we are replacing an operation with a call we need
2590/// to find the call that occurs before and the call that occurs after it to
2591/// properly serialize the calls in the block.  The returned operand is the
2592/// input chain value for the new call (e.g. the entry node or the previous
2593/// call), and OutChain is set to be the chain node to update to point to the
2594/// end of the call chain.
2595static SDOperand FindInputOutputChains(SDNode *OpNode, SDNode *&OutChain,
2596                                       SDOperand Entry) {
2597  SDNode *LatestCallSeqStart = Entry.Val;
2598  SDNode *LatestCallSeqEnd = 0;
2599  FindLatestCallSeqStart(OpNode, LatestCallSeqStart);
2600  //std::cerr<<"Found node: "; LatestCallSeqStart->dump(); std::cerr <<"\n";
2601
2602  // It is possible that no ISD::CALLSEQ_START was found because there is no
2603  // previous call in the function.  LatestCallStackDown may in that case be
2604  // the entry node itself.  Do not attempt to find a matching CALLSEQ_END
2605  // unless LatestCallStackDown is an CALLSEQ_START.
2606  if (LatestCallSeqStart->getOpcode() == ISD::CALLSEQ_START)
2607    LatestCallSeqEnd = FindCallSeqEnd(LatestCallSeqStart);
2608  else
2609    LatestCallSeqEnd = Entry.Val;
2610  assert(LatestCallSeqEnd && "NULL return from FindCallSeqEnd");
2611
2612  // Finally, find the first call that this must come before, first we find the
2613  // CallSeqEnd that ends the call.
2614  OutChain = 0;
2615  std::set<SDNode*> Visited;
2616  FindEarliestCallSeqEnd(OpNode, OutChain, Visited);
2617
2618  // If we found one, translate from the adj up to the callseq_start.
2619  if (OutChain)
2620    OutChain = FindCallSeqStart(OutChain);
2621
2622  return SDOperand(LatestCallSeqEnd, 0);
2623}
2624
2625/// SpliceCallInto - Given the result chain of a libcall (CallResult), and a
2626void SelectionDAGLegalize::SpliceCallInto(const SDOperand &CallResult,
2627                                          SDNode *OutChain) {
2628  // Nothing to splice it into?
2629  if (OutChain == 0) return;
2630
2631  assert(OutChain->getOperand(0).getValueType() == MVT::Other);
2632  //OutChain->dump();
2633
2634  // Form a token factor node merging the old inval and the new inval.
2635  SDOperand InToken = DAG.getNode(ISD::TokenFactor, MVT::Other, CallResult,
2636                                  OutChain->getOperand(0));
2637  // Change the node to refer to the new token.
2638  OutChain->setAdjCallChain(InToken);
2639}
2640
2641
2642// ExpandLibCall - Expand a node into a call to a libcall.  If the result value
2643// does not fit into a register, return the lo part and set the hi part to the
2644// by-reg argument.  If it does fit into a single register, return the result
2645// and leave the Hi part unset.
2646SDOperand SelectionDAGLegalize::ExpandLibCall(const char *Name, SDNode *Node,
2647                                              SDOperand &Hi) {
2648  SDNode *OutChain;
2649  SDOperand InChain = FindInputOutputChains(Node, OutChain,
2650                                            DAG.getEntryNode());
2651  if (InChain.Val == 0)
2652    InChain = DAG.getEntryNode();
2653
2654  TargetLowering::ArgListTy Args;
2655  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
2656    MVT::ValueType ArgVT = Node->getOperand(i).getValueType();
2657    const Type *ArgTy = MVT::getTypeForValueType(ArgVT);
2658    Args.push_back(std::make_pair(Node->getOperand(i), ArgTy));
2659  }
2660  SDOperand Callee = DAG.getExternalSymbol(Name, TLI.getPointerTy());
2661
2662  // Splice the libcall in wherever FindInputOutputChains tells us to.
2663  const Type *RetTy = MVT::getTypeForValueType(Node->getValueType(0));
2664  std::pair<SDOperand,SDOperand> CallInfo =
2665    TLI.LowerCallTo(InChain, RetTy, false, CallingConv::C, false,
2666                    Callee, Args, DAG);
2667  SpliceCallInto(CallInfo.second, OutChain);
2668
2669  NeedsAnotherIteration = true;
2670
2671  switch (getTypeAction(CallInfo.first.getValueType())) {
2672  default: assert(0 && "Unknown thing");
2673  case Legal:
2674    return CallInfo.first;
2675  case Promote:
2676    assert(0 && "Cannot promote this yet!");
2677  case Expand:
2678    SDOperand Lo;
2679    ExpandOp(CallInfo.first, Lo, Hi);
2680    return Lo;
2681  }
2682}
2683
2684
2685/// ExpandIntToFP - Expand a [US]INT_TO_FP operation, assuming that the
2686/// destination type is legal.
2687SDOperand SelectionDAGLegalize::
2688ExpandIntToFP(bool isSigned, MVT::ValueType DestTy, SDOperand Source) {
2689  assert(getTypeAction(DestTy) == Legal && "Destination type is not legal!");
2690  assert(getTypeAction(Source.getValueType()) == Expand &&
2691         "This is not an expansion!");
2692  assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
2693
2694  if (!isSigned) {
2695    assert(Source.getValueType() == MVT::i64 &&
2696           "This only works for 64-bit -> FP");
2697    // The 64-bit value loaded will be incorrectly if the 'sign bit' of the
2698    // incoming integer is set.  To handle this, we dynamically test to see if
2699    // it is set, and, if so, add a fudge factor.
2700    SDOperand Lo, Hi;
2701    ExpandOp(Source, Lo, Hi);
2702
2703    // If this is unsigned, and not supported, first perform the conversion to
2704    // signed, then adjust the result if the sign bit is set.
2705    SDOperand SignedConv = ExpandIntToFP(true, DestTy,
2706                   DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), Lo, Hi));
2707
2708    SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Hi,
2709                                     DAG.getConstant(0, Hi.getValueType()),
2710                                     ISD::SETLT);
2711    SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
2712    SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
2713                                      SignSet, Four, Zero);
2714    uint64_t FF = 0x5f800000ULL;
2715    if (TLI.isLittleEndian()) FF <<= 32;
2716    static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
2717
2718    MachineConstantPool *CP = DAG.getMachineFunction().getConstantPool();
2719    SDOperand CPIdx = DAG.getConstantPool(CP->getConstantPoolIndex(FudgeFactor),
2720                                          TLI.getPointerTy());
2721    CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
2722    SDOperand FudgeInReg;
2723    if (DestTy == MVT::f32)
2724      FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
2725                               DAG.getSrcValue(NULL));
2726    else {
2727      assert(DestTy == MVT::f64 && "Unexpected conversion");
2728      FudgeInReg = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
2729                                  CPIdx, DAG.getSrcValue(NULL), MVT::f32);
2730    }
2731    return DAG.getNode(ISD::ADD, DestTy, SignedConv, FudgeInReg);
2732  }
2733
2734  // Check to see if the target has a custom way to lower this.  If so, use it.
2735  switch (TLI.getOperationAction(ISD::SINT_TO_FP, Source.getValueType())) {
2736  default: assert(0 && "This action not implemented for this operation!");
2737  case TargetLowering::Legal:
2738  case TargetLowering::Expand:
2739    break;   // This case is handled below.
2740  case TargetLowering::Custom:
2741    Source = DAG.getNode(ISD::SINT_TO_FP, DestTy, Source);
2742    return LegalizeOp(TLI.LowerOperation(Source, DAG));
2743  }
2744
2745  // Expand the source, then glue it back together for the call.  We must expand
2746  // the source in case it is shared (this pass of legalize must traverse it).
2747  SDOperand SrcLo, SrcHi;
2748  ExpandOp(Source, SrcLo, SrcHi);
2749  Source = DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), SrcLo, SrcHi);
2750
2751  SDNode *OutChain = 0;
2752  SDOperand InChain = FindInputOutputChains(Source.Val, OutChain,
2753                                            DAG.getEntryNode());
2754  const char *FnName = 0;
2755  if (DestTy == MVT::f32)
2756    FnName = "__floatdisf";
2757  else {
2758    assert(DestTy == MVT::f64 && "Unknown fp value type!");
2759    FnName = "__floatdidf";
2760  }
2761
2762  SDOperand Callee = DAG.getExternalSymbol(FnName, TLI.getPointerTy());
2763
2764  TargetLowering::ArgListTy Args;
2765  const Type *ArgTy = MVT::getTypeForValueType(Source.getValueType());
2766
2767  Args.push_back(std::make_pair(Source, ArgTy));
2768
2769  // We don't care about token chains for libcalls.  We just use the entry
2770  // node as our input and ignore the output chain.  This allows us to place
2771  // calls wherever we need them to satisfy data dependences.
2772  const Type *RetTy = MVT::getTypeForValueType(DestTy);
2773
2774  std::pair<SDOperand,SDOperand> CallResult =
2775    TLI.LowerCallTo(InChain, RetTy, false, CallingConv::C, true,
2776                    Callee, Args, DAG);
2777
2778  SpliceCallInto(CallResult.second, OutChain);
2779  return CallResult.first;
2780}
2781
2782
2783
2784/// ExpandOp - Expand the specified SDOperand into its two component pieces
2785/// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
2786/// LegalizeNodes map is filled in for any results that are not expanded, the
2787/// ExpandedNodes map is filled in for any results that are expanded, and the
2788/// Lo/Hi values are returned.
2789void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
2790  MVT::ValueType VT = Op.getValueType();
2791  MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
2792  SDNode *Node = Op.Val;
2793  assert(getTypeAction(VT) == Expand && "Not an expanded type!");
2794  assert(MVT::isInteger(VT) && "Cannot expand FP values!");
2795  assert(MVT::isInteger(NVT) && NVT < VT &&
2796         "Cannot expand to FP value or to larger int value!");
2797
2798  // If there is more than one use of this, see if we already expanded it.
2799  // There is no use remembering values that only have a single use, as the map
2800  // entries will never be reused.
2801  if (!Node->hasOneUse()) {
2802    std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
2803      = ExpandedNodes.find(Op);
2804    if (I != ExpandedNodes.end()) {
2805      Lo = I->second.first;
2806      Hi = I->second.second;
2807      return;
2808    }
2809  } else {
2810    assert(!ExpandedNodes.count(Op) && "Re-expanding a node!");
2811  }
2812
2813  // Expanding to multiple registers needs to perform an optimization step, and
2814  // is not careful to avoid operations the target does not support.  Make sure
2815  // that all generated operations are legalized in the next iteration.
2816  NeedsAnotherIteration = true;
2817
2818  switch (Node->getOpcode()) {
2819   case ISD::CopyFromReg:
2820      assert(0 && "CopyFromReg must be legal!");
2821   default:
2822    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
2823    assert(0 && "Do not know how to expand this operator!");
2824    abort();
2825  case ISD::UNDEF:
2826    Lo = DAG.getNode(ISD::UNDEF, NVT);
2827    Hi = DAG.getNode(ISD::UNDEF, NVT);
2828    break;
2829  case ISD::Constant: {
2830    uint64_t Cst = cast<ConstantSDNode>(Node)->getValue();
2831    Lo = DAG.getConstant(Cst, NVT);
2832    Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
2833    break;
2834  }
2835
2836  case ISD::BUILD_PAIR:
2837    // Legalize both operands.  FIXME: in the future we should handle the case
2838    // where the two elements are not legal.
2839    assert(isTypeLegal(NVT) && "Cannot expand this multiple times yet!");
2840    Lo = LegalizeOp(Node->getOperand(0));
2841    Hi = LegalizeOp(Node->getOperand(1));
2842    break;
2843
2844  case ISD::CTPOP:
2845    ExpandOp(Node->getOperand(0), Lo, Hi);
2846    Lo = DAG.getNode(ISD::ADD, NVT,          // ctpop(HL) -> ctpop(H)+ctpop(L)
2847                     DAG.getNode(ISD::CTPOP, NVT, Lo),
2848                     DAG.getNode(ISD::CTPOP, NVT, Hi));
2849    Hi = DAG.getConstant(0, NVT);
2850    break;
2851
2852  case ISD::CTLZ: {
2853    // ctlz (HL) -> ctlz(H) != 32 ? ctlz(H) : (ctlz(L)+32)
2854    ExpandOp(Node->getOperand(0), Lo, Hi);
2855    SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
2856    SDOperand HLZ = DAG.getNode(ISD::CTLZ, NVT, Hi);
2857    SDOperand TopNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), HLZ, BitsC,
2858                                        ISD::SETNE);
2859    SDOperand LowPart = DAG.getNode(ISD::CTLZ, NVT, Lo);
2860    LowPart = DAG.getNode(ISD::ADD, NVT, LowPart, BitsC);
2861
2862    Lo = DAG.getNode(ISD::SELECT, NVT, TopNotZero, HLZ, LowPart);
2863    Hi = DAG.getConstant(0, NVT);
2864    break;
2865  }
2866
2867  case ISD::CTTZ: {
2868    // cttz (HL) -> cttz(L) != 32 ? cttz(L) : (cttz(H)+32)
2869    ExpandOp(Node->getOperand(0), Lo, Hi);
2870    SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
2871    SDOperand LTZ = DAG.getNode(ISD::CTTZ, NVT, Lo);
2872    SDOperand BotNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), LTZ, BitsC,
2873                                        ISD::SETNE);
2874    SDOperand HiPart = DAG.getNode(ISD::CTTZ, NVT, Hi);
2875    HiPart = DAG.getNode(ISD::ADD, NVT, HiPart, BitsC);
2876
2877    Lo = DAG.getNode(ISD::SELECT, NVT, BotNotZero, LTZ, HiPart);
2878    Hi = DAG.getConstant(0, NVT);
2879    break;
2880  }
2881
2882  case ISD::LOAD: {
2883    SDOperand Ch = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
2884    SDOperand Ptr = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2885    Lo = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
2886
2887    // Increment the pointer to the other half.
2888    unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
2889    Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
2890                      getIntPtrConstant(IncrementSize));
2891    //Is this safe?  declaring that the two parts of the split load
2892    //are from the same instruction?
2893    Hi = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
2894
2895    // Build a factor node to remember that this load is independent of the
2896    // other one.
2897    SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
2898                               Hi.getValue(1));
2899
2900    // Remember that we legalized the chain.
2901    AddLegalizedOperand(Op.getValue(1), TF);
2902    if (!TLI.isLittleEndian())
2903      std::swap(Lo, Hi);
2904    break;
2905  }
2906  case ISD::TAILCALL:
2907  case ISD::CALL: {
2908    SDOperand Chain  = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2909    SDOperand Callee = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
2910
2911    bool Changed = false;
2912    std::vector<SDOperand> Ops;
2913    for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i) {
2914      Ops.push_back(LegalizeOp(Node->getOperand(i)));
2915      Changed |= Ops.back() != Node->getOperand(i);
2916    }
2917
2918    assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
2919           "Can only expand a call once so far, not i64 -> i16!");
2920
2921    std::vector<MVT::ValueType> RetTyVTs;
2922    RetTyVTs.reserve(3);
2923    RetTyVTs.push_back(NVT);
2924    RetTyVTs.push_back(NVT);
2925    RetTyVTs.push_back(MVT::Other);
2926    SDNode *NC = DAG.getCall(RetTyVTs, Chain, Callee, Ops,
2927                             Node->getOpcode() == ISD::TAILCALL);
2928    Lo = SDOperand(NC, 0);
2929    Hi = SDOperand(NC, 1);
2930
2931    // Insert the new chain mapping.
2932    AddLegalizedOperand(Op.getValue(1), Hi.getValue(2));
2933    break;
2934  }
2935  case ISD::AND:
2936  case ISD::OR:
2937  case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
2938    SDOperand LL, LH, RL, RH;
2939    ExpandOp(Node->getOperand(0), LL, LH);
2940    ExpandOp(Node->getOperand(1), RL, RH);
2941    Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
2942    Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
2943    break;
2944  }
2945  case ISD::SELECT: {
2946    SDOperand C, LL, LH, RL, RH;
2947
2948    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2949    case Expand: assert(0 && "It's impossible to expand bools");
2950    case Legal:
2951      C = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
2952      break;
2953    case Promote:
2954      C = PromoteOp(Node->getOperand(0));  // Promote the condition.
2955      break;
2956    }
2957    ExpandOp(Node->getOperand(1), LL, LH);
2958    ExpandOp(Node->getOperand(2), RL, RH);
2959    Lo = DAG.getNode(ISD::SELECT, NVT, C, LL, RL);
2960    Hi = DAG.getNode(ISD::SELECT, NVT, C, LH, RH);
2961    break;
2962  }
2963  case ISD::SELECT_CC: {
2964    SDOperand TL, TH, FL, FH;
2965    ExpandOp(Node->getOperand(2), TL, TH);
2966    ExpandOp(Node->getOperand(3), FL, FH);
2967    Lo = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
2968                     Node->getOperand(1), TL, FL, Node->getOperand(4));
2969    Hi = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
2970                     Node->getOperand(1), TH, FH, Node->getOperand(4));
2971    Lo = LegalizeOp(Lo);
2972    Hi = LegalizeOp(Hi);
2973    break;
2974  }
2975  case ISD::SIGN_EXTEND: {
2976    SDOperand In;
2977    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2978    case Expand: assert(0 && "expand-expand not implemented yet!");
2979    case Legal: In = LegalizeOp(Node->getOperand(0)); break;
2980    case Promote:
2981      In = PromoteOp(Node->getOperand(0));
2982      // Emit the appropriate sign_extend_inreg to get the value we want.
2983      In = DAG.getNode(ISD::SIGN_EXTEND_INREG, In.getValueType(), In,
2984                       DAG.getValueType(Node->getOperand(0).getValueType()));
2985      break;
2986    }
2987
2988    // The low part is just a sign extension of the input (which degenerates to
2989    // a copy).
2990    Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, In);
2991
2992    // The high part is obtained by SRA'ing all but one of the bits of the lo
2993    // part.
2994    unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
2995    Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1,
2996                                                       TLI.getShiftAmountTy()));
2997    break;
2998  }
2999  case ISD::ZERO_EXTEND: {
3000    SDOperand In;
3001    switch (getTypeAction(Node->getOperand(0).getValueType())) {
3002    case Expand: assert(0 && "expand-expand not implemented yet!");
3003    case Legal: In = LegalizeOp(Node->getOperand(0)); break;
3004    case Promote:
3005      In = PromoteOp(Node->getOperand(0));
3006      // Emit the appropriate zero_extend_inreg to get the value we want.
3007      In = DAG.getZeroExtendInReg(In, Node->getOperand(0).getValueType());
3008      break;
3009    }
3010
3011    // The low part is just a zero extension of the input (which degenerates to
3012    // a copy).
3013    Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, In);
3014
3015    // The high part is just a zero.
3016    Hi = DAG.getConstant(0, NVT);
3017    break;
3018  }
3019    // These operators cannot be expanded directly, emit them as calls to
3020    // library functions.
3021  case ISD::FP_TO_SINT:
3022    if (TLI.getOperationAction(ISD::FP_TO_SINT, VT) == TargetLowering::Custom) {
3023      SDOperand Op;
3024      switch (getTypeAction(Node->getOperand(0).getValueType())) {
3025      case Expand: assert(0 && "cannot expand FP!");
3026      case Legal: Op = LegalizeOp(Node->getOperand(0)); break;
3027      case Promote: Op = PromoteOp(Node->getOperand(0)); break;
3028      }
3029
3030      Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_SINT, VT, Op), DAG);
3031
3032      // Now that the custom expander is done, expand the result, which is still
3033      // VT.
3034      ExpandOp(Op, Lo, Hi);
3035      break;
3036    }
3037
3038    if (Node->getOperand(0).getValueType() == MVT::f32)
3039      Lo = ExpandLibCall("__fixsfdi", Node, Hi);
3040    else
3041      Lo = ExpandLibCall("__fixdfdi", Node, Hi);
3042    break;
3043
3044  case ISD::FP_TO_UINT:
3045    if (TLI.getOperationAction(ISD::FP_TO_UINT, VT) == TargetLowering::Custom) {
3046      SDOperand Op = DAG.getNode(ISD::FP_TO_UINT, VT,
3047                                 LegalizeOp(Node->getOperand(0)));
3048      // Now that the custom expander is done, expand the result, which is still
3049      // VT.
3050      ExpandOp(TLI.LowerOperation(Op, DAG), Lo, Hi);
3051      break;
3052    }
3053
3054    if (Node->getOperand(0).getValueType() == MVT::f32)
3055      Lo = ExpandLibCall("__fixunssfdi", Node, Hi);
3056    else
3057      Lo = ExpandLibCall("__fixunsdfdi", Node, Hi);
3058    break;
3059
3060  case ISD::SHL:
3061    // If we can emit an efficient shift operation, do so now.
3062    if (ExpandShift(ISD::SHL, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
3063      break;
3064
3065    // If this target supports SHL_PARTS, use it.
3066    if (TLI.getOperationAction(ISD::SHL_PARTS, NVT) == TargetLowering::Legal) {
3067      ExpandShiftParts(ISD::SHL_PARTS, Node->getOperand(0), Node->getOperand(1),
3068                       Lo, Hi);
3069      break;
3070    }
3071
3072    // Otherwise, emit a libcall.
3073    Lo = ExpandLibCall("__ashldi3", Node, Hi);
3074    break;
3075
3076  case ISD::SRA:
3077    // If we can emit an efficient shift operation, do so now.
3078    if (ExpandShift(ISD::SRA, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
3079      break;
3080
3081    // If this target supports SRA_PARTS, use it.
3082    if (TLI.getOperationAction(ISD::SRA_PARTS, NVT) == TargetLowering::Legal) {
3083      ExpandShiftParts(ISD::SRA_PARTS, Node->getOperand(0), Node->getOperand(1),
3084                       Lo, Hi);
3085      break;
3086    }
3087
3088    // Otherwise, emit a libcall.
3089    Lo = ExpandLibCall("__ashrdi3", Node, Hi);
3090    break;
3091  case ISD::SRL:
3092    // If we can emit an efficient shift operation, do so now.
3093    if (ExpandShift(ISD::SRL, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
3094      break;
3095
3096    // If this target supports SRL_PARTS, use it.
3097    if (TLI.getOperationAction(ISD::SRL_PARTS, NVT) == TargetLowering::Legal) {
3098      ExpandShiftParts(ISD::SRL_PARTS, Node->getOperand(0), Node->getOperand(1),
3099                       Lo, Hi);
3100      break;
3101    }
3102
3103    // Otherwise, emit a libcall.
3104    Lo = ExpandLibCall("__lshrdi3", Node, Hi);
3105    break;
3106
3107  case ISD::ADD:
3108    ExpandByParts(ISD::ADD_PARTS, Node->getOperand(0), Node->getOperand(1),
3109                  Lo, Hi);
3110    break;
3111  case ISD::SUB:
3112    ExpandByParts(ISD::SUB_PARTS, Node->getOperand(0), Node->getOperand(1),
3113                  Lo, Hi);
3114    break;
3115  case ISD::MUL: {
3116    if (TLI.getOperationAction(ISD::MULHU, NVT) == TargetLowering::Legal) {
3117      SDOperand LL, LH, RL, RH;
3118      ExpandOp(Node->getOperand(0), LL, LH);
3119      ExpandOp(Node->getOperand(1), RL, RH);
3120      Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
3121      RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
3122      LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
3123      Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
3124      Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
3125      Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
3126    } else {
3127      Lo = ExpandLibCall("__muldi3" , Node, Hi); break;
3128    }
3129    break;
3130  }
3131  case ISD::SDIV: Lo = ExpandLibCall("__divdi3" , Node, Hi); break;
3132  case ISD::UDIV: Lo = ExpandLibCall("__udivdi3", Node, Hi); break;
3133  case ISD::SREM: Lo = ExpandLibCall("__moddi3" , Node, Hi); break;
3134  case ISD::UREM: Lo = ExpandLibCall("__umoddi3", Node, Hi); break;
3135  }
3136
3137  // Remember in a map if the values will be reused later.
3138  if (!Node->hasOneUse()) {
3139    bool isNew = ExpandedNodes.insert(std::make_pair(Op,
3140                                            std::make_pair(Lo, Hi))).second;
3141    assert(isNew && "Value already expanded?!?");
3142  }
3143}
3144
3145
3146// SelectionDAG::Legalize - This is the entry point for the file.
3147//
3148void SelectionDAG::Legalize() {
3149  /// run - This is the main entry point to this class.
3150  ///
3151  SelectionDAGLegalize(*this).Run();
3152}
3153
3154