LegalizeDAG.cpp revision e34b396ab7d28469bf3d9679a748b643d8e30458
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(TargetLowering &TLI, 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  bool ExpandShift(unsigned Opc, SDOperand Op, SDOperand Amt,
123                   SDOperand &Lo, SDOperand &Hi);
124
125  SDOperand getIntPtrConstant(uint64_t Val) {
126    return DAG.getConstant(Val, TLI.getPointerTy());
127  }
128};
129}
130
131
132SelectionDAGLegalize::SelectionDAGLegalize(TargetLowering &tli,
133                                           SelectionDAG &dag)
134  : TLI(tli), DAG(dag), ValueTypeActions(TLI.getValueTypeActions()) {
135  assert(MVT::LAST_VALUETYPE <= 16 &&
136         "Too many value types for ValueTypeActions to hold!");
137}
138
139void SelectionDAGLegalize::LegalizeDAG() {
140  SDOperand OldRoot = DAG.getRoot();
141  SDOperand NewRoot = LegalizeOp(OldRoot);
142  DAG.setRoot(NewRoot);
143
144  ExpandedNodes.clear();
145  LegalizedNodes.clear();
146  PromotedNodes.clear();
147
148  // Remove dead nodes now.
149  DAG.RemoveDeadNodes(OldRoot.Val);
150}
151
152SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
153  assert(getTypeAction(Op.getValueType()) == Legal &&
154         "Caller should expand or promote operands that are not legal!");
155
156  // If this operation defines any values that cannot be represented in a
157  // register on this target, make sure to expand or promote them.
158  if (Op.Val->getNumValues() > 1) {
159    for (unsigned i = 0, e = Op.Val->getNumValues(); i != e; ++i)
160      switch (getTypeAction(Op.Val->getValueType(i))) {
161      case Legal: break;  // Nothing to do.
162      case Expand: {
163        SDOperand T1, T2;
164        ExpandOp(Op.getValue(i), T1, T2);
165        assert(LegalizedNodes.count(Op) &&
166               "Expansion didn't add legal operands!");
167        return LegalizedNodes[Op];
168      }
169      case Promote:
170        PromoteOp(Op.getValue(i));
171        assert(LegalizedNodes.count(Op) &&
172               "Expansion didn't add legal operands!");
173        return LegalizedNodes[Op];
174      }
175  }
176
177  std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
178  if (I != LegalizedNodes.end()) return I->second;
179
180  SDOperand Tmp1, Tmp2, Tmp3;
181
182  SDOperand Result = Op;
183  SDNode *Node = Op.Val;
184
185  switch (Node->getOpcode()) {
186  default:
187    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
188    assert(0 && "Do not know how to legalize this operator!");
189    abort();
190  case ISD::EntryToken:
191  case ISD::FrameIndex:
192  case ISD::GlobalAddress:
193  case ISD::ExternalSymbol:
194  case ISD::ConstantPool:           // Nothing to do.
195    assert(getTypeAction(Node->getValueType(0)) == Legal &&
196           "This must be legal!");
197    break;
198  case ISD::CopyFromReg:
199    Tmp1 = LegalizeOp(Node->getOperand(0));
200    if (Tmp1 != Node->getOperand(0))
201      Result = DAG.getCopyFromReg(cast<RegSDNode>(Node)->getReg(),
202                                  Node->getValueType(0), Tmp1);
203    break;
204  case ISD::ImplicitDef:
205    Tmp1 = LegalizeOp(Node->getOperand(0));
206    if (Tmp1 != Node->getOperand(0))
207      Result = DAG.getImplicitDef(Tmp1, cast<RegSDNode>(Node)->getReg());
208    break;
209  case ISD::Constant:
210    // We know we don't need to expand constants here, constants only have one
211    // value and we check that it is fine above.
212
213    // FIXME: Maybe we should handle things like targets that don't support full
214    // 32-bit immediates?
215    break;
216  case ISD::ConstantFP: {
217    // Spill FP immediates to the constant pool if the target cannot directly
218    // codegen them.  Targets often have some immediate values that can be
219    // efficiently generated into an FP register without a load.  We explicitly
220    // leave these constants as ConstantFP nodes for the target to deal with.
221
222    ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
223
224    // Check to see if this FP immediate is already legal.
225    bool isLegal = false;
226    for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
227           E = TLI.legal_fpimm_end(); I != E; ++I)
228      if (CFP->isExactlyValue(*I)) {
229        isLegal = true;
230        break;
231      }
232
233    if (!isLegal) {
234      // Otherwise we need to spill the constant to memory.
235      MachineConstantPool *CP = DAG.getMachineFunction().getConstantPool();
236
237      bool Extend = false;
238
239      // If a FP immediate is precise when represented as a float, we put it
240      // into the constant pool as a float, even if it's is statically typed
241      // as a double.
242      MVT::ValueType VT = CFP->getValueType(0);
243      bool isDouble = VT == MVT::f64;
244      ConstantFP *LLVMC = ConstantFP::get(isDouble ? Type::DoubleTy :
245                                             Type::FloatTy, CFP->getValue());
246      if (isDouble && CFP->isExactlyValue((float)CFP->getValue())) {
247        LLVMC = cast<ConstantFP>(ConstantExpr::getCast(LLVMC, Type::FloatTy));
248        VT = MVT::f32;
249        Extend = true;
250      }
251
252      SDOperand CPIdx = DAG.getConstantPool(CP->getConstantPoolIndex(LLVMC),
253                                            TLI.getPointerTy());
254      if (Extend) {
255        Result = DAG.getNode(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(), CPIdx,
256                             MVT::f32);
257      } else {
258        Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx);
259      }
260    }
261    break;
262  }
263  case ISD::TokenFactor: {
264    std::vector<SDOperand> Ops;
265    bool Changed = false;
266    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
267      Ops.push_back(LegalizeOp(Node->getOperand(i)));  // Legalize the operands
268      Changed |= Ops[i] != Node->getOperand(i);
269    }
270    if (Changed)
271      Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Ops);
272    break;
273  }
274
275  case ISD::ADJCALLSTACKDOWN:
276  case ISD::ADJCALLSTACKUP:
277    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
278    // There is no need to legalize the size argument (Operand #1)
279    if (Tmp1 != Node->getOperand(0))
280      Result = DAG.getNode(Node->getOpcode(), MVT::Other, Tmp1,
281                           Node->getOperand(1));
282    break;
283  case ISD::DYNAMIC_STACKALLOC:
284    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
285    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
286    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
287    if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
288        Tmp3 != Node->getOperand(2))
289      Result = DAG.getNode(ISD::DYNAMIC_STACKALLOC, Node->getValueType(0),
290                           Tmp1, Tmp2, Tmp3);
291    else
292      Result = Op.getValue(0);
293
294    // Since this op produces two values, make sure to remember that we
295    // legalized both of them.
296    AddLegalizedOperand(SDOperand(Node, 0), Result);
297    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
298    return Result.getValue(Op.ResNo);
299
300  case ISD::CALL:
301    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
302    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
303    if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1)) {
304      std::vector<MVT::ValueType> RetTyVTs;
305      RetTyVTs.reserve(Node->getNumValues());
306      for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
307        RetTyVTs.push_back(Node->getValueType(i));
308      Result = SDOperand(DAG.getCall(RetTyVTs, Tmp1, Tmp2), 0);
309    } else {
310      Result = Result.getValue(0);
311    }
312    // Since calls produce multiple values, make sure to remember that we
313    // legalized all of them.
314    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
315      AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
316    return Result.getValue(Op.ResNo);
317
318  case ISD::BR:
319    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
320    if (Tmp1 != Node->getOperand(0))
321      Result = DAG.getNode(ISD::BR, MVT::Other, Tmp1, Node->getOperand(1));
322    break;
323
324  case ISD::BRCOND:
325    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
326
327    switch (getTypeAction(Node->getOperand(1).getValueType())) {
328    case Expand: assert(0 && "It's impossible to expand bools");
329    case Legal:
330      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
331      break;
332    case Promote:
333      Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
334      break;
335    }
336    // Basic block destination (Op#2) is always legal.
337    if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
338      Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
339                           Node->getOperand(2));
340    break;
341
342  case ISD::LOAD:
343    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
344    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
345    if (Tmp1 != Node->getOperand(0) ||
346        Tmp2 != Node->getOperand(1))
347      Result = DAG.getLoad(Node->getValueType(0), Tmp1, Tmp2);
348    else
349      Result = SDOperand(Node, 0);
350
351    // Since loads produce two values, make sure to remember that we legalized
352    // both of them.
353    AddLegalizedOperand(SDOperand(Node, 0), Result);
354    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
355    return Result.getValue(Op.ResNo);
356
357  case ISD::EXTLOAD:
358  case ISD::SEXTLOAD:
359  case ISD::ZEXTLOAD:
360    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
361    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
362    if (Tmp1 != Node->getOperand(0) ||
363        Tmp2 != Node->getOperand(1))
364      Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1, Tmp2,
365                           cast<MVTSDNode>(Node)->getExtraValueType());
366    else
367      Result = SDOperand(Node, 0);
368
369    // Since loads produce two values, make sure to remember that we legalized
370    // both of them.
371    AddLegalizedOperand(SDOperand(Node, 0), Result);
372    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
373    return Result.getValue(Op.ResNo);
374
375  case ISD::EXTRACT_ELEMENT:
376    // Get both the low and high parts.
377    ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
378    if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
379      Result = Tmp2;  // 1 -> Hi
380    else
381      Result = Tmp1;  // 0 -> Lo
382    break;
383
384  case ISD::CopyToReg:
385    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
386
387    switch (getTypeAction(Node->getOperand(1).getValueType())) {
388    case Legal:
389      // Legalize the incoming value (must be legal).
390      Tmp2 = LegalizeOp(Node->getOperand(1));
391      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
392        Result = DAG.getCopyToReg(Tmp1, Tmp2, cast<RegSDNode>(Node)->getReg());
393      break;
394    case Promote:
395      Tmp2 = PromoteOp(Node->getOperand(1));
396      Result = DAG.getCopyToReg(Tmp1, Tmp2, cast<RegSDNode>(Node)->getReg());
397      break;
398    case Expand:
399      SDOperand Lo, Hi;
400      ExpandOp(Node->getOperand(1), Lo, Hi);
401      unsigned Reg = cast<RegSDNode>(Node)->getReg();
402      Result = DAG.getCopyToReg(Tmp1, Lo, Reg);
403      Result = DAG.getCopyToReg(Result, Hi, Reg+1);
404      assert(isTypeLegal(Result.getValueType()) &&
405             "Cannot expand multiple times yet (i64 -> i16)");
406      break;
407    }
408    break;
409
410  case ISD::RET:
411    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
412    switch (Node->getNumOperands()) {
413    case 2:  // ret val
414      switch (getTypeAction(Node->getOperand(1).getValueType())) {
415      case Legal:
416        Tmp2 = LegalizeOp(Node->getOperand(1));
417        if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
418          Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
419        break;
420      case Expand: {
421        SDOperand Lo, Hi;
422        ExpandOp(Node->getOperand(1), Lo, Hi);
423        Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
424        break;
425      }
426      case Promote:
427        Tmp2 = PromoteOp(Node->getOperand(1));
428        Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
429        break;
430      }
431      break;
432    case 1:  // ret void
433      if (Tmp1 != Node->getOperand(0))
434        Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1);
435      break;
436    default: { // ret <values>
437      std::vector<SDOperand> NewValues;
438      NewValues.push_back(Tmp1);
439      for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
440        switch (getTypeAction(Node->getOperand(i).getValueType())) {
441        case Legal:
442          NewValues.push_back(LegalizeOp(Node->getOperand(i)));
443          break;
444        case Expand: {
445          SDOperand Lo, Hi;
446          ExpandOp(Node->getOperand(i), Lo, Hi);
447          NewValues.push_back(Lo);
448          NewValues.push_back(Hi);
449          break;
450        }
451        case Promote:
452          assert(0 && "Can't promote multiple return value yet!");
453        }
454      Result = DAG.getNode(ISD::RET, MVT::Other, NewValues);
455      break;
456    }
457    }
458    break;
459  case ISD::STORE:
460    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
461    Tmp2 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
462
463    // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
464    if (ConstantFPSDNode *CFP =dyn_cast<ConstantFPSDNode>(Node->getOperand(1))){
465      if (CFP->getValueType(0) == MVT::f32) {
466        union {
467          unsigned I;
468          float    F;
469        } V;
470        V.F = CFP->getValue();
471        Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
472                             DAG.getConstant(V.I, MVT::i32), Tmp2);
473      } else {
474        assert(CFP->getValueType(0) == MVT::f64 && "Unknown FP type!");
475        union {
476          uint64_t I;
477          double   F;
478        } V;
479        V.F = CFP->getValue();
480        Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
481                             DAG.getConstant(V.I, MVT::i64), Tmp2);
482      }
483      Op = Result;
484      Node = Op.Val;
485    }
486
487    switch (getTypeAction(Node->getOperand(1).getValueType())) {
488    case Legal: {
489      SDOperand Val = LegalizeOp(Node->getOperand(1));
490      if (Val != Node->getOperand(1) || Tmp1 != Node->getOperand(0) ||
491          Tmp2 != Node->getOperand(2))
492        Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Val, Tmp2);
493      break;
494    }
495    case Promote:
496      // Truncate the value and store the result.
497      Tmp3 = PromoteOp(Node->getOperand(1));
498      Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp3, Tmp2,
499                           Node->getOperand(1).getValueType());
500      break;
501
502    case Expand:
503      SDOperand Lo, Hi;
504      ExpandOp(Node->getOperand(1), Lo, Hi);
505
506      if (!TLI.isLittleEndian())
507        std::swap(Lo, Hi);
508
509      // FIXME: These two stores are independent of each other!
510      Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Lo, Tmp2);
511
512      unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
513      Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
514                         getIntPtrConstant(IncrementSize));
515      assert(isTypeLegal(Tmp2.getValueType()) &&
516             "Pointers must be legal!");
517      Result = DAG.getNode(ISD::STORE, MVT::Other, Result, Hi, Tmp2);
518    }
519    break;
520  case ISD::TRUNCSTORE:
521    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
522    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
523
524    switch (getTypeAction(Node->getOperand(1).getValueType())) {
525    case Legal:
526      Tmp2 = LegalizeOp(Node->getOperand(1));
527      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
528          Tmp3 != Node->getOperand(2))
529        Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
530                             cast<MVTSDNode>(Node)->getExtraValueType());
531      break;
532    case Promote:
533    case Expand:
534      assert(0 && "Cannot handle illegal TRUNCSTORE yet!");
535    }
536    break;
537  case ISD::SELECT:
538    switch (getTypeAction(Node->getOperand(0).getValueType())) {
539    case Expand: assert(0 && "It's impossible to expand bools");
540    case Legal:
541      Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
542      break;
543    case Promote:
544      Tmp1 = PromoteOp(Node->getOperand(0));  // Promote the condition.
545      break;
546    }
547    Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
548    Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
549
550    switch (TLI.getOperationAction(Node->getOpcode(), Tmp2.getValueType())) {
551    default: assert(0 && "This action is not supported yet!");
552    case TargetLowering::Legal:
553      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
554          Tmp3 != Node->getOperand(2))
555        Result = DAG.getNode(ISD::SELECT, Node->getValueType(0),
556                             Tmp1, Tmp2, Tmp3);
557      break;
558    case TargetLowering::Promote: {
559      MVT::ValueType NVT =
560        TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
561      unsigned ExtOp, TruncOp;
562      if (MVT::isInteger(Tmp2.getValueType())) {
563        ExtOp = ISD::ZERO_EXTEND;
564        TruncOp  = ISD::TRUNCATE;
565      } else {
566        ExtOp = ISD::FP_EXTEND;
567        TruncOp  = ISD::FP_ROUND;
568      }
569      // Promote each of the values to the new type.
570      Tmp2 = DAG.getNode(ExtOp, NVT, Tmp2);
571      Tmp3 = DAG.getNode(ExtOp, NVT, Tmp3);
572      // Perform the larger operation, then round down.
573      Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2,Tmp3);
574      Result = DAG.getNode(TruncOp, Node->getValueType(0), Result);
575      break;
576    }
577    }
578    break;
579  case ISD::SETCC:
580    switch (getTypeAction(Node->getOperand(0).getValueType())) {
581    case Legal:
582      Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
583      Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
584      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
585        Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
586                              Node->getValueType(0), Tmp1, Tmp2);
587      break;
588    case Promote:
589      Tmp1 = PromoteOp(Node->getOperand(0));   // LHS
590      Tmp2 = PromoteOp(Node->getOperand(1));   // RHS
591
592      // If this is an FP compare, the operands have already been extended.
593      if (MVT::isInteger(Node->getOperand(0).getValueType())) {
594        MVT::ValueType VT = Node->getOperand(0).getValueType();
595        MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
596
597        // Otherwise, we have to insert explicit sign or zero extends.  Note
598        // that we could insert sign extends for ALL conditions, but zero extend
599        // is cheaper on many machines (an AND instead of two shifts), so prefer
600        // it.
601        switch (cast<SetCCSDNode>(Node)->getCondition()) {
602        default: assert(0 && "Unknown integer comparison!");
603        case ISD::SETEQ:
604        case ISD::SETNE:
605        case ISD::SETUGE:
606        case ISD::SETUGT:
607        case ISD::SETULE:
608        case ISD::SETULT:
609          // ALL of these operations will work if we either sign or zero extend
610          // the operands (including the unsigned comparisons!).  Zero extend is
611          // usually a simpler/cheaper operation, so prefer it.
612          Tmp1 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp1, VT);
613          Tmp2 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp2, VT);
614          break;
615        case ISD::SETGE:
616        case ISD::SETGT:
617        case ISD::SETLT:
618        case ISD::SETLE:
619          Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1, VT);
620          Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2, VT);
621          break;
622        }
623
624      }
625      Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
626                            Node->getValueType(0), Tmp1, Tmp2);
627      break;
628    case Expand:
629      SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
630      ExpandOp(Node->getOperand(0), LHSLo, LHSHi);
631      ExpandOp(Node->getOperand(1), RHSLo, RHSHi);
632      switch (cast<SetCCSDNode>(Node)->getCondition()) {
633      case ISD::SETEQ:
634      case ISD::SETNE:
635        Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
636        Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
637        Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
638        Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
639                              Node->getValueType(0), Tmp1,
640                              DAG.getConstant(0, Tmp1.getValueType()));
641        break;
642      default:
643        // FIXME: This generated code sucks.
644        ISD::CondCode LowCC;
645        switch (cast<SetCCSDNode>(Node)->getCondition()) {
646        default: assert(0 && "Unknown integer setcc!");
647        case ISD::SETLT:
648        case ISD::SETULT: LowCC = ISD::SETULT; break;
649        case ISD::SETGT:
650        case ISD::SETUGT: LowCC = ISD::SETUGT; break;
651        case ISD::SETLE:
652        case ISD::SETULE: LowCC = ISD::SETULE; break;
653        case ISD::SETGE:
654        case ISD::SETUGE: LowCC = ISD::SETUGE; break;
655        }
656
657        // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
658        // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
659        // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
660
661        // NOTE: on targets without efficient SELECT of bools, we can always use
662        // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
663        Tmp1 = DAG.getSetCC(LowCC, Node->getValueType(0), LHSLo, RHSLo);
664        Tmp2 = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
665                            Node->getValueType(0), LHSHi, RHSHi);
666        Result = DAG.getSetCC(ISD::SETEQ, Node->getValueType(0), LHSHi, RHSHi);
667        Result = DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
668                             Result, Tmp1, Tmp2);
669        break;
670      }
671    }
672    break;
673
674  case ISD::MEMSET:
675  case ISD::MEMCPY:
676  case ISD::MEMMOVE: {
677    Tmp1 = LegalizeOp(Node->getOperand(0));
678    Tmp2 = LegalizeOp(Node->getOperand(1));
679    Tmp3 = LegalizeOp(Node->getOperand(2));
680    SDOperand Tmp4 = LegalizeOp(Node->getOperand(3));
681    SDOperand Tmp5 = LegalizeOp(Node->getOperand(4));
682
683    switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
684    default: assert(0 && "This action not implemented for this operation!");
685    case TargetLowering::Legal:
686      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
687          Tmp3 != Node->getOperand(2) || Tmp4 != Node->getOperand(3) ||
688          Tmp5 != Node->getOperand(4)) {
689        std::vector<SDOperand> Ops;
690        Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
691        Ops.push_back(Tmp4); Ops.push_back(Tmp5);
692        Result = DAG.getNode(Node->getOpcode(), MVT::Other, Ops);
693      }
694      break;
695    case TargetLowering::Expand: {
696      // Otherwise, the target does not support this operation.  Lower the
697      // operation to an explicit libcall as appropriate.
698      MVT::ValueType IntPtr = TLI.getPointerTy();
699      const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
700      std::vector<std::pair<SDOperand, const Type*> > Args;
701
702      const char *FnName = 0;
703      if (Node->getOpcode() == ISD::MEMSET) {
704        Args.push_back(std::make_pair(Tmp2, IntPtrTy));
705        // Extend the ubyte argument to be an int value for the call.
706        Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Tmp3);
707        Args.push_back(std::make_pair(Tmp3, Type::IntTy));
708        Args.push_back(std::make_pair(Tmp4, IntPtrTy));
709
710        FnName = "memset";
711      } else if (Node->getOpcode() == ISD::MEMCPY ||
712                 Node->getOpcode() == ISD::MEMMOVE) {
713        Args.push_back(std::make_pair(Tmp2, IntPtrTy));
714        Args.push_back(std::make_pair(Tmp3, IntPtrTy));
715        Args.push_back(std::make_pair(Tmp4, IntPtrTy));
716        FnName = Node->getOpcode() == ISD::MEMMOVE ? "memmove" : "memcpy";
717      } else {
718        assert(0 && "Unknown op!");
719      }
720      std::pair<SDOperand,SDOperand> CallResult =
721        TLI.LowerCallTo(Tmp1, Type::VoidTy,
722                        DAG.getExternalSymbol(FnName, IntPtr), Args, DAG);
723      Result = LegalizeOp(CallResult.second);
724      break;
725    }
726    case TargetLowering::Custom:
727      std::vector<SDOperand> Ops;
728      Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
729      Ops.push_back(Tmp4); Ops.push_back(Tmp5);
730      Result = DAG.getNode(Node->getOpcode(), MVT::Other, Ops);
731      Result = TLI.LowerOperation(Result);
732      Result = LegalizeOp(Result);
733      break;
734    }
735    break;
736  }
737  case ISD::ADD:
738  case ISD::SUB:
739  case ISD::MUL:
740  case ISD::UDIV:
741  case ISD::SDIV:
742  case ISD::UREM:
743  case ISD::SREM:
744  case ISD::AND:
745  case ISD::OR:
746  case ISD::XOR:
747  case ISD::SHL:
748  case ISD::SRL:
749  case ISD::SRA:
750    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
751    Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
752    if (Tmp1 != Node->getOperand(0) ||
753        Tmp2 != Node->getOperand(1))
754      Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,Tmp2);
755    break;
756  case ISD::ZERO_EXTEND:
757  case ISD::SIGN_EXTEND:
758  case ISD::TRUNCATE:
759  case ISD::FP_EXTEND:
760  case ISD::FP_ROUND:
761  case ISD::FP_TO_SINT:
762  case ISD::FP_TO_UINT:
763  case ISD::SINT_TO_FP:
764  case ISD::UINT_TO_FP:
765    switch (getTypeAction(Node->getOperand(0).getValueType())) {
766    case Legal:
767      Tmp1 = LegalizeOp(Node->getOperand(0));
768      if (Tmp1 != Node->getOperand(0))
769        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
770      break;
771    case Expand:
772      assert(Node->getOpcode() != ISD::SINT_TO_FP &&
773             Node->getOpcode() != ISD::UINT_TO_FP &&
774             "Cannot lower Xint_to_fp to a call yet!");
775
776      // In the expand case, we must be dealing with a truncate, because
777      // otherwise the result would be larger than the source.
778      assert(Node->getOpcode() == ISD::TRUNCATE &&
779             "Shouldn't need to expand other operators here!");
780      ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
781
782      // Since the result is legal, we should just be able to truncate the low
783      // part of the source.
784      Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
785      break;
786
787    case Promote:
788      switch (Node->getOpcode()) {
789      case ISD::ZERO_EXTEND:
790        Result = PromoteOp(Node->getOperand(0));
791        // NOTE: Any extend would work here...
792        Result = DAG.getNode(ISD::ZERO_EXTEND, Op.getValueType(), Result);
793        Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, Op.getValueType(),
794                             Result, Node->getOperand(0).getValueType());
795        break;
796      case ISD::SIGN_EXTEND:
797        Result = PromoteOp(Node->getOperand(0));
798        // NOTE: Any extend would work here...
799        Result = DAG.getNode(ISD::ZERO_EXTEND, Op.getValueType(), Result);
800        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
801                             Result, Node->getOperand(0).getValueType());
802        break;
803      case ISD::TRUNCATE:
804        Result = PromoteOp(Node->getOperand(0));
805        Result = DAG.getNode(ISD::TRUNCATE, Op.getValueType(), Result);
806        break;
807      case ISD::FP_EXTEND:
808        Result = PromoteOp(Node->getOperand(0));
809        if (Result.getValueType() != Op.getValueType())
810          // Dynamically dead while we have only 2 FP types.
811          Result = DAG.getNode(ISD::FP_EXTEND, Op.getValueType(), Result);
812        break;
813      case ISD::FP_ROUND:
814      case ISD::FP_TO_SINT:
815      case ISD::FP_TO_UINT:
816        Result = PromoteOp(Node->getOperand(0));
817        Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
818        break;
819      case ISD::SINT_TO_FP:
820        Result = PromoteOp(Node->getOperand(0));
821        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
822                             Result, Node->getOperand(0).getValueType());
823        Result = DAG.getNode(ISD::SINT_TO_FP, Op.getValueType(), Result);
824        break;
825      case ISD::UINT_TO_FP:
826        Result = PromoteOp(Node->getOperand(0));
827        Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, Result.getValueType(),
828                             Result, Node->getOperand(0).getValueType());
829        Result = DAG.getNode(ISD::UINT_TO_FP, Op.getValueType(), Result);
830        break;
831      }
832    }
833    break;
834  case ISD::FP_ROUND_INREG:
835  case ISD::SIGN_EXTEND_INREG:
836  case ISD::ZERO_EXTEND_INREG: {
837    Tmp1 = LegalizeOp(Node->getOperand(0));
838    MVT::ValueType ExtraVT = cast<MVTSDNode>(Node)->getExtraValueType();
839
840    // If this operation is not supported, convert it to a shl/shr or load/store
841    // pair.
842    switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
843    default: assert(0 && "This action not supported for this op yet!");
844    case TargetLowering::Legal:
845      if (Tmp1 != Node->getOperand(0))
846        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
847                             ExtraVT);
848      break;
849    case TargetLowering::Expand:
850      // If this is an integer extend and shifts are supported, do that.
851      if (Node->getOpcode() == ISD::ZERO_EXTEND_INREG) {
852        // NOTE: we could fall back on load/store here too for targets without
853        // AND.  However, it is doubtful that any exist.
854        // AND out the appropriate bits.
855        SDOperand Mask =
856          DAG.getConstant((1ULL << MVT::getSizeInBits(ExtraVT))-1,
857                          Node->getValueType(0));
858        Result = DAG.getNode(ISD::AND, Node->getValueType(0),
859                             Node->getOperand(0), Mask);
860      } else if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
861        // NOTE: we could fall back on load/store here too for targets without
862        // SAR.  However, it is doubtful that any exist.
863        unsigned BitsDiff = MVT::getSizeInBits(Node->getValueType(0)) -
864                            MVT::getSizeInBits(ExtraVT);
865        SDOperand ShiftCst = DAG.getConstant(BitsDiff, MVT::i8);
866        Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
867                             Node->getOperand(0), ShiftCst);
868        Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
869                             Result, ShiftCst);
870      } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
871        // The only way we can lower this is to turn it into a STORETRUNC,
872        // EXTLOAD pair, targetting a temporary location (a stack slot).
873
874        // NOTE: there is a choice here between constantly creating new stack
875        // slots and always reusing the same one.  We currently always create
876        // new ones, as reuse may inhibit scheduling.
877        const Type *Ty = MVT::getTypeForValueType(ExtraVT);
878        unsigned TySize = (unsigned)TLI.getTargetData().getTypeSize(Ty);
879        unsigned Align  = TLI.getTargetData().getTypeAlignment(Ty);
880        MachineFunction &MF = DAG.getMachineFunction();
881        int SSFI =
882          MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
883        SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
884        Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, DAG.getEntryNode(),
885                             Node->getOperand(0), StackSlot, ExtraVT);
886        Result = DAG.getNode(ISD::EXTLOAD, Node->getValueType(0),
887                             Result, StackSlot, ExtraVT);
888      } else {
889        assert(0 && "Unknown op");
890      }
891      Result = LegalizeOp(Result);
892      break;
893    }
894    break;
895  }
896  }
897
898  if (!Op.Val->hasOneUse())
899    AddLegalizedOperand(Op, Result);
900
901  return Result;
902}
903
904/// PromoteOp - Given an operation that produces a value in an invalid type,
905/// promote it to compute the value into a larger type.  The produced value will
906/// have the correct bits for the low portion of the register, but no guarantee
907/// is made about the top bits: it may be zero, sign-extended, or garbage.
908SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
909  MVT::ValueType VT = Op.getValueType();
910  MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
911  assert(getTypeAction(VT) == Promote &&
912         "Caller should expand or legalize operands that are not promotable!");
913  assert(NVT > VT && MVT::isInteger(NVT) == MVT::isInteger(VT) &&
914         "Cannot promote to smaller type!");
915
916  std::map<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
917  if (I != PromotedNodes.end()) return I->second;
918
919  SDOperand Tmp1, Tmp2, Tmp3;
920
921  SDOperand Result;
922  SDNode *Node = Op.Val;
923
924  // Promotion needs an optimization step to clean up after it, and is not
925  // careful to avoid operations the target does not support.  Make sure that
926  // all generated operations are legalized in the next iteration.
927  NeedsAnotherIteration = true;
928
929  switch (Node->getOpcode()) {
930  default:
931    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
932    assert(0 && "Do not know how to promote this operator!");
933    abort();
934  case ISD::Constant:
935    Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
936    assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
937    break;
938  case ISD::ConstantFP:
939    Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
940    assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
941    break;
942  case ISD::CopyFromReg:
943    Result = DAG.getCopyFromReg(cast<RegSDNode>(Node)->getReg(), NVT,
944                                Node->getOperand(0));
945    // Remember that we legalized the chain.
946    AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
947    break;
948
949  case ISD::SETCC:
950    assert(getTypeAction(TLI.getSetCCResultTy()) == Legal &&
951           "SetCC type is not legal??");
952    Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
953                          TLI.getSetCCResultTy(), Node->getOperand(0),
954                          Node->getOperand(1));
955    Result = LegalizeOp(Result);
956    break;
957
958  case ISD::TRUNCATE:
959    switch (getTypeAction(Node->getOperand(0).getValueType())) {
960    case Legal:
961      Result = LegalizeOp(Node->getOperand(0));
962      assert(Result.getValueType() >= NVT &&
963             "This truncation doesn't make sense!");
964      if (Result.getValueType() > NVT)    // Truncate to NVT instead of VT
965        Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
966      break;
967    case Expand:
968      assert(0 && "Cannot handle expand yet");
969    case Promote:
970      assert(0 && "Cannot handle promote-promote yet");
971    }
972    break;
973  case ISD::SIGN_EXTEND:
974  case ISD::ZERO_EXTEND:
975    switch (getTypeAction(Node->getOperand(0).getValueType())) {
976    case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
977    case Legal:
978      // Input is legal?  Just do extend all the way to the larger type.
979      Result = LegalizeOp(Node->getOperand(0));
980      Result = DAG.getNode(Node->getOpcode(), NVT, Result);
981      break;
982    case Promote:
983      // Promote the reg if it's smaller.
984      Result = PromoteOp(Node->getOperand(0));
985      // The high bits are not guaranteed to be anything.  Insert an extend.
986      if (Node->getOpcode() == ISD::SIGN_EXTEND)
987        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result, VT);
988      else
989        Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Result, VT);
990      break;
991    }
992    break;
993
994  case ISD::FP_EXTEND:
995    assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
996  case ISD::FP_ROUND:
997    switch (getTypeAction(Node->getOperand(0).getValueType())) {
998    case Expand: assert(0 && "BUG: Cannot expand FP regs!");
999    case Promote:  assert(0 && "Unreachable with 2 FP types!");
1000    case Legal:
1001      // Input is legal?  Do an FP_ROUND_INREG.
1002      Result = LegalizeOp(Node->getOperand(0));
1003      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1004      break;
1005    }
1006    break;
1007
1008  case ISD::SINT_TO_FP:
1009  case ISD::UINT_TO_FP:
1010    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1011    case Legal:
1012      Result = LegalizeOp(Node->getOperand(0));
1013      break;
1014
1015    case Promote:
1016      Result = PromoteOp(Node->getOperand(0));
1017      if (Node->getOpcode() == ISD::SINT_TO_FP)
1018        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1019                             Result, Node->getOperand(0).getValueType());
1020      else
1021        Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, Result.getValueType(),
1022                             Result, Node->getOperand(0).getValueType());
1023      break;
1024    case Expand:
1025      assert(0 && "Unimplemented");
1026    }
1027    // No extra round required here.
1028    Result = DAG.getNode(Node->getOpcode(), NVT, Result);
1029    break;
1030
1031  case ISD::FP_TO_SINT:
1032  case ISD::FP_TO_UINT:
1033    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1034    case Legal:
1035      Tmp1 = LegalizeOp(Node->getOperand(0));
1036      break;
1037    case Promote:
1038      // The input result is prerounded, so we don't have to do anything
1039      // special.
1040      Tmp1 = PromoteOp(Node->getOperand(0));
1041      break;
1042    case Expand:
1043      assert(0 && "not implemented");
1044    }
1045    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
1046    break;
1047
1048  case ISD::AND:
1049  case ISD::OR:
1050  case ISD::XOR:
1051  case ISD::ADD:
1052  case ISD::SUB:
1053  case ISD::MUL:
1054    // The input may have strange things in the top bits of the registers, but
1055    // these operations don't care.  They may have wierd bits going out, but
1056    // that too is okay if they are integer operations.
1057    Tmp1 = PromoteOp(Node->getOperand(0));
1058    Tmp2 = PromoteOp(Node->getOperand(1));
1059    assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
1060    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1061
1062    // However, if this is a floating point operation, they will give excess
1063    // precision that we may not be able to tolerate.  If we DO allow excess
1064    // precision, just leave it, otherwise excise it.
1065    // FIXME: Why would we need to round FP ops more than integer ones?
1066    //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
1067    if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
1068      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1069    break;
1070
1071  case ISD::SDIV:
1072  case ISD::SREM:
1073    // These operators require that their input be sign extended.
1074    Tmp1 = PromoteOp(Node->getOperand(0));
1075    Tmp2 = PromoteOp(Node->getOperand(1));
1076    if (MVT::isInteger(NVT)) {
1077      Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1, VT);
1078      Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2, VT);
1079    }
1080    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1081
1082    // Perform FP_ROUND: this is probably overly pessimistic.
1083    if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
1084      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1085    break;
1086
1087  case ISD::UDIV:
1088  case ISD::UREM:
1089    // These operators require that their input be zero extended.
1090    Tmp1 = PromoteOp(Node->getOperand(0));
1091    Tmp2 = PromoteOp(Node->getOperand(1));
1092    assert(MVT::isInteger(NVT) && "Operators don't apply to FP!");
1093    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp1, VT);
1094    Tmp2 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp2, VT);
1095    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1096    break;
1097
1098  case ISD::SHL:
1099    Tmp1 = PromoteOp(Node->getOperand(0));
1100    Tmp2 = LegalizeOp(Node->getOperand(1));
1101    Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Tmp2);
1102    break;
1103  case ISD::SRA:
1104    // The input value must be properly sign extended.
1105    Tmp1 = PromoteOp(Node->getOperand(0));
1106    Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1, VT);
1107    Tmp2 = LegalizeOp(Node->getOperand(1));
1108    Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Tmp2);
1109    break;
1110  case ISD::SRL:
1111    // The input value must be properly zero extended.
1112    Tmp1 = PromoteOp(Node->getOperand(0));
1113    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp1, VT);
1114    Tmp2 = LegalizeOp(Node->getOperand(1));
1115    Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Tmp2);
1116    break;
1117  case ISD::LOAD:
1118    Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
1119    Tmp2 = LegalizeOp(Node->getOperand(1));   // Legalize the pointer.
1120    Result = DAG.getNode(ISD::EXTLOAD, NVT, Tmp1, Tmp2, VT);
1121
1122    // Remember that we legalized the chain.
1123    AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1124    break;
1125  case ISD::SELECT:
1126    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1127    case Expand: assert(0 && "It's impossible to expand bools");
1128    case Legal:
1129      Tmp1 = LegalizeOp(Node->getOperand(0));// Legalize the condition.
1130      break;
1131    case Promote:
1132      Tmp1 = PromoteOp(Node->getOperand(0)); // Promote the condition.
1133      break;
1134    }
1135    Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
1136    Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
1137    Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2, Tmp3);
1138    break;
1139  case ISD::CALL: {
1140    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1141    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
1142
1143    assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
1144           "Can only promote single result calls");
1145    std::vector<MVT::ValueType> RetTyVTs;
1146    RetTyVTs.reserve(2);
1147    RetTyVTs.push_back(NVT);
1148    RetTyVTs.push_back(MVT::Other);
1149    SDNode *NC = DAG.getCall(RetTyVTs, Tmp1, Tmp2);
1150    Result = SDOperand(NC, 0);
1151
1152    // Insert the new chain mapping.
1153    AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1154    break;
1155  }
1156  }
1157
1158  assert(Result.Val && "Didn't set a result!");
1159  AddPromotedOperand(Op, Result);
1160  return Result;
1161}
1162
1163/// ExpandShift - Try to find a clever way to expand this shift operation out to
1164/// smaller elements.  If we can't find a way that is more efficient than a
1165/// libcall on this target, return false.  Otherwise, return true with the
1166/// low-parts expanded into Lo and Hi.
1167bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDOperand Op,SDOperand Amt,
1168                                       SDOperand &Lo, SDOperand &Hi) {
1169  assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
1170         "This is not a shift!");
1171  MVT::ValueType NVT = TLI.getTypeToTransformTo(Op.getValueType());
1172
1173  // If we have an efficient select operation (or if the selects will all fold
1174  // away), lower to some complex code, otherwise just emit the libcall.
1175  if (TLI.getOperationAction(ISD::SELECT, NVT) != TargetLowering::Legal &&
1176      !isa<ConstantSDNode>(Amt))
1177    return false;
1178
1179  SDOperand InL, InH;
1180  ExpandOp(Op, InL, InH);
1181  SDOperand ShAmt = LegalizeOp(Amt);
1182  SDOperand OShAmt = ShAmt;  // Unmasked shift amount.
1183  MVT::ValueType ShTy = ShAmt.getValueType();
1184
1185  unsigned NVTBits = MVT::getSizeInBits(NVT);
1186  SDOperand NAmt = DAG.getNode(ISD::SUB, ShTy,           // NAmt = 32-ShAmt
1187                               DAG.getConstant(NVTBits, ShTy), ShAmt);
1188
1189  if (TLI.getShiftAmountFlavor() != TargetLowering::Mask) {
1190    ShAmt = DAG.getNode(ISD::AND, ShTy, ShAmt,             // ShAmt &= 31
1191                        DAG.getConstant(NVTBits-1, ShTy));
1192    NAmt  = DAG.getNode(ISD::AND, ShTy, NAmt,              // NAmt &= 31
1193                        DAG.getConstant(NVTBits-1, ShTy));
1194  }
1195
1196  if (Opc == ISD::SHL) {
1197    SDOperand T1 = DAG.getNode(ISD::OR, NVT,// T1 = (Hi << Amt) | (Lo >> NAmt)
1198                               DAG.getNode(ISD::SHL, NVT, InH, ShAmt),
1199                               DAG.getNode(ISD::SRL, NVT, InL, NAmt));
1200    SDOperand T2 = DAG.getNode(ISD::SHL, NVT, InL, ShAmt); // T2 = Lo << Amt
1201
1202    SDOperand Cond = DAG.getSetCC(ISD::SETGE, TLI.getSetCCResultTy(), OShAmt,
1203                                  DAG.getConstant(NVTBits, ShTy));
1204    Hi = DAG.getNode(ISD::SELECT, NVT, Cond, T2, T1);
1205    Lo = DAG.getNode(ISD::SELECT, NVT, Cond, DAG.getConstant(0, NVT), T2);
1206  } else {
1207    SDOperand T1 = DAG.getNode(ISD::OR, NVT,// T1 = (Hi << NAmt) | (Lo >> Amt)
1208                               DAG.getNode(ISD::SHL, NVT, InH, NAmt),
1209                               DAG.getNode(ISD::SRL, NVT, InL, ShAmt));
1210    bool isSign = Opc == ISD::SRA;
1211    SDOperand T2 = DAG.getNode(Opc, NVT, InH, ShAmt);
1212
1213    SDOperand HiPart;
1214    if (isSign)
1215      HiPart = DAG.getNode(Opc, NVT, InH, DAG.getConstant(NVTBits-1, ShTy));
1216    else
1217      HiPart = DAG.getConstant(0, NVT);
1218    SDOperand Cond = DAG.getSetCC(ISD::SETGE, TLI.getSetCCResultTy(), OShAmt,
1219                                  DAG.getConstant(NVTBits, ShTy));
1220    Lo = DAG.getNode(ISD::SELECT, NVT, Cond, T2, T1);
1221    Hi = DAG.getNode(ISD::SELECT, NVT, Cond, HiPart,T2);
1222  }
1223  return true;
1224}
1225
1226
1227
1228/// ExpandOp - Expand the specified SDOperand into its two component pieces
1229/// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
1230/// LegalizeNodes map is filled in for any results that are not expanded, the
1231/// ExpandedNodes map is filled in for any results that are expanded, and the
1232/// Lo/Hi values are returned.
1233void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
1234  MVT::ValueType VT = Op.getValueType();
1235  MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
1236  SDNode *Node = Op.Val;
1237  assert(getTypeAction(VT) == Expand && "Not an expanded type!");
1238  assert(MVT::isInteger(VT) && "Cannot expand FP values!");
1239  assert(MVT::isInteger(NVT) && NVT < VT &&
1240         "Cannot expand to FP value or to larger int value!");
1241
1242  // If there is more than one use of this, see if we already expanded it.
1243  // There is no use remembering values that only have a single use, as the map
1244  // entries will never be reused.
1245  if (!Node->hasOneUse()) {
1246    std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
1247      = ExpandedNodes.find(Op);
1248    if (I != ExpandedNodes.end()) {
1249      Lo = I->second.first;
1250      Hi = I->second.second;
1251      return;
1252    }
1253  }
1254
1255  // Expanding to multiple registers needs to perform an optimization step, and
1256  // is not careful to avoid operations the target does not support.  Make sure
1257  // that all generated operations are legalized in the next iteration.
1258  NeedsAnotherIteration = true;
1259  const char *LibCallName = 0;
1260
1261  switch (Node->getOpcode()) {
1262  default:
1263    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
1264    assert(0 && "Do not know how to expand this operator!");
1265    abort();
1266  case ISD::Constant: {
1267    uint64_t Cst = cast<ConstantSDNode>(Node)->getValue();
1268    Lo = DAG.getConstant(Cst, NVT);
1269    Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
1270    break;
1271  }
1272
1273  case ISD::CopyFromReg: {
1274    unsigned Reg = cast<RegSDNode>(Node)->getReg();
1275    // Aggregate register values are always in consequtive pairs.
1276    Lo = DAG.getCopyFromReg(Reg, NVT, Node->getOperand(0));
1277    Hi = DAG.getCopyFromReg(Reg+1, NVT, Lo.getValue(1));
1278
1279    // Remember that we legalized the chain.
1280    AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
1281
1282    assert(isTypeLegal(NVT) && "Cannot expand this multiple times yet!");
1283    break;
1284  }
1285
1286  case ISD::LOAD: {
1287    SDOperand Ch = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
1288    SDOperand Ptr = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1289    Lo = DAG.getLoad(NVT, Ch, Ptr);
1290
1291    // Increment the pointer to the other half.
1292    unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
1293    Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
1294                      getIntPtrConstant(IncrementSize));
1295    // FIXME: This load is independent of the first one.
1296    Hi = DAG.getLoad(NVT, Lo.getValue(1), Ptr);
1297
1298    // Remember that we legalized the chain.
1299    AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
1300    if (!TLI.isLittleEndian())
1301      std::swap(Lo, Hi);
1302    break;
1303  }
1304  case ISD::CALL: {
1305    SDOperand Chain  = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1306    SDOperand Callee = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
1307
1308    assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
1309           "Can only expand a call once so far, not i64 -> i16!");
1310
1311    std::vector<MVT::ValueType> RetTyVTs;
1312    RetTyVTs.reserve(3);
1313    RetTyVTs.push_back(NVT);
1314    RetTyVTs.push_back(NVT);
1315    RetTyVTs.push_back(MVT::Other);
1316    SDNode *NC = DAG.getCall(RetTyVTs, Chain, Callee);
1317    Lo = SDOperand(NC, 0);
1318    Hi = SDOperand(NC, 1);
1319
1320    // Insert the new chain mapping.
1321    AddLegalizedOperand(Op.getValue(1), Hi.getValue(2));
1322    break;
1323  }
1324  case ISD::AND:
1325  case ISD::OR:
1326  case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
1327    SDOperand LL, LH, RL, RH;
1328    ExpandOp(Node->getOperand(0), LL, LH);
1329    ExpandOp(Node->getOperand(1), RL, RH);
1330    Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
1331    Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
1332    break;
1333  }
1334  case ISD::SELECT: {
1335    SDOperand C, LL, LH, RL, RH;
1336
1337    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1338    case Expand: assert(0 && "It's impossible to expand bools");
1339    case Legal:
1340      C = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
1341      break;
1342    case Promote:
1343      C = PromoteOp(Node->getOperand(0));  // Promote the condition.
1344      break;
1345    }
1346    ExpandOp(Node->getOperand(1), LL, LH);
1347    ExpandOp(Node->getOperand(2), RL, RH);
1348    Lo = DAG.getNode(ISD::SELECT, NVT, C, LL, RL);
1349    Hi = DAG.getNode(ISD::SELECT, NVT, C, LH, RH);
1350    break;
1351  }
1352  case ISD::SIGN_EXTEND: {
1353    // The low part is just a sign extension of the input (which degenerates to
1354    // a copy).
1355    Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, LegalizeOp(Node->getOperand(0)));
1356
1357    // The high part is obtained by SRA'ing all but one of the bits of the lo
1358    // part.
1359    unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
1360    Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1, MVT::i8));
1361    break;
1362  }
1363  case ISD::ZERO_EXTEND:
1364    // The low part is just a zero extension of the input (which degenerates to
1365    // a copy).
1366    Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, LegalizeOp(Node->getOperand(0)));
1367
1368    // The high part is just a zero.
1369    Hi = DAG.getConstant(0, NVT);
1370    break;
1371
1372    // These operators cannot be expanded directly, emit them as calls to
1373    // library functions.
1374  case ISD::FP_TO_SINT:
1375    if (Node->getOperand(0).getValueType() == MVT::f32)
1376      LibCallName = "__fixsfdi";
1377    else
1378      LibCallName = "__fixdfdi";
1379    break;
1380  case ISD::FP_TO_UINT:
1381    if (Node->getOperand(0).getValueType() == MVT::f32)
1382      LibCallName = "__fixunssfdi";
1383    else
1384      LibCallName = "__fixunsdfdi";
1385    break;
1386
1387  case ISD::SHL:
1388    // If we can emit an efficient shift operation, do so now.
1389    if (ExpandShift(ISD::SHL, Node->getOperand(0), Node->getOperand(1),
1390                    Lo, Hi))
1391      break;
1392    // Otherwise, emit a libcall.
1393    LibCallName = "__ashldi3";
1394    break;
1395
1396  case ISD::SRA:
1397    // If we can emit an efficient shift operation, do so now.
1398    if (ExpandShift(ISD::SRA, Node->getOperand(0), Node->getOperand(1),
1399                    Lo, Hi))
1400      break;
1401    // Otherwise, emit a libcall.
1402    LibCallName = "__ashrdi3";
1403    break;
1404  case ISD::SRL:
1405    // If we can emit an efficient shift operation, do so now.
1406    if (ExpandShift(ISD::SRL, Node->getOperand(0), Node->getOperand(1),
1407                    Lo, Hi))
1408      break;
1409    // Otherwise, emit a libcall.
1410    LibCallName = "__lshrdi3";
1411    break;
1412
1413  case ISD::ADD:  LibCallName = "__adddi3"; break;
1414  case ISD::SUB:  LibCallName = "__subdi3"; break;
1415  case ISD::MUL:  LibCallName = "__muldi3"; break;
1416  case ISD::SDIV: LibCallName = "__divdi3"; break;
1417  case ISD::UDIV: LibCallName = "__udivdi3"; break;
1418  case ISD::SREM: LibCallName = "__moddi3"; break;
1419  case ISD::UREM: LibCallName = "__umoddi3"; break;
1420  }
1421
1422  // Int2FP -> __floatdisf/__floatdidf
1423
1424  // If this is to be expanded into a libcall... do so now.
1425  if (LibCallName) {
1426    TargetLowering::ArgListTy Args;
1427    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1428      Args.push_back(std::make_pair(Node->getOperand(i),
1429                 MVT::getTypeForValueType(Node->getOperand(i).getValueType())));
1430    SDOperand Callee = DAG.getExternalSymbol(LibCallName, TLI.getPointerTy());
1431
1432    // We don't care about token chains for libcalls.  We just use the entry
1433    // node as our input and ignore the output chain.  This allows us to place
1434    // calls wherever we need them to satisfy data dependences.
1435    SDOperand Result = TLI.LowerCallTo(DAG.getEntryNode(),
1436                           MVT::getTypeForValueType(Op.getValueType()), Callee,
1437                                       Args, DAG).first;
1438    ExpandOp(Result, Lo, Hi);
1439  }
1440
1441  // Remember in a map if the values will be reused later.
1442  if (!Node->hasOneUse()) {
1443    bool isNew = ExpandedNodes.insert(std::make_pair(Op,
1444                                            std::make_pair(Lo, Hi))).second;
1445    assert(isNew && "Value already expanded?!?");
1446  }
1447}
1448
1449
1450// SelectionDAG::Legalize - This is the entry point for the file.
1451//
1452void SelectionDAG::Legalize(TargetLowering &TLI) {
1453  /// run - This is the main entry point to this class.
1454  ///
1455  SelectionDAGLegalize(TLI, *this).Run();
1456}
1457
1458