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