LegalizeDAG.cpp revision 1c51c6ac13b5e68b099605021784c7f552dcce3c
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/Target/TargetLowering.h"
19#include "llvm/Target/TargetData.h"
20#include "llvm/Target/TargetOptions.h"
21#include "llvm/Constants.h"
22#include <iostream>
23using namespace llvm;
24
25//===----------------------------------------------------------------------===//
26/// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
27/// hacks on it until the target machine can handle it.  This involves
28/// eliminating value sizes the machine cannot handle (promoting small sizes to
29/// large sizes or splitting up large values into small values) as well as
30/// eliminating operations the machine cannot handle.
31///
32/// This code also does a small amount of optimization and recognition of idioms
33/// as part of its processing.  For example, if a target does not support a
34/// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
35/// will attempt merge setcc and brc instructions into brcc's.
36///
37namespace {
38class SelectionDAGLegalize {
39  TargetLowering &TLI;
40  SelectionDAG &DAG;
41
42  /// LegalizeAction - This enum indicates what action we should take for each
43  /// value type the can occur in the program.
44  enum LegalizeAction {
45    Legal,            // The target natively supports this value type.
46    Promote,          // This should be promoted to the next larger type.
47    Expand,           // This integer type should be broken into smaller pieces.
48  };
49
50  /// ValueTypeActions - This is a bitvector that contains two bits for each
51  /// value type, where the two bits correspond to the LegalizeAction enum.
52  /// This can be queried with "getTypeAction(VT)".
53  unsigned ValueTypeActions;
54
55  /// NeedsAnotherIteration - This is set when we expand a large integer
56  /// operation into smaller integer operations, but the smaller operations are
57  /// not set.  This occurs only rarely in practice, for targets that don't have
58  /// 32-bit or larger integer registers.
59  bool NeedsAnotherIteration;
60
61  /// LegalizedNodes - For nodes that are of legal width, and that have more
62  /// than one use, this map indicates what regularized operand to use.  This
63  /// allows us to avoid legalizing the same thing more than once.
64  std::map<SDOperand, SDOperand> LegalizedNodes;
65
66  /// PromotedNodes - For nodes that are below legal width, and that have more
67  /// than one use, this map indicates what promoted value to use.  This allows
68  /// us to avoid promoting the same thing more than once.
69  std::map<SDOperand, SDOperand> PromotedNodes;
70
71  /// ExpandedNodes - For nodes that need to be expanded, and which have more
72  /// than one use, this map indicates which which operands are the expanded
73  /// version of the input.  This allows us to avoid expanding the same node
74  /// more than once.
75  std::map<SDOperand, std::pair<SDOperand, SDOperand> > ExpandedNodes;
76
77  void AddLegalizedOperand(SDOperand From, SDOperand To) {
78    bool isNew = LegalizedNodes.insert(std::make_pair(From, To)).second;
79    assert(isNew && "Got into the map somehow?");
80  }
81  void AddPromotedOperand(SDOperand From, SDOperand To) {
82    bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
83    assert(isNew && "Got into the map somehow?");
84  }
85
86public:
87
88  SelectionDAGLegalize(SelectionDAG &DAG);
89
90  /// Run - While there is still lowering to do, perform a pass over the DAG.
91  /// Most regularization can be done in a single pass, but targets that require
92  /// large values to be split into registers multiple times (e.g. i64 -> 4x
93  /// i16) require iteration for these values (the first iteration will demote
94  /// to i32, the second will demote to i16).
95  void Run() {
96    do {
97      NeedsAnotherIteration = false;
98      LegalizeDAG();
99    } while (NeedsAnotherIteration);
100  }
101
102  /// getTypeAction - Return how we should legalize values of this type, either
103  /// it is already legal or we need to expand it into multiple registers of
104  /// smaller integer type, or we need to promote it to a larger type.
105  LegalizeAction getTypeAction(MVT::ValueType VT) const {
106    return (LegalizeAction)((ValueTypeActions >> (2*VT)) & 3);
107  }
108
109  /// isTypeLegal - Return true if this type is legal on this target.
110  ///
111  bool isTypeLegal(MVT::ValueType VT) const {
112    return getTypeAction(VT) == Legal;
113  }
114
115private:
116  void LegalizeDAG();
117
118  SDOperand LegalizeOp(SDOperand O);
119  void ExpandOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
120  SDOperand PromoteOp(SDOperand O);
121
122  SDOperand ExpandLibCall(const char *Name, SDNode *Node,
123                          SDOperand &Hi);
124  SDOperand ExpandIntToFP(bool isSigned, MVT::ValueType DestTy,
125                          SDOperand Source);
126  bool ExpandShift(unsigned Opc, SDOperand Op, SDOperand Amt,
127                   SDOperand &Lo, SDOperand &Hi);
128  void ExpandShiftParts(unsigned NodeOp, SDOperand Op, SDOperand Amt,
129                        SDOperand &Lo, SDOperand &Hi);
130  void ExpandByParts(unsigned NodeOp, SDOperand LHS, SDOperand RHS,
131                     SDOperand &Lo, SDOperand &Hi);
132
133  SDOperand getIntPtrConstant(uint64_t Val) {
134    return DAG.getConstant(Val, TLI.getPointerTy());
135  }
136};
137}
138
139
140SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag)
141  : TLI(dag.getTargetLoweringInfo()), DAG(dag),
142    ValueTypeActions(TLI.getValueTypeActions()) {
143  assert(MVT::LAST_VALUETYPE <= 16 &&
144         "Too many value types for ValueTypeActions to hold!");
145}
146
147void SelectionDAGLegalize::LegalizeDAG() {
148  SDOperand OldRoot = DAG.getRoot();
149  SDOperand NewRoot = LegalizeOp(OldRoot);
150  DAG.setRoot(NewRoot);
151
152  ExpandedNodes.clear();
153  LegalizedNodes.clear();
154  PromotedNodes.clear();
155
156  // Remove dead nodes now.
157  DAG.RemoveDeadNodes(OldRoot.Val);
158}
159
160SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
161  assert(getTypeAction(Op.getValueType()) == Legal &&
162         "Caller should expand or promote operands that are not legal!");
163
164  // If this operation defines any values that cannot be represented in a
165  // register on this target, make sure to expand or promote them.
166  if (Op.Val->getNumValues() > 1) {
167    for (unsigned i = 0, e = Op.Val->getNumValues(); i != e; ++i)
168      switch (getTypeAction(Op.Val->getValueType(i))) {
169      case Legal: break;  // Nothing to do.
170      case Expand: {
171        SDOperand T1, T2;
172        ExpandOp(Op.getValue(i), T1, T2);
173        assert(LegalizedNodes.count(Op) &&
174               "Expansion didn't add legal operands!");
175        return LegalizedNodes[Op];
176      }
177      case Promote:
178        PromoteOp(Op.getValue(i));
179        assert(LegalizedNodes.count(Op) &&
180               "Expansion didn't add legal operands!");
181        return LegalizedNodes[Op];
182      }
183  }
184
185  std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
186  if (I != LegalizedNodes.end()) return I->second;
187
188  SDOperand Tmp1, Tmp2, Tmp3;
189
190  SDOperand Result = Op;
191  SDNode *Node = Op.Val;
192
193  switch (Node->getOpcode()) {
194  default:
195    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
196    assert(0 && "Do not know how to legalize this operator!");
197    abort();
198  case ISD::EntryToken:
199  case ISD::FrameIndex:
200  case ISD::GlobalAddress:
201  case ISD::ExternalSymbol:
202  case ISD::ConstantPool:           // Nothing to do.
203    assert(getTypeAction(Node->getValueType(0)) == Legal &&
204           "This must be legal!");
205    break;
206  case ISD::CopyFromReg:
207    Tmp1 = LegalizeOp(Node->getOperand(0));
208    if (Tmp1 != Node->getOperand(0))
209      Result = DAG.getCopyFromReg(cast<RegSDNode>(Node)->getReg(),
210                                  Node->getValueType(0), Tmp1);
211    else
212      Result = Op.getValue(0);
213
214    // Since CopyFromReg produces two values, make sure to remember that we
215    // legalized both of them.
216    AddLegalizedOperand(Op.getValue(0), Result);
217    AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
218    return Result.getValue(Op.ResNo);
219  case ISD::ImplicitDef:
220    Tmp1 = LegalizeOp(Node->getOperand(0));
221    if (Tmp1 != Node->getOperand(0))
222      Result = DAG.getImplicitDef(Tmp1, cast<RegSDNode>(Node)->getReg());
223    break;
224  case ISD::UNDEF: {
225    MVT::ValueType VT = Op.getValueType();
226    switch (TLI.getOperationAction(ISD::UNDEF, VT)) {
227    default: assert(0 && "This action is not supported yet!");
228    case TargetLowering::Expand:
229    case TargetLowering::Promote:
230      if (MVT::isInteger(VT))
231        Result = DAG.getConstant(0, VT);
232      else if (MVT::isFloatingPoint(VT))
233        Result = DAG.getConstantFP(0, VT);
234      else
235        assert(0 && "Unknown value type!");
236      break;
237    case TargetLowering::Legal:
238      break;
239    }
240    break;
241  }
242  case ISD::Constant:
243    // We know we don't need to expand constants here, constants only have one
244    // value and we check that it is fine above.
245
246    // FIXME: Maybe we should handle things like targets that don't support full
247    // 32-bit immediates?
248    break;
249  case ISD::ConstantFP: {
250    // Spill FP immediates to the constant pool if the target cannot directly
251    // codegen them.  Targets often have some immediate values that can be
252    // efficiently generated into an FP register without a load.  We explicitly
253    // leave these constants as ConstantFP nodes for the target to deal with.
254
255    ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
256
257    // Check to see if this FP immediate is already legal.
258    bool isLegal = false;
259    for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
260           E = TLI.legal_fpimm_end(); I != E; ++I)
261      if (CFP->isExactlyValue(*I)) {
262        isLegal = true;
263        break;
264      }
265
266    if (!isLegal) {
267      // Otherwise we need to spill the constant to memory.
268      MachineConstantPool *CP = DAG.getMachineFunction().getConstantPool();
269
270      bool Extend = false;
271
272      // If a FP immediate is precise when represented as a float, we put it
273      // into the constant pool as a float, even if it's is statically typed
274      // as a double.
275      MVT::ValueType VT = CFP->getValueType(0);
276      bool isDouble = VT == MVT::f64;
277      ConstantFP *LLVMC = ConstantFP::get(isDouble ? Type::DoubleTy :
278                                             Type::FloatTy, CFP->getValue());
279      if (isDouble && CFP->isExactlyValue((float)CFP->getValue()) &&
280          // Only do this if the target has a native EXTLOAD instruction from
281          // f32.
282          TLI.getOperationAction(ISD::EXTLOAD,
283                                 MVT::f32) == TargetLowering::Legal) {
284        LLVMC = cast<ConstantFP>(ConstantExpr::getCast(LLVMC, Type::FloatTy));
285        VT = MVT::f32;
286        Extend = true;
287      }
288
289      SDOperand CPIdx = DAG.getConstantPool(CP->getConstantPoolIndex(LLVMC),
290                                            TLI.getPointerTy());
291      if (Extend) {
292        Result = DAG.getNode(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(), CPIdx,
293                             MVT::f32);
294      } else {
295        Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx);
296      }
297    }
298    break;
299  }
300  case ISD::TokenFactor: {
301    std::vector<SDOperand> Ops;
302    bool Changed = false;
303    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
304      SDOperand Op = Node->getOperand(i);
305      // Fold single-use TokenFactor nodes into this token factor as we go.
306      if (Op.getOpcode() == ISD::TokenFactor && Op.hasOneUse()) {
307        Changed = true;
308        for (unsigned j = 0, e = Op.getNumOperands(); j != e; ++j)
309          Ops.push_back(LegalizeOp(Op.getOperand(j)));
310      } else {
311        Ops.push_back(LegalizeOp(Op));  // Legalize the operands
312        Changed |= Ops[i] != Op;
313      }
314    }
315    if (Changed)
316      Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Ops);
317    break;
318  }
319
320  case ISD::ADJCALLSTACKDOWN:
321  case ISD::ADJCALLSTACKUP:
322    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
323    // There is no need to legalize the size argument (Operand #1)
324    if (Tmp1 != Node->getOperand(0))
325      Result = DAG.getNode(Node->getOpcode(), MVT::Other, Tmp1,
326                           Node->getOperand(1));
327    break;
328  case ISD::DYNAMIC_STACKALLOC:
329    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
330    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
331    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
332    if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
333        Tmp3 != Node->getOperand(2))
334      Result = DAG.getNode(ISD::DYNAMIC_STACKALLOC, Node->getValueType(0),
335                           Tmp1, Tmp2, Tmp3);
336    else
337      Result = Op.getValue(0);
338
339    // Since this op produces two values, make sure to remember that we
340    // legalized both of them.
341    AddLegalizedOperand(SDOperand(Node, 0), Result);
342    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
343    return Result.getValue(Op.ResNo);
344
345  case ISD::CALL: {
346    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
347    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
348
349    bool Changed = false;
350    std::vector<SDOperand> Ops;
351    for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i) {
352      Ops.push_back(LegalizeOp(Node->getOperand(i)));
353      Changed |= Ops.back() != Node->getOperand(i);
354    }
355
356    if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) || Changed) {
357      std::vector<MVT::ValueType> RetTyVTs;
358      RetTyVTs.reserve(Node->getNumValues());
359      for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
360        RetTyVTs.push_back(Node->getValueType(i));
361      Result = SDOperand(DAG.getCall(RetTyVTs, Tmp1, Tmp2, Ops), 0);
362    } else {
363      Result = Result.getValue(0);
364    }
365    // Since calls produce multiple values, make sure to remember that we
366    // legalized all of them.
367    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
368      AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
369    return Result.getValue(Op.ResNo);
370  }
371  case ISD::BR:
372    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
373    if (Tmp1 != Node->getOperand(0))
374      Result = DAG.getNode(ISD::BR, MVT::Other, Tmp1, Node->getOperand(1));
375    break;
376
377  case ISD::BRCOND:
378    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
379
380    switch (getTypeAction(Node->getOperand(1).getValueType())) {
381    case Expand: assert(0 && "It's impossible to expand bools");
382    case Legal:
383      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
384      break;
385    case Promote:
386      Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
387      break;
388    }
389    // Basic block destination (Op#2) is always legal.
390    if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
391      Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
392                           Node->getOperand(2));
393    break;
394  case ISD::BRCONDTWOWAY:
395    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
396    switch (getTypeAction(Node->getOperand(1).getValueType())) {
397    case Expand: assert(0 && "It's impossible to expand bools");
398    case Legal:
399      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
400      break;
401    case Promote:
402      Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
403      break;
404    }
405    // If this target does not support BRCONDTWOWAY, lower it to a BRCOND/BR
406    // pair.
407    switch (TLI.getOperationAction(ISD::BRCONDTWOWAY, MVT::Other)) {
408    case TargetLowering::Promote:
409    default: assert(0 && "This action is not supported yet!");
410    case TargetLowering::Legal:
411      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1)) {
412        std::vector<SDOperand> Ops;
413        Ops.push_back(Tmp1);
414        Ops.push_back(Tmp2);
415        Ops.push_back(Node->getOperand(2));
416        Ops.push_back(Node->getOperand(3));
417        Result = DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops);
418      }
419      break;
420    case TargetLowering::Expand:
421      Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
422                           Node->getOperand(2));
423      Result = DAG.getNode(ISD::BR, MVT::Other, Result, Node->getOperand(3));
424      break;
425    }
426    break;
427
428  case ISD::LOAD:
429    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
430    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
431    if (Tmp1 != Node->getOperand(0) ||
432        Tmp2 != Node->getOperand(1))
433      Result = DAG.getLoad(Node->getValueType(0), Tmp1, Tmp2);
434    else
435      Result = SDOperand(Node, 0);
436
437    // Since loads produce two values, make sure to remember that we legalized
438    // both of them.
439    AddLegalizedOperand(SDOperand(Node, 0), Result);
440    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
441    return Result.getValue(Op.ResNo);
442
443  case ISD::EXTLOAD:
444  case ISD::SEXTLOAD:
445  case ISD::ZEXTLOAD: {
446    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
447    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
448
449    MVT::ValueType SrcVT = cast<MVTSDNode>(Node)->getExtraValueType();
450    switch (TLI.getOperationAction(Node->getOpcode(), SrcVT)) {
451    default: assert(0 && "This action is not supported yet!");
452    case TargetLowering::Promote:
453      assert(SrcVT == MVT::i1 && "Can only promote EXTLOAD from i1 -> i8!");
454      Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0),
455                           Tmp1, Tmp2, MVT::i8);
456      // Since loads produce two values, make sure to remember that we legalized
457      // both of them.
458      AddLegalizedOperand(SDOperand(Node, 0), Result);
459      AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
460      return Result.getValue(Op.ResNo);
461
462    case TargetLowering::Legal:
463      if (Tmp1 != Node->getOperand(0) ||
464          Tmp2 != Node->getOperand(1))
465        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0),
466                             Tmp1, Tmp2, SrcVT);
467      else
468        Result = SDOperand(Node, 0);
469
470      // Since loads produce two values, make sure to remember that we legalized
471      // both of them.
472      AddLegalizedOperand(SDOperand(Node, 0), Result);
473      AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
474      return Result.getValue(Op.ResNo);
475    case TargetLowering::Expand:
476      assert(Node->getOpcode() != ISD::EXTLOAD &&
477             "EXTLOAD should always be supported!");
478      // Turn the unsupported load into an EXTLOAD followed by an explicit
479      // zero/sign extend inreg.
480      Result = DAG.getNode(ISD::EXTLOAD, Node->getValueType(0),
481                           Tmp1, Tmp2, SrcVT);
482      unsigned ExtOp = Node->getOpcode() == ISD::SEXTLOAD ?
483                            ISD::SIGN_EXTEND_INREG : ISD::ZERO_EXTEND_INREG;
484      SDOperand ValRes = DAG.getNode(ExtOp, Result.getValueType(),
485                                     Result, SrcVT);
486      AddLegalizedOperand(SDOperand(Node, 0), ValRes);
487      AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
488      if (Op.ResNo)
489        return Result.getValue(1);
490      return ValRes;
491    }
492    assert(0 && "Unreachable");
493  }
494  case ISD::EXTRACT_ELEMENT:
495    // Get both the low and high parts.
496    ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
497    if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
498      Result = Tmp2;  // 1 -> Hi
499    else
500      Result = Tmp1;  // 0 -> Lo
501    break;
502
503  case ISD::CopyToReg:
504    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
505
506    switch (getTypeAction(Node->getOperand(1).getValueType())) {
507    case Legal:
508      // Legalize the incoming value (must be legal).
509      Tmp2 = LegalizeOp(Node->getOperand(1));
510      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
511        Result = DAG.getCopyToReg(Tmp1, Tmp2, cast<RegSDNode>(Node)->getReg());
512      break;
513    case Promote:
514      Tmp2 = PromoteOp(Node->getOperand(1));
515      Result = DAG.getCopyToReg(Tmp1, Tmp2, cast<RegSDNode>(Node)->getReg());
516      break;
517    case Expand:
518      SDOperand Lo, Hi;
519      ExpandOp(Node->getOperand(1), Lo, Hi);
520      unsigned Reg = cast<RegSDNode>(Node)->getReg();
521      Lo = DAG.getCopyToReg(Tmp1, Lo, Reg);
522      Hi = DAG.getCopyToReg(Tmp1, Hi, Reg+1);
523      // Note that the copytoreg nodes are independent of each other.
524      Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
525      assert(isTypeLegal(Result.getValueType()) &&
526             "Cannot expand multiple times yet (i64 -> i16)");
527      break;
528    }
529    break;
530
531  case ISD::RET:
532    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
533    switch (Node->getNumOperands()) {
534    case 2:  // ret val
535      switch (getTypeAction(Node->getOperand(1).getValueType())) {
536      case Legal:
537        Tmp2 = LegalizeOp(Node->getOperand(1));
538        if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
539          Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
540        break;
541      case Expand: {
542        SDOperand Lo, Hi;
543        ExpandOp(Node->getOperand(1), Lo, Hi);
544        Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
545        break;
546      }
547      case Promote:
548        Tmp2 = PromoteOp(Node->getOperand(1));
549        Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
550        break;
551      }
552      break;
553    case 1:  // ret void
554      if (Tmp1 != Node->getOperand(0))
555        Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1);
556      break;
557    default: { // ret <values>
558      std::vector<SDOperand> NewValues;
559      NewValues.push_back(Tmp1);
560      for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
561        switch (getTypeAction(Node->getOperand(i).getValueType())) {
562        case Legal:
563          NewValues.push_back(LegalizeOp(Node->getOperand(i)));
564          break;
565        case Expand: {
566          SDOperand Lo, Hi;
567          ExpandOp(Node->getOperand(i), Lo, Hi);
568          NewValues.push_back(Lo);
569          NewValues.push_back(Hi);
570          break;
571        }
572        case Promote:
573          assert(0 && "Can't promote multiple return value yet!");
574        }
575      Result = DAG.getNode(ISD::RET, MVT::Other, NewValues);
576      break;
577    }
578    }
579    break;
580  case ISD::STORE:
581    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
582    Tmp2 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
583
584    // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
585    if (ConstantFPSDNode *CFP =dyn_cast<ConstantFPSDNode>(Node->getOperand(1))){
586      if (CFP->getValueType(0) == MVT::f32) {
587        union {
588          unsigned I;
589          float    F;
590        } V;
591        V.F = CFP->getValue();
592        Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
593                             DAG.getConstant(V.I, MVT::i32), Tmp2);
594      } else {
595        assert(CFP->getValueType(0) == MVT::f64 && "Unknown FP type!");
596        union {
597          uint64_t I;
598          double   F;
599        } V;
600        V.F = CFP->getValue();
601        Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
602                             DAG.getConstant(V.I, MVT::i64), Tmp2);
603      }
604      Node = Result.Val;
605    }
606
607    switch (getTypeAction(Node->getOperand(1).getValueType())) {
608    case Legal: {
609      SDOperand Val = LegalizeOp(Node->getOperand(1));
610      if (Val != Node->getOperand(1) || Tmp1 != Node->getOperand(0) ||
611          Tmp2 != Node->getOperand(2))
612        Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Val, Tmp2);
613      break;
614    }
615    case Promote:
616      // Truncate the value and store the result.
617      Tmp3 = PromoteOp(Node->getOperand(1));
618      Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp3, Tmp2,
619                           Node->getOperand(1).getValueType());
620      break;
621
622    case Expand:
623      SDOperand Lo, Hi;
624      ExpandOp(Node->getOperand(1), Lo, Hi);
625
626      if (!TLI.isLittleEndian())
627        std::swap(Lo, Hi);
628
629      Lo = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Lo, Tmp2);
630
631      unsigned IncrementSize = MVT::getSizeInBits(Hi.getValueType())/8;
632      Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
633                         getIntPtrConstant(IncrementSize));
634      assert(isTypeLegal(Tmp2.getValueType()) &&
635             "Pointers must be legal!");
636      Hi = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Hi, Tmp2);
637      Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
638      break;
639    }
640    break;
641  case ISD::PCMARKER:
642    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
643    if (Tmp1 != Node->getOperand(0))
644      Result = DAG.getNode(ISD::PCMARKER, MVT::Other, Tmp1,Node->getOperand(1));
645    break;
646  case ISD::TRUNCSTORE:
647    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
648    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
649
650    switch (getTypeAction(Node->getOperand(1).getValueType())) {
651    case Legal:
652      Tmp2 = LegalizeOp(Node->getOperand(1));
653      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
654          Tmp3 != Node->getOperand(2))
655        Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
656                             cast<MVTSDNode>(Node)->getExtraValueType());
657      break;
658    case Promote:
659    case Expand:
660      assert(0 && "Cannot handle illegal TRUNCSTORE yet!");
661    }
662    break;
663  case ISD::SELECT:
664    switch (getTypeAction(Node->getOperand(0).getValueType())) {
665    case Expand: assert(0 && "It's impossible to expand bools");
666    case Legal:
667      Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
668      break;
669    case Promote:
670      Tmp1 = PromoteOp(Node->getOperand(0));  // Promote the condition.
671      break;
672    }
673    Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
674    Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
675
676    switch (TLI.getOperationAction(Node->getOpcode(), Tmp2.getValueType())) {
677    default: assert(0 && "This action is not supported yet!");
678    case TargetLowering::Legal:
679      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
680          Tmp3 != Node->getOperand(2))
681        Result = DAG.getNode(ISD::SELECT, Node->getValueType(0),
682                             Tmp1, Tmp2, Tmp3);
683      break;
684    case TargetLowering::Promote: {
685      MVT::ValueType NVT =
686        TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
687      unsigned ExtOp, TruncOp;
688      if (MVT::isInteger(Tmp2.getValueType())) {
689        ExtOp = ISD::ZERO_EXTEND;
690        TruncOp  = ISD::TRUNCATE;
691      } else {
692        ExtOp = ISD::FP_EXTEND;
693        TruncOp  = ISD::FP_ROUND;
694      }
695      // Promote each of the values to the new type.
696      Tmp2 = DAG.getNode(ExtOp, NVT, Tmp2);
697      Tmp3 = DAG.getNode(ExtOp, NVT, Tmp3);
698      // Perform the larger operation, then round down.
699      Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2,Tmp3);
700      Result = DAG.getNode(TruncOp, Node->getValueType(0), Result);
701      break;
702    }
703    }
704    break;
705  case ISD::SETCC:
706    switch (getTypeAction(Node->getOperand(0).getValueType())) {
707    case Legal:
708      Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
709      Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
710      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
711        Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
712                              Node->getValueType(0), Tmp1, Tmp2);
713      break;
714    case Promote:
715      Tmp1 = PromoteOp(Node->getOperand(0));   // LHS
716      Tmp2 = PromoteOp(Node->getOperand(1));   // RHS
717
718      // If this is an FP compare, the operands have already been extended.
719      if (MVT::isInteger(Node->getOperand(0).getValueType())) {
720        MVT::ValueType VT = Node->getOperand(0).getValueType();
721        MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
722
723        // Otherwise, we have to insert explicit sign or zero extends.  Note
724        // that we could insert sign extends for ALL conditions, but zero extend
725        // is cheaper on many machines (an AND instead of two shifts), so prefer
726        // it.
727        switch (cast<SetCCSDNode>(Node)->getCondition()) {
728        default: assert(0 && "Unknown integer comparison!");
729        case ISD::SETEQ:
730        case ISD::SETNE:
731        case ISD::SETUGE:
732        case ISD::SETUGT:
733        case ISD::SETULE:
734        case ISD::SETULT:
735          // ALL of these operations will work if we either sign or zero extend
736          // the operands (including the unsigned comparisons!).  Zero extend is
737          // usually a simpler/cheaper operation, so prefer it.
738          Tmp1 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp1, VT);
739          Tmp2 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp2, VT);
740          break;
741        case ISD::SETGE:
742        case ISD::SETGT:
743        case ISD::SETLT:
744        case ISD::SETLE:
745          Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1, VT);
746          Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2, VT);
747          break;
748        }
749
750      }
751      Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
752                            Node->getValueType(0), Tmp1, Tmp2);
753      break;
754    case Expand:
755      SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
756      ExpandOp(Node->getOperand(0), LHSLo, LHSHi);
757      ExpandOp(Node->getOperand(1), RHSLo, RHSHi);
758      switch (cast<SetCCSDNode>(Node)->getCondition()) {
759      case ISD::SETEQ:
760      case ISD::SETNE:
761        if (RHSLo == RHSHi)
762          if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo))
763            if (RHSCST->isAllOnesValue()) {
764              // Comparison to -1.
765              Tmp1 = DAG.getNode(ISD::AND, LHSLo.getValueType(), LHSLo, LHSHi);
766              Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
767                                    Node->getValueType(0), Tmp1, RHSLo);
768              break;
769            }
770
771        Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
772        Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
773        Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
774        Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
775                              Node->getValueType(0), Tmp1,
776                              DAG.getConstant(0, Tmp1.getValueType()));
777        break;
778      default:
779        // If this is a comparison of the sign bit, just look at the top part.
780        // X > -1,  x < 0
781        if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Node->getOperand(1)))
782          if ((cast<SetCCSDNode>(Node)->getCondition() == ISD::SETLT &&
783               CST->getValue() == 0) ||              // X < 0
784              (cast<SetCCSDNode>(Node)->getCondition() == ISD::SETGT &&
785               (CST->isAllOnesValue())))             // X > -1
786            return DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
787                                Node->getValueType(0), LHSHi, RHSHi);
788
789        // FIXME: This generated code sucks.
790        ISD::CondCode LowCC;
791        switch (cast<SetCCSDNode>(Node)->getCondition()) {
792        default: assert(0 && "Unknown integer setcc!");
793        case ISD::SETLT:
794        case ISD::SETULT: LowCC = ISD::SETULT; break;
795        case ISD::SETGT:
796        case ISD::SETUGT: LowCC = ISD::SETUGT; break;
797        case ISD::SETLE:
798        case ISD::SETULE: LowCC = ISD::SETULE; break;
799        case ISD::SETGE:
800        case ISD::SETUGE: LowCC = ISD::SETUGE; break;
801        }
802
803        // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
804        // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
805        // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
806
807        // NOTE: on targets without efficient SELECT of bools, we can always use
808        // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
809        Tmp1 = DAG.getSetCC(LowCC, Node->getValueType(0), LHSLo, RHSLo);
810        Tmp2 = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
811                            Node->getValueType(0), LHSHi, RHSHi);
812        Result = DAG.getSetCC(ISD::SETEQ, Node->getValueType(0), LHSHi, RHSHi);
813        Result = DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
814                             Result, Tmp1, Tmp2);
815        break;
816      }
817    }
818    break;
819
820  case ISD::MEMSET:
821  case ISD::MEMCPY:
822  case ISD::MEMMOVE: {
823    Tmp1 = LegalizeOp(Node->getOperand(0));      // Chain
824    Tmp2 = LegalizeOp(Node->getOperand(1));      // Pointer
825
826    if (Node->getOpcode() == ISD::MEMSET) {      // memset = ubyte
827      switch (getTypeAction(Node->getOperand(2).getValueType())) {
828      case Expand: assert(0 && "Cannot expand a byte!");
829      case Legal:
830        Tmp3 = LegalizeOp(Node->getOperand(2));
831        break;
832      case Promote:
833        Tmp3 = PromoteOp(Node->getOperand(2));
834        break;
835      }
836    } else {
837      Tmp3 = LegalizeOp(Node->getOperand(2));    // memcpy/move = pointer,
838    }
839
840    SDOperand Tmp4;
841    switch (getTypeAction(Node->getOperand(3).getValueType())) {
842    case Expand: assert(0 && "Cannot expand this yet!");
843    case Legal:
844      Tmp4 = LegalizeOp(Node->getOperand(3));
845      break;
846    case Promote:
847      Tmp4 = PromoteOp(Node->getOperand(3));
848      break;
849    }
850
851    SDOperand Tmp5;
852    switch (getTypeAction(Node->getOperand(4).getValueType())) {  // uint
853    case Expand: assert(0 && "Cannot expand this yet!");
854    case Legal:
855      Tmp5 = LegalizeOp(Node->getOperand(4));
856      break;
857    case Promote:
858      Tmp5 = PromoteOp(Node->getOperand(4));
859      break;
860    }
861
862    switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
863    default: assert(0 && "This action not implemented for this operation!");
864    case TargetLowering::Legal:
865      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
866          Tmp3 != Node->getOperand(2) || Tmp4 != Node->getOperand(3) ||
867          Tmp5 != Node->getOperand(4)) {
868        std::vector<SDOperand> Ops;
869        Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
870        Ops.push_back(Tmp4); Ops.push_back(Tmp5);
871        Result = DAG.getNode(Node->getOpcode(), MVT::Other, Ops);
872      }
873      break;
874    case TargetLowering::Expand: {
875      // Otherwise, the target does not support this operation.  Lower the
876      // operation to an explicit libcall as appropriate.
877      MVT::ValueType IntPtr = TLI.getPointerTy();
878      const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
879      std::vector<std::pair<SDOperand, const Type*> > Args;
880
881      const char *FnName = 0;
882      if (Node->getOpcode() == ISD::MEMSET) {
883        Args.push_back(std::make_pair(Tmp2, IntPtrTy));
884        // Extend the ubyte argument to be an int value for the call.
885        Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Tmp3);
886        Args.push_back(std::make_pair(Tmp3, Type::IntTy));
887        Args.push_back(std::make_pair(Tmp4, IntPtrTy));
888
889        FnName = "memset";
890      } else if (Node->getOpcode() == ISD::MEMCPY ||
891                 Node->getOpcode() == ISD::MEMMOVE) {
892        Args.push_back(std::make_pair(Tmp2, IntPtrTy));
893        Args.push_back(std::make_pair(Tmp3, IntPtrTy));
894        Args.push_back(std::make_pair(Tmp4, IntPtrTy));
895        FnName = Node->getOpcode() == ISD::MEMMOVE ? "memmove" : "memcpy";
896      } else {
897        assert(0 && "Unknown op!");
898      }
899      std::pair<SDOperand,SDOperand> CallResult =
900        TLI.LowerCallTo(Tmp1, Type::VoidTy, false,
901                        DAG.getExternalSymbol(FnName, IntPtr), Args, DAG);
902      Result = LegalizeOp(CallResult.second);
903      break;
904    }
905    case TargetLowering::Custom:
906      std::vector<SDOperand> Ops;
907      Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
908      Ops.push_back(Tmp4); Ops.push_back(Tmp5);
909      Result = DAG.getNode(Node->getOpcode(), MVT::Other, Ops);
910      Result = TLI.LowerOperation(Result);
911      Result = LegalizeOp(Result);
912      break;
913    }
914    break;
915  }
916  case ISD::ADD_PARTS:
917  case ISD::SUB_PARTS:
918  case ISD::SHL_PARTS:
919  case ISD::SRA_PARTS:
920  case ISD::SRL_PARTS: {
921    std::vector<SDOperand> Ops;
922    bool Changed = false;
923    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
924      Ops.push_back(LegalizeOp(Node->getOperand(i)));
925      Changed |= Ops.back() != Node->getOperand(i);
926    }
927    if (Changed)
928      Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Ops);
929
930    // Since these produce multiple values, make sure to remember that we
931    // legalized all of them.
932    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
933      AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
934    return Result.getValue(Op.ResNo);
935  }
936
937    // Binary operators
938  case ISD::ADD:
939  case ISD::SUB:
940  case ISD::MUL:
941  case ISD::MULHS:
942  case ISD::MULHU:
943  case ISD::UDIV:
944  case ISD::SDIV:
945  case ISD::AND:
946  case ISD::OR:
947  case ISD::XOR:
948  case ISD::SHL:
949  case ISD::SRL:
950  case ISD::SRA:
951    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
952    Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
953    if (Tmp1 != Node->getOperand(0) ||
954        Tmp2 != Node->getOperand(1))
955      Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,Tmp2);
956    break;
957
958  case ISD::UREM:
959  case ISD::SREM:
960    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
961    Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
962    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
963    case TargetLowering::Legal:
964      if (Tmp1 != Node->getOperand(0) ||
965          Tmp2 != Node->getOperand(1))
966        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
967                             Tmp2);
968      break;
969    case TargetLowering::Promote:
970    case TargetLowering::Custom:
971      assert(0 && "Cannot promote/custom handle this yet!");
972    case TargetLowering::Expand: {
973      MVT::ValueType VT = Node->getValueType(0);
974      unsigned Opc = (Node->getOpcode() == ISD::UREM) ? ISD::UDIV : ISD::SDIV;
975      Result = DAG.getNode(Opc, VT, Tmp1, Tmp2);
976      Result = DAG.getNode(ISD::MUL, VT, Result, Tmp2);
977      Result = DAG.getNode(ISD::SUB, VT, Tmp1, Result);
978      }
979      break;
980    }
981    break;
982
983    // Unary operators
984  case ISD::FABS:
985  case ISD::FNEG:
986    Tmp1 = LegalizeOp(Node->getOperand(0));
987    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
988    case TargetLowering::Legal:
989      if (Tmp1 != Node->getOperand(0))
990        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
991      break;
992    case TargetLowering::Promote:
993    case TargetLowering::Custom:
994      assert(0 && "Cannot promote/custom handle this yet!");
995    case TargetLowering::Expand:
996      if (Node->getOpcode() == ISD::FNEG) {
997        // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
998        Tmp2 = DAG.getConstantFP(-0.0, Node->getValueType(0));
999        Result = LegalizeOp(DAG.getNode(ISD::SUB, Node->getValueType(0),
1000                                        Tmp2, Tmp1));
1001      } else if (Node->getOpcode() == ISD::FABS) {
1002        // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
1003        MVT::ValueType VT = Node->getValueType(0);
1004        Tmp2 = DAG.getConstantFP(0.0, VT);
1005        Tmp2 = DAG.getSetCC(ISD::SETUGT, TLI.getSetCCResultTy(), Tmp1, Tmp2);
1006        Tmp3 = DAG.getNode(ISD::FNEG, VT, Tmp1);
1007        Result = DAG.getNode(ISD::SELECT, VT, Tmp2, Tmp1, Tmp3);
1008        Result = LegalizeOp(Result);
1009      } else {
1010        assert(0 && "Unreachable!");
1011      }
1012      break;
1013    }
1014    break;
1015
1016    // Conversion operators.  The source and destination have different types.
1017  case ISD::ZERO_EXTEND:
1018  case ISD::SIGN_EXTEND:
1019  case ISD::TRUNCATE:
1020  case ISD::FP_EXTEND:
1021  case ISD::FP_ROUND:
1022  case ISD::FP_TO_SINT:
1023  case ISD::FP_TO_UINT:
1024  case ISD::SINT_TO_FP:
1025  case ISD::UINT_TO_FP:
1026    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1027    case Legal:
1028      Tmp1 = LegalizeOp(Node->getOperand(0));
1029      if (Tmp1 != Node->getOperand(0))
1030        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1031      break;
1032    case Expand:
1033      if (Node->getOpcode() == ISD::SINT_TO_FP ||
1034          Node->getOpcode() == ISD::UINT_TO_FP) {
1035        Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP,
1036                               Node->getValueType(0), Node->getOperand(0));
1037        Result = LegalizeOp(Result);
1038        break;
1039      } else if (Node->getOpcode() == ISD::TRUNCATE) {
1040        // In the expand case, we must be dealing with a truncate, because
1041        // otherwise the result would be larger than the source.
1042        ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
1043
1044        // Since the result is legal, we should just be able to truncate the low
1045        // part of the source.
1046        Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
1047        break;
1048      }
1049      assert(0 && "Shouldn't need to expand other operators here!");
1050
1051    case Promote:
1052      switch (Node->getOpcode()) {
1053      case ISD::ZERO_EXTEND:
1054        Result = PromoteOp(Node->getOperand(0));
1055        // NOTE: Any extend would work here...
1056        Result = DAG.getNode(ISD::ZERO_EXTEND, Op.getValueType(), Result);
1057        Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, Op.getValueType(),
1058                             Result, Node->getOperand(0).getValueType());
1059        break;
1060      case ISD::SIGN_EXTEND:
1061        Result = PromoteOp(Node->getOperand(0));
1062        // NOTE: Any extend would work here...
1063        Result = DAG.getNode(ISD::ZERO_EXTEND, Op.getValueType(), Result);
1064        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1065                             Result, Node->getOperand(0).getValueType());
1066        break;
1067      case ISD::TRUNCATE:
1068        Result = PromoteOp(Node->getOperand(0));
1069        Result = DAG.getNode(ISD::TRUNCATE, Op.getValueType(), Result);
1070        break;
1071      case ISD::FP_EXTEND:
1072        Result = PromoteOp(Node->getOperand(0));
1073        if (Result.getValueType() != Op.getValueType())
1074          // Dynamically dead while we have only 2 FP types.
1075          Result = DAG.getNode(ISD::FP_EXTEND, Op.getValueType(), Result);
1076        break;
1077      case ISD::FP_ROUND:
1078      case ISD::FP_TO_SINT:
1079      case ISD::FP_TO_UINT:
1080        Result = PromoteOp(Node->getOperand(0));
1081        Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
1082        break;
1083      case ISD::SINT_TO_FP:
1084        Result = PromoteOp(Node->getOperand(0));
1085        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1086                             Result, Node->getOperand(0).getValueType());
1087        Result = DAG.getNode(ISD::SINT_TO_FP, Op.getValueType(), Result);
1088        break;
1089      case ISD::UINT_TO_FP:
1090        Result = PromoteOp(Node->getOperand(0));
1091        Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, Result.getValueType(),
1092                             Result, Node->getOperand(0).getValueType());
1093        Result = DAG.getNode(ISD::UINT_TO_FP, Op.getValueType(), Result);
1094        break;
1095      }
1096    }
1097    break;
1098  case ISD::FP_ROUND_INREG:
1099  case ISD::SIGN_EXTEND_INREG:
1100  case ISD::ZERO_EXTEND_INREG: {
1101    Tmp1 = LegalizeOp(Node->getOperand(0));
1102    MVT::ValueType ExtraVT = cast<MVTSDNode>(Node)->getExtraValueType();
1103
1104    // If this operation is not supported, convert it to a shl/shr or load/store
1105    // pair.
1106    switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
1107    default: assert(0 && "This action not supported for this op yet!");
1108    case TargetLowering::Legal:
1109      if (Tmp1 != Node->getOperand(0))
1110        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
1111                             ExtraVT);
1112      break;
1113    case TargetLowering::Expand:
1114      // If this is an integer extend and shifts are supported, do that.
1115      if (Node->getOpcode() == ISD::ZERO_EXTEND_INREG) {
1116        // NOTE: we could fall back on load/store here too for targets without
1117        // AND.  However, it is doubtful that any exist.
1118        // AND out the appropriate bits.
1119        SDOperand Mask =
1120          DAG.getConstant((1ULL << MVT::getSizeInBits(ExtraVT))-1,
1121                          Node->getValueType(0));
1122        Result = DAG.getNode(ISD::AND, Node->getValueType(0),
1123                             Node->getOperand(0), Mask);
1124      } else if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
1125        // NOTE: we could fall back on load/store here too for targets without
1126        // SAR.  However, it is doubtful that any exist.
1127        unsigned BitsDiff = MVT::getSizeInBits(Node->getValueType(0)) -
1128                            MVT::getSizeInBits(ExtraVT);
1129        SDOperand ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
1130        Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
1131                             Node->getOperand(0), ShiftCst);
1132        Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
1133                             Result, ShiftCst);
1134      } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
1135        // The only way we can lower this is to turn it into a STORETRUNC,
1136        // EXTLOAD pair, targetting a temporary location (a stack slot).
1137
1138        // NOTE: there is a choice here between constantly creating new stack
1139        // slots and always reusing the same one.  We currently always create
1140        // new ones, as reuse may inhibit scheduling.
1141        const Type *Ty = MVT::getTypeForValueType(ExtraVT);
1142        unsigned TySize = (unsigned)TLI.getTargetData().getTypeSize(Ty);
1143        unsigned Align  = TLI.getTargetData().getTypeAlignment(Ty);
1144        MachineFunction &MF = DAG.getMachineFunction();
1145        int SSFI =
1146          MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
1147        SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
1148        Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, DAG.getEntryNode(),
1149                             Node->getOperand(0), StackSlot, ExtraVT);
1150        Result = DAG.getNode(ISD::EXTLOAD, Node->getValueType(0),
1151                             Result, StackSlot, ExtraVT);
1152      } else {
1153        assert(0 && "Unknown op");
1154      }
1155      Result = LegalizeOp(Result);
1156      break;
1157    }
1158    break;
1159  }
1160  }
1161
1162  if (!Op.Val->hasOneUse())
1163    AddLegalizedOperand(Op, Result);
1164
1165  return Result;
1166}
1167
1168/// PromoteOp - Given an operation that produces a value in an invalid type,
1169/// promote it to compute the value into a larger type.  The produced value will
1170/// have the correct bits for the low portion of the register, but no guarantee
1171/// is made about the top bits: it may be zero, sign-extended, or garbage.
1172SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
1173  MVT::ValueType VT = Op.getValueType();
1174  MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
1175  assert(getTypeAction(VT) == Promote &&
1176         "Caller should expand or legalize operands that are not promotable!");
1177  assert(NVT > VT && MVT::isInteger(NVT) == MVT::isInteger(VT) &&
1178         "Cannot promote to smaller type!");
1179
1180  std::map<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
1181  if (I != PromotedNodes.end()) return I->second;
1182
1183  SDOperand Tmp1, Tmp2, Tmp3;
1184
1185  SDOperand Result;
1186  SDNode *Node = Op.Val;
1187
1188  // Promotion needs an optimization step to clean up after it, and is not
1189  // careful to avoid operations the target does not support.  Make sure that
1190  // all generated operations are legalized in the next iteration.
1191  NeedsAnotherIteration = true;
1192
1193  switch (Node->getOpcode()) {
1194  default:
1195    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
1196    assert(0 && "Do not know how to promote this operator!");
1197    abort();
1198  case ISD::UNDEF:
1199    Result = DAG.getNode(ISD::UNDEF, NVT);
1200    break;
1201  case ISD::Constant:
1202    Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
1203    assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
1204    break;
1205  case ISD::ConstantFP:
1206    Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
1207    assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
1208    break;
1209  case ISD::CopyFromReg:
1210    Result = DAG.getCopyFromReg(cast<RegSDNode>(Node)->getReg(), NVT,
1211                                Node->getOperand(0));
1212    // Remember that we legalized the chain.
1213    AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1214    break;
1215
1216  case ISD::SETCC:
1217    assert(getTypeAction(TLI.getSetCCResultTy()) == Legal &&
1218           "SetCC type is not legal??");
1219    Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
1220                          TLI.getSetCCResultTy(), Node->getOperand(0),
1221                          Node->getOperand(1));
1222    Result = LegalizeOp(Result);
1223    break;
1224
1225  case ISD::TRUNCATE:
1226    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1227    case Legal:
1228      Result = LegalizeOp(Node->getOperand(0));
1229      assert(Result.getValueType() >= NVT &&
1230             "This truncation doesn't make sense!");
1231      if (Result.getValueType() > NVT)    // Truncate to NVT instead of VT
1232        Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
1233      break;
1234    case Promote:
1235      // The truncation is not required, because we don't guarantee anything
1236      // about high bits anyway.
1237      Result = PromoteOp(Node->getOperand(0));
1238      break;
1239    case Expand:
1240      ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
1241      // Truncate the low part of the expanded value to the result type
1242      Result = DAG.getNode(ISD::TRUNCATE, VT, Tmp1);
1243    }
1244    break;
1245  case ISD::SIGN_EXTEND:
1246  case ISD::ZERO_EXTEND:
1247    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1248    case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
1249    case Legal:
1250      // Input is legal?  Just do extend all the way to the larger type.
1251      Result = LegalizeOp(Node->getOperand(0));
1252      Result = DAG.getNode(Node->getOpcode(), NVT, Result);
1253      break;
1254    case Promote:
1255      // Promote the reg if it's smaller.
1256      Result = PromoteOp(Node->getOperand(0));
1257      // The high bits are not guaranteed to be anything.  Insert an extend.
1258      if (Node->getOpcode() == ISD::SIGN_EXTEND)
1259        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
1260                             Node->getOperand(0).getValueType());
1261      else
1262        Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Result,
1263                             Node->getOperand(0).getValueType());
1264      break;
1265    }
1266    break;
1267
1268  case ISD::FP_EXTEND:
1269    assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
1270  case ISD::FP_ROUND:
1271    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1272    case Expand: assert(0 && "BUG: Cannot expand FP regs!");
1273    case Promote:  assert(0 && "Unreachable with 2 FP types!");
1274    case Legal:
1275      // Input is legal?  Do an FP_ROUND_INREG.
1276      Result = LegalizeOp(Node->getOperand(0));
1277      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1278      break;
1279    }
1280    break;
1281
1282  case ISD::SINT_TO_FP:
1283  case ISD::UINT_TO_FP:
1284    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1285    case Legal:
1286      Result = LegalizeOp(Node->getOperand(0));
1287      // No extra round required here.
1288      Result = DAG.getNode(Node->getOpcode(), NVT, Result);
1289      break;
1290
1291    case Promote:
1292      Result = PromoteOp(Node->getOperand(0));
1293      if (Node->getOpcode() == ISD::SINT_TO_FP)
1294        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1295                             Result, Node->getOperand(0).getValueType());
1296      else
1297        Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, Result.getValueType(),
1298                             Result, Node->getOperand(0).getValueType());
1299      // No extra round required here.
1300      Result = DAG.getNode(Node->getOpcode(), NVT, Result);
1301      break;
1302    case Expand:
1303      Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, NVT,
1304                             Node->getOperand(0));
1305      Result = LegalizeOp(Result);
1306
1307      // Round if we cannot tolerate excess precision.
1308      if (NoExcessFPPrecision)
1309        Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1310      break;
1311    }
1312    break;
1313
1314  case ISD::FP_TO_SINT:
1315  case ISD::FP_TO_UINT:
1316    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1317    case Legal:
1318      Tmp1 = LegalizeOp(Node->getOperand(0));
1319      break;
1320    case Promote:
1321      // The input result is prerounded, so we don't have to do anything
1322      // special.
1323      Tmp1 = PromoteOp(Node->getOperand(0));
1324      break;
1325    case Expand:
1326      assert(0 && "not implemented");
1327    }
1328    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
1329    break;
1330
1331  case ISD::FABS:
1332  case ISD::FNEG:
1333    Tmp1 = PromoteOp(Node->getOperand(0));
1334    assert(Tmp1.getValueType() == NVT);
1335    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
1336    // NOTE: we do not have to do any extra rounding here for
1337    // NoExcessFPPrecision, because we know the input will have the appropriate
1338    // precision, and these operations don't modify precision at all.
1339    break;
1340
1341  case ISD::AND:
1342  case ISD::OR:
1343  case ISD::XOR:
1344  case ISD::ADD:
1345  case ISD::SUB:
1346  case ISD::MUL:
1347    // The input may have strange things in the top bits of the registers, but
1348    // these operations don't care.  They may have wierd bits going out, but
1349    // that too is okay if they are integer operations.
1350    Tmp1 = PromoteOp(Node->getOperand(0));
1351    Tmp2 = PromoteOp(Node->getOperand(1));
1352    assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
1353    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1354
1355    // However, if this is a floating point operation, they will give excess
1356    // precision that we may not be able to tolerate.  If we DO allow excess
1357    // precision, just leave it, otherwise excise it.
1358    // FIXME: Why would we need to round FP ops more than integer ones?
1359    //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
1360    if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
1361      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1362    break;
1363
1364  case ISD::SDIV:
1365  case ISD::SREM:
1366    // These operators require that their input be sign extended.
1367    Tmp1 = PromoteOp(Node->getOperand(0));
1368    Tmp2 = PromoteOp(Node->getOperand(1));
1369    if (MVT::isInteger(NVT)) {
1370      Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1, VT);
1371      Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2, VT);
1372    }
1373    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1374
1375    // Perform FP_ROUND: this is probably overly pessimistic.
1376    if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
1377      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1378    break;
1379
1380  case ISD::UDIV:
1381  case ISD::UREM:
1382    // These operators require that their input be zero extended.
1383    Tmp1 = PromoteOp(Node->getOperand(0));
1384    Tmp2 = PromoteOp(Node->getOperand(1));
1385    assert(MVT::isInteger(NVT) && "Operators don't apply to FP!");
1386    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp1, VT);
1387    Tmp2 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp2, VT);
1388    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1389    break;
1390
1391  case ISD::SHL:
1392    Tmp1 = PromoteOp(Node->getOperand(0));
1393    Tmp2 = LegalizeOp(Node->getOperand(1));
1394    Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Tmp2);
1395    break;
1396  case ISD::SRA:
1397    // The input value must be properly sign extended.
1398    Tmp1 = PromoteOp(Node->getOperand(0));
1399    Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1, VT);
1400    Tmp2 = LegalizeOp(Node->getOperand(1));
1401    Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Tmp2);
1402    break;
1403  case ISD::SRL:
1404    // The input value must be properly zero extended.
1405    Tmp1 = PromoteOp(Node->getOperand(0));
1406    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp1, VT);
1407    Tmp2 = LegalizeOp(Node->getOperand(1));
1408    Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Tmp2);
1409    break;
1410  case ISD::LOAD:
1411    Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
1412    Tmp2 = LegalizeOp(Node->getOperand(1));   // Legalize the pointer.
1413    // FIXME: When the DAG combiner exists, change this to use EXTLOAD!
1414    if (MVT::isInteger(NVT))
1415      Result = DAG.getNode(ISD::ZEXTLOAD, NVT, Tmp1, Tmp2, VT);
1416    else
1417      Result = DAG.getNode(ISD::EXTLOAD, NVT, Tmp1, Tmp2, VT);
1418
1419    // Remember that we legalized the chain.
1420    AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1421    break;
1422  case ISD::SELECT:
1423    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1424    case Expand: assert(0 && "It's impossible to expand bools");
1425    case Legal:
1426      Tmp1 = LegalizeOp(Node->getOperand(0));// Legalize the condition.
1427      break;
1428    case Promote:
1429      Tmp1 = PromoteOp(Node->getOperand(0)); // Promote the condition.
1430      break;
1431    }
1432    Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
1433    Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
1434    Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2, Tmp3);
1435    break;
1436  case ISD::CALL: {
1437    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1438    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
1439
1440    std::vector<SDOperand> Ops;
1441    for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i)
1442      Ops.push_back(LegalizeOp(Node->getOperand(i)));
1443
1444    assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
1445           "Can only promote single result calls");
1446    std::vector<MVT::ValueType> RetTyVTs;
1447    RetTyVTs.reserve(2);
1448    RetTyVTs.push_back(NVT);
1449    RetTyVTs.push_back(MVT::Other);
1450    SDNode *NC = DAG.getCall(RetTyVTs, Tmp1, Tmp2, Ops);
1451    Result = SDOperand(NC, 0);
1452
1453    // Insert the new chain mapping.
1454    AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1455    break;
1456  }
1457  }
1458
1459  assert(Result.Val && "Didn't set a result!");
1460  AddPromotedOperand(Op, Result);
1461  return Result;
1462}
1463
1464/// ExpandAddSub - Find a clever way to expand this add operation into
1465/// subcomponents.
1466void SelectionDAGLegalize::
1467ExpandByParts(unsigned NodeOp, SDOperand LHS, SDOperand RHS,
1468              SDOperand &Lo, SDOperand &Hi) {
1469  // Expand the subcomponents.
1470  SDOperand LHSL, LHSH, RHSL, RHSH;
1471  ExpandOp(LHS, LHSL, LHSH);
1472  ExpandOp(RHS, RHSL, RHSH);
1473
1474  // FIXME: this should be moved to the dag combiner someday.
1475  if (NodeOp == ISD::ADD_PARTS || NodeOp == ISD::SUB_PARTS)
1476    if (LHSL.getValueType() == MVT::i32) {
1477      SDOperand LowEl;
1478      if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHSL))
1479        if (C->getValue() == 0)
1480          LowEl = RHSL;
1481      if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHSL))
1482        if (C->getValue() == 0)
1483          LowEl = LHSL;
1484      if (LowEl.Val) {
1485        // Turn this into an add/sub of the high part only.
1486        SDOperand HiEl =
1487          DAG.getNode(NodeOp == ISD::ADD_PARTS ? ISD::ADD : ISD::SUB,
1488                      LowEl.getValueType(), LHSH, RHSH);
1489        Lo = LowEl;
1490        Hi = HiEl;
1491        return;
1492      }
1493    }
1494
1495  std::vector<SDOperand> Ops;
1496  Ops.push_back(LHSL);
1497  Ops.push_back(LHSH);
1498  Ops.push_back(RHSL);
1499  Ops.push_back(RHSH);
1500  Lo = DAG.getNode(NodeOp, LHSL.getValueType(), Ops);
1501  Hi = Lo.getValue(1);
1502}
1503
1504void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
1505                                            SDOperand Op, SDOperand Amt,
1506                                            SDOperand &Lo, SDOperand &Hi) {
1507  // Expand the subcomponents.
1508  SDOperand LHSL, LHSH;
1509  ExpandOp(Op, LHSL, LHSH);
1510
1511  std::vector<SDOperand> Ops;
1512  Ops.push_back(LHSL);
1513  Ops.push_back(LHSH);
1514  Ops.push_back(Amt);
1515  Lo = DAG.getNode(NodeOp, LHSL.getValueType(), Ops);
1516  Hi = Lo.getValue(1);
1517}
1518
1519
1520/// ExpandShift - Try to find a clever way to expand this shift operation out to
1521/// smaller elements.  If we can't find a way that is more efficient than a
1522/// libcall on this target, return false.  Otherwise, return true with the
1523/// low-parts expanded into Lo and Hi.
1524bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDOperand Op,SDOperand Amt,
1525                                       SDOperand &Lo, SDOperand &Hi) {
1526  assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
1527         "This is not a shift!");
1528
1529  MVT::ValueType NVT = TLI.getTypeToTransformTo(Op.getValueType());
1530  SDOperand ShAmt = LegalizeOp(Amt);
1531  MVT::ValueType ShTy = ShAmt.getValueType();
1532  unsigned VTBits = MVT::getSizeInBits(Op.getValueType());
1533  unsigned NVTBits = MVT::getSizeInBits(NVT);
1534
1535  // Handle the case when Amt is an immediate.  Other cases are currently broken
1536  // and are disabled.
1537  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Amt.Val)) {
1538    unsigned Cst = CN->getValue();
1539    // Expand the incoming operand to be shifted, so that we have its parts
1540    SDOperand InL, InH;
1541    ExpandOp(Op, InL, InH);
1542    switch(Opc) {
1543    case ISD::SHL:
1544      if (Cst > VTBits) {
1545        Lo = DAG.getConstant(0, NVT);
1546        Hi = DAG.getConstant(0, NVT);
1547      } else if (Cst > NVTBits) {
1548        Lo = DAG.getConstant(0, NVT);
1549        Hi = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst-NVTBits,ShTy));
1550      } else if (Cst == NVTBits) {
1551        Lo = DAG.getConstant(0, NVT);
1552        Hi = InL;
1553      } else {
1554        Lo = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst, ShTy));
1555        Hi = DAG.getNode(ISD::OR, NVT,
1556           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(Cst, ShTy)),
1557           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(NVTBits-Cst, ShTy)));
1558      }
1559      return true;
1560    case ISD::SRL:
1561      if (Cst > VTBits) {
1562        Lo = DAG.getConstant(0, NVT);
1563        Hi = DAG.getConstant(0, NVT);
1564      } else if (Cst > NVTBits) {
1565        Lo = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst-NVTBits,ShTy));
1566        Hi = DAG.getConstant(0, NVT);
1567      } else if (Cst == NVTBits) {
1568        Lo = InH;
1569        Hi = DAG.getConstant(0, NVT);
1570      } else {
1571        Lo = DAG.getNode(ISD::OR, NVT,
1572           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
1573           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
1574        Hi = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst, ShTy));
1575      }
1576      return true;
1577    case ISD::SRA:
1578      if (Cst > VTBits) {
1579        Hi = Lo = DAG.getNode(ISD::SRA, NVT, InH,
1580                              DAG.getConstant(NVTBits-1, ShTy));
1581      } else if (Cst > NVTBits) {
1582        Lo = DAG.getNode(ISD::SRA, NVT, InH,
1583                           DAG.getConstant(Cst-NVTBits, ShTy));
1584        Hi = DAG.getNode(ISD::SRA, NVT, InH,
1585                              DAG.getConstant(NVTBits-1, ShTy));
1586      } else if (Cst == NVTBits) {
1587        Lo = InH;
1588        Hi = DAG.getNode(ISD::SRA, NVT, InH,
1589                              DAG.getConstant(NVTBits-1, ShTy));
1590      } else {
1591        Lo = DAG.getNode(ISD::OR, NVT,
1592           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
1593           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
1594        Hi = DAG.getNode(ISD::SRA, NVT, InH, DAG.getConstant(Cst, ShTy));
1595      }
1596      return true;
1597    }
1598  }
1599  // FIXME: The following code for expanding shifts using ISD::SELECT is buggy,
1600  // so disable it for now.  Currently targets are handling this via SHL_PARTS
1601  // and friends.
1602  return false;
1603
1604  // If we have an efficient select operation (or if the selects will all fold
1605  // away), lower to some complex code, otherwise just emit the libcall.
1606  if (TLI.getOperationAction(ISD::SELECT, NVT) != TargetLowering::Legal &&
1607      !isa<ConstantSDNode>(Amt))
1608    return false;
1609
1610  SDOperand InL, InH;
1611  ExpandOp(Op, InL, InH);
1612  SDOperand NAmt = DAG.getNode(ISD::SUB, ShTy,           // NAmt = 32-ShAmt
1613                               DAG.getConstant(NVTBits, ShTy), ShAmt);
1614
1615  // Compare the unmasked shift amount against 32.
1616  SDOperand Cond = DAG.getSetCC(ISD::SETGE, TLI.getSetCCResultTy(), ShAmt,
1617                                DAG.getConstant(NVTBits, ShTy));
1618
1619  if (TLI.getShiftAmountFlavor() != TargetLowering::Mask) {
1620    ShAmt = DAG.getNode(ISD::AND, ShTy, ShAmt,             // ShAmt &= 31
1621                        DAG.getConstant(NVTBits-1, ShTy));
1622    NAmt  = DAG.getNode(ISD::AND, ShTy, NAmt,              // NAmt &= 31
1623                        DAG.getConstant(NVTBits-1, ShTy));
1624  }
1625
1626  if (Opc == ISD::SHL) {
1627    SDOperand T1 = DAG.getNode(ISD::OR, NVT,// T1 = (Hi << Amt) | (Lo >> NAmt)
1628                               DAG.getNode(ISD::SHL, NVT, InH, ShAmt),
1629                               DAG.getNode(ISD::SRL, NVT, InL, NAmt));
1630    SDOperand T2 = DAG.getNode(ISD::SHL, NVT, InL, ShAmt); // T2 = Lo << Amt&31
1631
1632    Hi = DAG.getNode(ISD::SELECT, NVT, Cond, T2, T1);
1633    Lo = DAG.getNode(ISD::SELECT, NVT, Cond, DAG.getConstant(0, NVT), T2);
1634  } else {
1635    SDOperand HiLoPart = DAG.getNode(ISD::SELECT, NVT,
1636                                     DAG.getSetCC(ISD::SETEQ,
1637                                                  TLI.getSetCCResultTy(), NAmt,
1638                                                  DAG.getConstant(32, ShTy)),
1639                                     DAG.getConstant(0, NVT),
1640                                     DAG.getNode(ISD::SHL, NVT, InH, NAmt));
1641    SDOperand T1 = DAG.getNode(ISD::OR, NVT,// T1 = (Hi << NAmt) | (Lo >> Amt)
1642                               HiLoPart,
1643                               DAG.getNode(ISD::SRL, NVT, InL, ShAmt));
1644    SDOperand T2 = DAG.getNode(Opc, NVT, InH, ShAmt);  // T2 = InH >> ShAmt&31
1645
1646    SDOperand HiPart;
1647    if (Opc == ISD::SRA)
1648      HiPart = DAG.getNode(ISD::SRA, NVT, InH,
1649                           DAG.getConstant(NVTBits-1, ShTy));
1650    else
1651      HiPart = DAG.getConstant(0, NVT);
1652    Lo = DAG.getNode(ISD::SELECT, NVT, Cond, T2, T1);
1653    Hi = DAG.getNode(ISD::SELECT, NVT, Cond, HiPart, T2);
1654  }
1655  return true;
1656}
1657
1658/// FindLatestAdjCallStackDown - Scan up the dag to find the latest (highest
1659/// NodeDepth) node that is an AdjCallStackDown operation and occurs later than
1660/// Found.
1661static void FindLatestAdjCallStackDown(SDNode *Node, SDNode *&Found) {
1662  if (Node->getNodeDepth() <= Found->getNodeDepth()) return;
1663
1664  // If we found an ADJCALLSTACKDOWN, we already know this node occurs later
1665  // than the Found node. Just remember this node and return.
1666  if (Node->getOpcode() == ISD::ADJCALLSTACKDOWN) {
1667    Found = Node;
1668    return;
1669  }
1670
1671  // Otherwise, scan the operands of Node to see if any of them is a call.
1672  assert(Node->getNumOperands() != 0 &&
1673         "All leaves should have depth equal to the entry node!");
1674  for (unsigned i = 0, e = Node->getNumOperands()-1; i != e; ++i)
1675    FindLatestAdjCallStackDown(Node->getOperand(i).Val, Found);
1676
1677  // Tail recurse for the last iteration.
1678  FindLatestAdjCallStackDown(Node->getOperand(Node->getNumOperands()-1).Val,
1679                             Found);
1680}
1681
1682
1683/// FindEarliestAdjCallStackUp - Scan down the dag to find the earliest (lowest
1684/// NodeDepth) node that is an AdjCallStackUp operation and occurs more recent
1685/// than Found.
1686static void FindEarliestAdjCallStackUp(SDNode *Node, SDNode *&Found) {
1687  if (Found && Node->getNodeDepth() >= Found->getNodeDepth()) return;
1688
1689  // If we found an ADJCALLSTACKUP, we already know this node occurs earlier
1690  // than the Found node. Just remember this node and return.
1691  if (Node->getOpcode() == ISD::ADJCALLSTACKUP) {
1692    Found = Node;
1693    return;
1694  }
1695
1696  // Otherwise, scan the operands of Node to see if any of them is a call.
1697  SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
1698  if (UI == E) return;
1699  for (--E; UI != E; ++UI)
1700    FindEarliestAdjCallStackUp(*UI, Found);
1701
1702  // Tail recurse for the last iteration.
1703  FindEarliestAdjCallStackUp(*UI, Found);
1704}
1705
1706/// FindAdjCallStackUp - Given a chained node that is part of a call sequence,
1707/// find the ADJCALLSTACKUP node that terminates the call sequence.
1708static SDNode *FindAdjCallStackUp(SDNode *Node) {
1709  if (Node->getOpcode() == ISD::ADJCALLSTACKUP)
1710    return Node;
1711  if (Node->use_empty())
1712    return 0;   // No adjcallstackup
1713
1714  if (Node->hasOneUse())  // Simple case, only has one user to check.
1715    return FindAdjCallStackUp(*Node->use_begin());
1716
1717  SDOperand TheChain(Node, Node->getNumValues()-1);
1718  assert(TheChain.getValueType() == MVT::Other && "Is not a token chain!");
1719
1720  for (SDNode::use_iterator UI = Node->use_begin(),
1721         E = Node->use_end(); ; ++UI) {
1722    assert(UI != E && "Didn't find a user of the tokchain, no ADJCALLSTACKUP!");
1723
1724    // Make sure to only follow users of our token chain.
1725    SDNode *User = *UI;
1726    for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
1727      if (User->getOperand(i) == TheChain)
1728        return FindAdjCallStackUp(User);
1729  }
1730  assert(0 && "Unreachable");
1731  abort();
1732}
1733
1734/// FindInputOutputChains - If we are replacing an operation with a call we need
1735/// to find the call that occurs before and the call that occurs after it to
1736/// properly serialize the calls in the block.
1737static SDOperand FindInputOutputChains(SDNode *OpNode, SDNode *&OutChain,
1738                                       SDOperand Entry) {
1739  SDNode *LatestAdjCallStackDown = Entry.Val;
1740  SDNode *LatestAdjCallStackUp = 0;
1741  FindLatestAdjCallStackDown(OpNode, LatestAdjCallStackDown);
1742  //std::cerr << "Found node: "; LatestAdjCallStackDown->dump(); std::cerr <<"\n";
1743
1744  // It is possible that no ISD::ADJCALLSTACKDOWN was found because there is no
1745  // previous call in the function.  LatestCallStackDown may in that case be
1746  // the entry node itself.  Do not attempt to find a matching ADJCALLSTACKUP
1747  // unless LatestCallStackDown is an ADJCALLSTACKDOWN.
1748  if (LatestAdjCallStackDown->getOpcode() == ISD::ADJCALLSTACKDOWN)
1749    LatestAdjCallStackUp = FindAdjCallStackUp(LatestAdjCallStackDown);
1750  else
1751    LatestAdjCallStackUp = Entry.Val;
1752  assert(LatestAdjCallStackUp && "NULL return from FindAdjCallStackUp");
1753
1754  SDNode *EarliestAdjCallStackUp = 0;
1755  FindEarliestAdjCallStackUp(OpNode, EarliestAdjCallStackUp);
1756
1757  if (EarliestAdjCallStackUp) {
1758    //std::cerr << "Found node: ";
1759    //EarliestAdjCallStackUp->dump(); std::cerr <<"\n";
1760  }
1761
1762  return SDOperand(LatestAdjCallStackUp, 0);
1763}
1764
1765
1766
1767// ExpandLibCall - Expand a node into a call to a libcall.  If the result value
1768// does not fit into a register, return the lo part and set the hi part to the
1769// by-reg argument.  If it does fit into a single register, return the result
1770// and leave the Hi part unset.
1771SDOperand SelectionDAGLegalize::ExpandLibCall(const char *Name, SDNode *Node,
1772                                              SDOperand &Hi) {
1773  SDNode *OutChain;
1774  SDOperand InChain = FindInputOutputChains(Node, OutChain,
1775                                            DAG.getEntryNode());
1776  if (InChain.Val == 0)
1777    InChain = DAG.getEntryNode();
1778
1779  TargetLowering::ArgListTy Args;
1780  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1781    MVT::ValueType ArgVT = Node->getOperand(i).getValueType();
1782    const Type *ArgTy = MVT::getTypeForValueType(ArgVT);
1783    Args.push_back(std::make_pair(Node->getOperand(i), ArgTy));
1784  }
1785  SDOperand Callee = DAG.getExternalSymbol(Name, TLI.getPointerTy());
1786
1787  // We don't care about token chains for libcalls.  We just use the entry
1788  // node as our input and ignore the output chain.  This allows us to place
1789  // calls wherever we need them to satisfy data dependences.
1790  const Type *RetTy = MVT::getTypeForValueType(Node->getValueType(0));
1791  SDOperand Result = TLI.LowerCallTo(InChain, RetTy, false, Callee,
1792                                     Args, DAG).first;
1793  switch (getTypeAction(Result.getValueType())) {
1794  default: assert(0 && "Unknown thing");
1795  case Legal:
1796    return Result;
1797  case Promote:
1798    assert(0 && "Cannot promote this yet!");
1799  case Expand:
1800    SDOperand Lo;
1801    ExpandOp(Result, Lo, Hi);
1802    return Lo;
1803  }
1804}
1805
1806
1807/// ExpandIntToFP - Expand a [US]INT_TO_FP operation, assuming that the
1808/// destination type is legal.
1809SDOperand SelectionDAGLegalize::
1810ExpandIntToFP(bool isSigned, MVT::ValueType DestTy, SDOperand Source) {
1811  assert(getTypeAction(DestTy) == Legal && "Destination type is not legal!");
1812  assert(getTypeAction(Source.getValueType()) == Expand &&
1813         "This is not an expansion!");
1814  assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
1815
1816  SDNode *OutChain;
1817  SDOperand InChain = FindInputOutputChains(Source.Val, OutChain,
1818                                            DAG.getEntryNode());
1819
1820  const char *FnName = 0;
1821  if (isSigned) {
1822    if (DestTy == MVT::f32)
1823      FnName = "__floatdisf";
1824    else {
1825      assert(DestTy == MVT::f64 && "Unknown fp value type!");
1826      FnName = "__floatdidf";
1827    }
1828  } else {
1829    // If this is unsigned, and not supported, first perform the conversion to
1830    // signed, then adjust the result if the sign bit is set.
1831    SDOperand SignedConv = ExpandIntToFP(false, DestTy, Source);
1832
1833    assert(0 && "Unsigned casts not supported yet!");
1834  }
1835  SDOperand Callee = DAG.getExternalSymbol(FnName, TLI.getPointerTy());
1836
1837  TargetLowering::ArgListTy Args;
1838  const Type *ArgTy = MVT::getTypeForValueType(Source.getValueType());
1839  Args.push_back(std::make_pair(Source, ArgTy));
1840
1841  // We don't care about token chains for libcalls.  We just use the entry
1842  // node as our input and ignore the output chain.  This allows us to place
1843  // calls wherever we need them to satisfy data dependences.
1844  const Type *RetTy = MVT::getTypeForValueType(DestTy);
1845  return TLI.LowerCallTo(InChain, RetTy, false, Callee, Args, DAG).first;
1846
1847}
1848
1849
1850
1851/// ExpandOp - Expand the specified SDOperand into its two component pieces
1852/// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
1853/// LegalizeNodes map is filled in for any results that are not expanded, the
1854/// ExpandedNodes map is filled in for any results that are expanded, and the
1855/// Lo/Hi values are returned.
1856void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
1857  MVT::ValueType VT = Op.getValueType();
1858  MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
1859  SDNode *Node = Op.Val;
1860  assert(getTypeAction(VT) == Expand && "Not an expanded type!");
1861  assert(MVT::isInteger(VT) && "Cannot expand FP values!");
1862  assert(MVT::isInteger(NVT) && NVT < VT &&
1863         "Cannot expand to FP value or to larger int value!");
1864
1865  // If there is more than one use of this, see if we already expanded it.
1866  // There is no use remembering values that only have a single use, as the map
1867  // entries will never be reused.
1868  if (!Node->hasOneUse()) {
1869    std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
1870      = ExpandedNodes.find(Op);
1871    if (I != ExpandedNodes.end()) {
1872      Lo = I->second.first;
1873      Hi = I->second.second;
1874      return;
1875    }
1876  }
1877
1878  // Expanding to multiple registers needs to perform an optimization step, and
1879  // is not careful to avoid operations the target does not support.  Make sure
1880  // that all generated operations are legalized in the next iteration.
1881  NeedsAnotherIteration = true;
1882
1883  switch (Node->getOpcode()) {
1884  default:
1885    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
1886    assert(0 && "Do not know how to expand this operator!");
1887    abort();
1888  case ISD::UNDEF:
1889    Lo = DAG.getNode(ISD::UNDEF, NVT);
1890    Hi = DAG.getNode(ISD::UNDEF, NVT);
1891    break;
1892  case ISD::Constant: {
1893    uint64_t Cst = cast<ConstantSDNode>(Node)->getValue();
1894    Lo = DAG.getConstant(Cst, NVT);
1895    Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
1896    break;
1897  }
1898
1899  case ISD::CopyFromReg: {
1900    unsigned Reg = cast<RegSDNode>(Node)->getReg();
1901    // Aggregate register values are always in consequtive pairs.
1902    Lo = DAG.getCopyFromReg(Reg, NVT, Node->getOperand(0));
1903    Hi = DAG.getCopyFromReg(Reg+1, NVT, Lo.getValue(1));
1904
1905    // Remember that we legalized the chain.
1906    AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
1907
1908    assert(isTypeLegal(NVT) && "Cannot expand this multiple times yet!");
1909    break;
1910  }
1911
1912  case ISD::BUILD_PAIR:
1913    // Legalize both operands.  FIXME: in the future we should handle the case
1914    // where the two elements are not legal.
1915    assert(isTypeLegal(NVT) && "Cannot expand this multiple times yet!");
1916    Lo = LegalizeOp(Node->getOperand(0));
1917    Hi = LegalizeOp(Node->getOperand(1));
1918    break;
1919
1920  case ISD::LOAD: {
1921    SDOperand Ch = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
1922    SDOperand Ptr = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1923    Lo = DAG.getLoad(NVT, Ch, Ptr);
1924
1925    // Increment the pointer to the other half.
1926    unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
1927    Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
1928                      getIntPtrConstant(IncrementSize));
1929    Hi = DAG.getLoad(NVT, Ch, Ptr);
1930
1931    // Build a factor node to remember that this load is independent of the
1932    // other one.
1933    SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
1934                               Hi.getValue(1));
1935
1936    // Remember that we legalized the chain.
1937    AddLegalizedOperand(Op.getValue(1), TF);
1938    if (!TLI.isLittleEndian())
1939      std::swap(Lo, Hi);
1940    break;
1941  }
1942  case ISD::CALL: {
1943    SDOperand Chain  = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1944    SDOperand Callee = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
1945
1946    bool Changed = false;
1947    std::vector<SDOperand> Ops;
1948    for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i) {
1949      Ops.push_back(LegalizeOp(Node->getOperand(i)));
1950      Changed |= Ops.back() != Node->getOperand(i);
1951    }
1952
1953    assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
1954           "Can only expand a call once so far, not i64 -> i16!");
1955
1956    std::vector<MVT::ValueType> RetTyVTs;
1957    RetTyVTs.reserve(3);
1958    RetTyVTs.push_back(NVT);
1959    RetTyVTs.push_back(NVT);
1960    RetTyVTs.push_back(MVT::Other);
1961    SDNode *NC = DAG.getCall(RetTyVTs, Chain, Callee, Ops);
1962    Lo = SDOperand(NC, 0);
1963    Hi = SDOperand(NC, 1);
1964
1965    // Insert the new chain mapping.
1966    AddLegalizedOperand(Op.getValue(1), Hi.getValue(2));
1967    break;
1968  }
1969  case ISD::AND:
1970  case ISD::OR:
1971  case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
1972    SDOperand LL, LH, RL, RH;
1973    ExpandOp(Node->getOperand(0), LL, LH);
1974    ExpandOp(Node->getOperand(1), RL, RH);
1975    Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
1976    Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
1977    break;
1978  }
1979  case ISD::SELECT: {
1980    SDOperand C, LL, LH, RL, RH;
1981
1982    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1983    case Expand: assert(0 && "It's impossible to expand bools");
1984    case Legal:
1985      C = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
1986      break;
1987    case Promote:
1988      C = PromoteOp(Node->getOperand(0));  // Promote the condition.
1989      break;
1990    }
1991    ExpandOp(Node->getOperand(1), LL, LH);
1992    ExpandOp(Node->getOperand(2), RL, RH);
1993    Lo = DAG.getNode(ISD::SELECT, NVT, C, LL, RL);
1994    Hi = DAG.getNode(ISD::SELECT, NVT, C, LH, RH);
1995    break;
1996  }
1997  case ISD::SIGN_EXTEND: {
1998    SDOperand In;
1999    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2000    case Expand: assert(0 && "expand-expand not implemented yet!");
2001    case Legal: In = LegalizeOp(Node->getOperand(0)); break;
2002    case Promote:
2003      In = PromoteOp(Node->getOperand(0));
2004      // Emit the appropriate sign_extend_inreg to get the value we want.
2005      In = DAG.getNode(ISD::SIGN_EXTEND_INREG, In.getValueType(), In,
2006                       Node->getOperand(0).getValueType());
2007      break;
2008    }
2009
2010    // The low part is just a sign extension of the input (which degenerates to
2011    // a copy).
2012    Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, In);
2013
2014    // The high part is obtained by SRA'ing all but one of the bits of the lo
2015    // part.
2016    unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
2017    Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1,
2018                                                       TLI.getShiftAmountTy()));
2019    break;
2020  }
2021  case ISD::ZERO_EXTEND: {
2022    SDOperand In;
2023    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2024    case Expand: assert(0 && "expand-expand not implemented yet!");
2025    case Legal: In = LegalizeOp(Node->getOperand(0)); break;
2026    case Promote:
2027      In = PromoteOp(Node->getOperand(0));
2028      // Emit the appropriate zero_extend_inreg to get the value we want.
2029      In = DAG.getNode(ISD::ZERO_EXTEND_INREG, In.getValueType(), In,
2030                       Node->getOperand(0).getValueType());
2031      break;
2032    }
2033
2034    // The low part is just a zero extension of the input (which degenerates to
2035    // a copy).
2036    Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, In);
2037
2038    // The high part is just a zero.
2039    Hi = DAG.getConstant(0, NVT);
2040    break;
2041  }
2042    // These operators cannot be expanded directly, emit them as calls to
2043    // library functions.
2044  case ISD::FP_TO_SINT:
2045    if (Node->getOperand(0).getValueType() == MVT::f32)
2046      Lo = ExpandLibCall("__fixsfdi", Node, Hi);
2047    else
2048      Lo = ExpandLibCall("__fixdfdi", Node, Hi);
2049    break;
2050  case ISD::FP_TO_UINT:
2051    if (Node->getOperand(0).getValueType() == MVT::f32)
2052      Lo = ExpandLibCall("__fixunssfdi", Node, Hi);
2053    else
2054      Lo = ExpandLibCall("__fixunsdfdi", Node, Hi);
2055    break;
2056
2057  case ISD::SHL:
2058    // If we can emit an efficient shift operation, do so now.
2059    if (ExpandShift(ISD::SHL, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
2060      break;
2061
2062    // If this target supports SHL_PARTS, use it.
2063    if (TLI.getOperationAction(ISD::SHL_PARTS, NVT) == TargetLowering::Legal) {
2064      ExpandShiftParts(ISD::SHL_PARTS, Node->getOperand(0), Node->getOperand(1),
2065                       Lo, Hi);
2066      break;
2067    }
2068
2069    // Otherwise, emit a libcall.
2070    Lo = ExpandLibCall("__ashldi3", Node, Hi);
2071    break;
2072
2073  case ISD::SRA:
2074    // If we can emit an efficient shift operation, do so now.
2075    if (ExpandShift(ISD::SRA, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
2076      break;
2077
2078    // If this target supports SRA_PARTS, use it.
2079    if (TLI.getOperationAction(ISD::SRA_PARTS, NVT) == TargetLowering::Legal) {
2080      ExpandShiftParts(ISD::SRA_PARTS, Node->getOperand(0), Node->getOperand(1),
2081                       Lo, Hi);
2082      break;
2083    }
2084
2085    // Otherwise, emit a libcall.
2086    Lo = ExpandLibCall("__ashrdi3", Node, Hi);
2087    break;
2088  case ISD::SRL:
2089    // If we can emit an efficient shift operation, do so now.
2090    if (ExpandShift(ISD::SRL, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
2091      break;
2092
2093    // If this target supports SRL_PARTS, use it.
2094    if (TLI.getOperationAction(ISD::SRL_PARTS, NVT) == TargetLowering::Legal) {
2095      ExpandShiftParts(ISD::SRL_PARTS, Node->getOperand(0), Node->getOperand(1),
2096                       Lo, Hi);
2097      break;
2098    }
2099
2100    // Otherwise, emit a libcall.
2101    Lo = ExpandLibCall("__lshrdi3", Node, Hi);
2102    break;
2103
2104  case ISD::ADD:
2105    ExpandByParts(ISD::ADD_PARTS, Node->getOperand(0), Node->getOperand(1),
2106                  Lo, Hi);
2107    break;
2108  case ISD::SUB:
2109    ExpandByParts(ISD::SUB_PARTS, Node->getOperand(0), Node->getOperand(1),
2110                  Lo, Hi);
2111    break;
2112  case ISD::MUL: {
2113    if (TLI.getOperationAction(ISD::MULHU, NVT) == TargetLowering::Legal) {
2114      SDOperand LL, LH, RL, RH;
2115      ExpandOp(Node->getOperand(0), LL, LH);
2116      ExpandOp(Node->getOperand(1), RL, RH);
2117      Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
2118      RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
2119      LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
2120      Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
2121      Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
2122      Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
2123    } else {
2124      Lo = ExpandLibCall("__muldi3" , Node, Hi); break;
2125    }
2126    break;
2127  }
2128  case ISD::SDIV: Lo = ExpandLibCall("__divdi3" , Node, Hi); break;
2129  case ISD::UDIV: Lo = ExpandLibCall("__udivdi3", Node, Hi); break;
2130  case ISD::SREM: Lo = ExpandLibCall("__moddi3" , Node, Hi); break;
2131  case ISD::UREM: Lo = ExpandLibCall("__umoddi3", Node, Hi); break;
2132  }
2133
2134  // Remember in a map if the values will be reused later.
2135  if (!Node->hasOneUse()) {
2136    bool isNew = ExpandedNodes.insert(std::make_pair(Op,
2137                                            std::make_pair(Lo, Hi))).second;
2138    assert(isNew && "Value already expanded?!?");
2139  }
2140}
2141
2142
2143// SelectionDAG::Legalize - This is the entry point for the file.
2144//
2145void SelectionDAG::Legalize() {
2146  /// run - This is the main entry point to this class.
2147  ///
2148  SelectionDAGLegalize(*this).Run();
2149}
2150
2151