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