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