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