LegalizeDAG.cpp revision 181b7a382fbdd3d03ce373a6ffac2204e763f9c3
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/MachineFunction.h"
16#include "llvm/CodeGen/MachineFrameInfo.h"
17#include "llvm/Support/MathExtras.h"
18#include "llvm/Target/TargetLowering.h"
19#include "llvm/Target/TargetData.h"
20#include "llvm/Target/TargetOptions.h"
21#include "llvm/CallingConv.h"
22#include "llvm/Constants.h"
23#include <iostream>
24#include <set>
25using namespace llvm;
26
27//===----------------------------------------------------------------------===//
28/// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
29/// hacks on it until the target machine can handle it.  This involves
30/// eliminating value sizes the machine cannot handle (promoting small sizes to
31/// large sizes or splitting up large values into small values) as well as
32/// eliminating operations the machine cannot handle.
33///
34/// This code also does a small amount of optimization and recognition of idioms
35/// as part of its processing.  For example, if a target does not support a
36/// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
37/// will attempt merge setcc and brc instructions into brcc's.
38///
39namespace {
40class SelectionDAGLegalize {
41  TargetLowering &TLI;
42  SelectionDAG &DAG;
43
44  /// LegalizeAction - This enum indicates what action we should take for each
45  /// value type the can occur in the program.
46  enum LegalizeAction {
47    Legal,            // The target natively supports this value type.
48    Promote,          // This should be promoted to the next larger type.
49    Expand,           // This integer type should be broken into smaller pieces.
50  };
51
52  /// ValueTypeActions - This is a bitvector that contains two bits for each
53  /// value type, where the two bits correspond to the LegalizeAction enum.
54  /// This can be queried with "getTypeAction(VT)".
55  unsigned long long ValueTypeActions;
56
57  /// NeedsAnotherIteration - This is set when we expand a large integer
58  /// operation into smaller integer operations, but the smaller operations are
59  /// not set.  This occurs only rarely in practice, for targets that don't have
60  /// 32-bit or larger integer registers.
61  bool NeedsAnotherIteration;
62
63  /// LegalizedNodes - For nodes that are of legal width, and that have more
64  /// than one use, this map indicates what regularized operand to use.  This
65  /// allows us to avoid legalizing the same thing more than once.
66  std::map<SDOperand, SDOperand> LegalizedNodes;
67
68  /// PromotedNodes - For nodes that are below legal width, and that have more
69  /// than one use, this map indicates what promoted value to use.  This allows
70  /// us to avoid promoting the same thing more than once.
71  std::map<SDOperand, SDOperand> PromotedNodes;
72
73  /// ExpandedNodes - For nodes that need to be expanded, and which have more
74  /// than one use, this map indicates which which operands are the expanded
75  /// version of the input.  This allows us to avoid expanding the same node
76  /// more than once.
77  std::map<SDOperand, std::pair<SDOperand, SDOperand> > ExpandedNodes;
78
79  void AddLegalizedOperand(SDOperand From, SDOperand To) {
80    bool isNew = LegalizedNodes.insert(std::make_pair(From, To)).second;
81    assert(isNew && "Got into the map somehow?");
82  }
83  void AddPromotedOperand(SDOperand From, SDOperand To) {
84    bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
85    assert(isNew && "Got into the map somehow?");
86  }
87
88public:
89
90  SelectionDAGLegalize(SelectionDAG &DAG);
91
92  /// Run - While there is still lowering to do, perform a pass over the DAG.
93  /// Most regularization can be done in a single pass, but targets that require
94  /// large values to be split into registers multiple times (e.g. i64 -> 4x
95  /// i16) require iteration for these values (the first iteration will demote
96  /// to i32, the second will demote to i16).
97  void Run() {
98    do {
99      NeedsAnotherIteration = false;
100      LegalizeDAG();
101    } while (NeedsAnotherIteration);
102  }
103
104  /// getTypeAction - Return how we should legalize values of this type, either
105  /// it is already legal or we need to expand it into multiple registers of
106  /// smaller integer type, or we need to promote it to a larger type.
107  LegalizeAction getTypeAction(MVT::ValueType VT) const {
108    return (LegalizeAction)((ValueTypeActions >> (2*VT)) & 3);
109  }
110
111  /// isTypeLegal - Return true if this type is legal on this target.
112  ///
113  bool isTypeLegal(MVT::ValueType VT) const {
114    return getTypeAction(VT) == Legal;
115  }
116
117private:
118  void LegalizeDAG();
119
120  SDOperand LegalizeOp(SDOperand O);
121  void ExpandOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
122  SDOperand PromoteOp(SDOperand O);
123
124  SDOperand ExpandLibCall(const char *Name, SDNode *Node,
125                          SDOperand &Hi);
126  SDOperand ExpandIntToFP(bool isSigned, MVT::ValueType DestTy,
127                          SDOperand Source);
128
129  SDOperand ExpandLegalINT_TO_FP(bool isSigned,
130                                 SDOperand LegalOp,
131                                 MVT::ValueType DestVT);
132  SDOperand PromoteLegalINT_TO_FP(SDOperand LegalOp, MVT::ValueType DestVT,
133                                  bool isSigned);
134  SDOperand PromoteLegalFP_TO_INT(SDOperand LegalOp, MVT::ValueType DestVT,
135                                  bool isSigned);
136
137  bool ExpandShift(unsigned Opc, SDOperand Op, SDOperand Amt,
138                   SDOperand &Lo, SDOperand &Hi);
139  void ExpandShiftParts(unsigned NodeOp, SDOperand Op, SDOperand Amt,
140                        SDOperand &Lo, SDOperand &Hi);
141  void ExpandByParts(unsigned NodeOp, SDOperand LHS, SDOperand RHS,
142                     SDOperand &Lo, SDOperand &Hi);
143
144  void SpliceCallInto(const SDOperand &CallResult, SDNode *OutChain);
145
146  SDOperand getIntPtrConstant(uint64_t Val) {
147    return DAG.getConstant(Val, TLI.getPointerTy());
148  }
149};
150}
151
152static unsigned getScalarizedOpcode(unsigned VecOp, MVT::ValueType VT) {
153  switch (VecOp) {
154  default: assert(0 && "Don't know how to scalarize this opcode!");
155  case ISD::VADD: return MVT::isInteger(VT) ? ISD::ADD : ISD::FADD;
156  case ISD::VSUB: return MVT::isInteger(VT) ? ISD::SUB : ISD::FSUB;
157  case ISD::VMUL: return MVT::isInteger(VT) ? ISD::MUL : ISD::FMUL;
158  }
159}
160
161SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag)
162  : TLI(dag.getTargetLoweringInfo()), DAG(dag),
163    ValueTypeActions(TLI.getValueTypeActions()) {
164  assert(MVT::LAST_VALUETYPE <= 32 &&
165         "Too many value types for ValueTypeActions to hold!");
166}
167
168/// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
169/// INT_TO_FP operation of the specified operand when the target requests that
170/// we expand it.  At this point, we know that the result and operand types are
171/// legal for the target.
172SDOperand SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
173                                                     SDOperand Op0,
174                                                     MVT::ValueType DestVT) {
175  if (Op0.getValueType() == MVT::i32) {
176    // simple 32-bit [signed|unsigned] integer to float/double expansion
177
178    // get the stack frame index of a 8 byte buffer
179    MachineFunction &MF = DAG.getMachineFunction();
180    int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
181    // get address of 8 byte buffer
182    SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
183    // word offset constant for Hi/Lo address computation
184    SDOperand WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
185    // set up Hi and Lo (into buffer) address based on endian
186    SDOperand Hi, Lo;
187    if (TLI.isLittleEndian()) {
188      Hi = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot, WordOff);
189      Lo = StackSlot;
190    } else {
191      Hi = StackSlot;
192      Lo = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot, WordOff);
193    }
194    // if signed map to unsigned space
195    SDOperand Op0Mapped;
196    if (isSigned) {
197      // constant used to invert sign bit (signed to unsigned mapping)
198      SDOperand SignBit = DAG.getConstant(0x80000000u, MVT::i32);
199      Op0Mapped = DAG.getNode(ISD::XOR, MVT::i32, Op0, SignBit);
200    } else {
201      Op0Mapped = Op0;
202    }
203    // store the lo of the constructed double - based on integer input
204    SDOperand Store1 = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
205                                   Op0Mapped, Lo, DAG.getSrcValue(NULL));
206    // initial hi portion of constructed double
207    SDOperand InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
208    // store the hi of the constructed double - biased exponent
209    SDOperand Store2 = DAG.getNode(ISD::STORE, MVT::Other, Store1,
210                                   InitialHi, Hi, DAG.getSrcValue(NULL));
211    // load the constructed double
212    SDOperand Load = DAG.getLoad(MVT::f64, Store2, StackSlot,
213                               DAG.getSrcValue(NULL));
214    // FP constant to bias correct the final result
215    SDOperand Bias = DAG.getConstantFP(isSigned ?
216                                            BitsToDouble(0x4330000080000000ULL)
217                                          : BitsToDouble(0x4330000000000000ULL),
218                                     MVT::f64);
219    // subtract the bias
220    SDOperand Sub = DAG.getNode(ISD::FSUB, MVT::f64, Load, Bias);
221    // final result
222    SDOperand Result;
223    // handle final rounding
224    if (DestVT == MVT::f64) {
225      // do nothing
226      Result = Sub;
227    } else {
228     // if f32 then cast to f32
229      Result = DAG.getNode(ISD::FP_ROUND, MVT::f32, Sub);
230    }
231    NeedsAnotherIteration = true;
232    return Result;
233  }
234  assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
235  SDOperand Tmp1 = DAG.getNode(ISD::SINT_TO_FP, DestVT, Op0);
236
237  SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Op0,
238                                   DAG.getConstant(0, Op0.getValueType()),
239                                   ISD::SETLT);
240  SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
241  SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
242                                    SignSet, Four, Zero);
243
244  // If the sign bit of the integer is set, the large number will be treated
245  // as a negative number.  To counteract this, the dynamic code adds an
246  // offset depending on the data type.
247  uint64_t FF;
248  switch (Op0.getValueType()) {
249  default: assert(0 && "Unsupported integer type!");
250  case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
251  case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
252  case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
253  case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
254  }
255  if (TLI.isLittleEndian()) FF <<= 32;
256  static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
257
258  SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
259  CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
260  SDOperand FudgeInReg;
261  if (DestVT == MVT::f32)
262    FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
263                             DAG.getSrcValue(NULL));
264  else {
265    assert(DestVT == MVT::f64 && "Unexpected conversion");
266    FudgeInReg = LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, MVT::f64,
267                                           DAG.getEntryNode(), CPIdx,
268                                           DAG.getSrcValue(NULL), MVT::f32));
269  }
270
271  NeedsAnotherIteration = true;
272  return DAG.getNode(ISD::FADD, DestVT, Tmp1, FudgeInReg);
273}
274
275/// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
276/// *INT_TO_FP operation of the specified operand when the target requests that
277/// we promote it.  At this point, we know that the result and operand types are
278/// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
279/// operation that takes a larger input.
280SDOperand SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDOperand LegalOp,
281                                                      MVT::ValueType DestVT,
282                                                      bool isSigned) {
283  // First step, figure out the appropriate *INT_TO_FP operation to use.
284  MVT::ValueType NewInTy = LegalOp.getValueType();
285
286  unsigned OpToUse = 0;
287
288  // Scan for the appropriate larger type to use.
289  while (1) {
290    NewInTy = (MVT::ValueType)(NewInTy+1);
291    assert(MVT::isInteger(NewInTy) && "Ran out of possibilities!");
292
293    // If the target supports SINT_TO_FP of this type, use it.
294    switch (TLI.getOperationAction(ISD::SINT_TO_FP, NewInTy)) {
295      default: break;
296      case TargetLowering::Legal:
297        if (!TLI.isTypeLegal(NewInTy))
298          break;  // Can't use this datatype.
299        // FALL THROUGH.
300      case TargetLowering::Custom:
301        OpToUse = ISD::SINT_TO_FP;
302        break;
303    }
304    if (OpToUse) break;
305    if (isSigned) continue;
306
307    // If the target supports UINT_TO_FP of this type, use it.
308    switch (TLI.getOperationAction(ISD::UINT_TO_FP, NewInTy)) {
309      default: break;
310      case TargetLowering::Legal:
311        if (!TLI.isTypeLegal(NewInTy))
312          break;  // Can't use this datatype.
313        // FALL THROUGH.
314      case TargetLowering::Custom:
315        OpToUse = ISD::UINT_TO_FP;
316        break;
317    }
318    if (OpToUse) break;
319
320    // Otherwise, try a larger type.
321  }
322
323  // Make sure to legalize any nodes we create here in the next pass.
324  NeedsAnotherIteration = true;
325
326  // Okay, we found the operation and type to use.  Zero extend our input to the
327  // desired type then run the operation on it.
328  return DAG.getNode(OpToUse, DestVT,
329                     DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
330                                 NewInTy, LegalOp));
331}
332
333/// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
334/// FP_TO_*INT operation of the specified operand when the target requests that
335/// we promote it.  At this point, we know that the result and operand types are
336/// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
337/// operation that returns a larger result.
338SDOperand SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDOperand LegalOp,
339                                                      MVT::ValueType DestVT,
340                                                      bool isSigned) {
341  // First step, figure out the appropriate FP_TO*INT operation to use.
342  MVT::ValueType NewOutTy = DestVT;
343
344  unsigned OpToUse = 0;
345
346  // Scan for the appropriate larger type to use.
347  while (1) {
348    NewOutTy = (MVT::ValueType)(NewOutTy+1);
349    assert(MVT::isInteger(NewOutTy) && "Ran out of possibilities!");
350
351    // If the target supports FP_TO_SINT returning this type, use it.
352    switch (TLI.getOperationAction(ISD::FP_TO_SINT, NewOutTy)) {
353    default: break;
354    case TargetLowering::Legal:
355      if (!TLI.isTypeLegal(NewOutTy))
356        break;  // Can't use this datatype.
357      // FALL THROUGH.
358    case TargetLowering::Custom:
359      OpToUse = ISD::FP_TO_SINT;
360      break;
361    }
362    if (OpToUse) break;
363
364    // If the target supports FP_TO_UINT of this type, use it.
365    switch (TLI.getOperationAction(ISD::FP_TO_UINT, NewOutTy)) {
366    default: break;
367    case TargetLowering::Legal:
368      if (!TLI.isTypeLegal(NewOutTy))
369        break;  // Can't use this datatype.
370      // FALL THROUGH.
371    case TargetLowering::Custom:
372      OpToUse = ISD::FP_TO_UINT;
373      break;
374    }
375    if (OpToUse) break;
376
377    // Otherwise, try a larger type.
378  }
379
380  // Make sure to legalize any nodes we create here in the next pass.
381  NeedsAnotherIteration = true;
382
383  // Okay, we found the operation and type to use.  Truncate the result of the
384  // extended FP_TO_*INT operation to the desired size.
385  return DAG.getNode(ISD::TRUNCATE, DestVT,
386                     DAG.getNode(OpToUse, NewOutTy, LegalOp));
387}
388
389/// ComputeTopDownOrdering - Add the specified node to the Order list if it has
390/// not been visited yet and if all of its operands have already been visited.
391static void ComputeTopDownOrdering(SDNode *N, std::vector<SDNode*> &Order,
392                                   std::map<SDNode*, unsigned> &Visited) {
393  if (++Visited[N] != N->getNumOperands())
394    return;  // Haven't visited all operands yet
395
396  Order.push_back(N);
397
398  if (N->hasOneUse()) { // Tail recurse in common case.
399    ComputeTopDownOrdering(*N->use_begin(), Order, Visited);
400    return;
401  }
402
403  // Now that we have N in, add anything that uses it if all of their operands
404  // are now done.
405  for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); UI != E;++UI)
406    ComputeTopDownOrdering(*UI, Order, Visited);
407}
408
409
410void SelectionDAGLegalize::LegalizeDAG() {
411  // The legalize process is inherently a bottom-up recursive process (users
412  // legalize their uses before themselves).  Given infinite stack space, we
413  // could just start legalizing on the root and traverse the whole graph.  In
414  // practice however, this causes us to run out of stack space on large basic
415  // blocks.  To avoid this problem, compute an ordering of the nodes where each
416  // node is only legalized after all of its operands are legalized.
417  std::map<SDNode*, unsigned> Visited;
418  std::vector<SDNode*> Order;
419
420  // Compute ordering from all of the leaves in the graphs, those (like the
421  // entry node) that have no operands.
422  for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
423       E = DAG.allnodes_end(); I != E; ++I) {
424    if (I->getNumOperands() == 0) {
425      Visited[I] = 0 - 1U;
426      ComputeTopDownOrdering(I, Order, Visited);
427    }
428  }
429
430  assert(Order.size() == Visited.size() &&
431         Order.size() ==
432            (unsigned)std::distance(DAG.allnodes_begin(), DAG.allnodes_end()) &&
433         "Error: DAG is cyclic!");
434  Visited.clear();
435
436  for (unsigned i = 0, e = Order.size(); i != e; ++i) {
437    SDNode *N = Order[i];
438    switch (getTypeAction(N->getValueType(0))) {
439    default: assert(0 && "Bad type action!");
440    case Legal:
441      LegalizeOp(SDOperand(N, 0));
442      break;
443    case Promote:
444      PromoteOp(SDOperand(N, 0));
445      break;
446    case Expand: {
447      SDOperand X, Y;
448      ExpandOp(SDOperand(N, 0), X, Y);
449      break;
450    }
451    }
452  }
453
454  // Finally, it's possible the root changed.  Get the new root.
455  SDOperand OldRoot = DAG.getRoot();
456  assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
457  DAG.setRoot(LegalizedNodes[OldRoot]);
458
459  ExpandedNodes.clear();
460  LegalizedNodes.clear();
461  PromotedNodes.clear();
462
463  // Remove dead nodes now.
464  DAG.RemoveDeadNodes(OldRoot.Val);
465}
466
467SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
468  assert(isTypeLegal(Op.getValueType()) &&
469         "Caller should expand or promote operands that are not legal!");
470  SDNode *Node = Op.Val;
471
472  // If this operation defines any values that cannot be represented in a
473  // register on this target, make sure to expand or promote them.
474  if (Node->getNumValues() > 1) {
475    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
476      switch (getTypeAction(Node->getValueType(i))) {
477      case Legal: break;  // Nothing to do.
478      case Expand: {
479        SDOperand T1, T2;
480        ExpandOp(Op.getValue(i), T1, T2);
481        assert(LegalizedNodes.count(Op) &&
482               "Expansion didn't add legal operands!");
483        return LegalizedNodes[Op];
484      }
485      case Promote:
486        PromoteOp(Op.getValue(i));
487        assert(LegalizedNodes.count(Op) &&
488               "Expansion didn't add legal operands!");
489        return LegalizedNodes[Op];
490      }
491  }
492
493  // Note that LegalizeOp may be reentered even from single-use nodes, which
494  // means that we always must cache transformed nodes.
495  std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
496  if (I != LegalizedNodes.end()) return I->second;
497
498  SDOperand Tmp1, Tmp2, Tmp3, Tmp4;
499
500  SDOperand Result = Op;
501
502  switch (Node->getOpcode()) {
503  default:
504    if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
505      // If this is a target node, legalize it by legalizing the operands then
506      // passing it through.
507      std::vector<SDOperand> Ops;
508      bool Changed = false;
509      for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
510        Ops.push_back(LegalizeOp(Node->getOperand(i)));
511        Changed = Changed || Node->getOperand(i) != Ops.back();
512      }
513      if (Changed)
514        if (Node->getNumValues() == 1)
515          Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Ops);
516        else {
517          std::vector<MVT::ValueType> VTs(Node->value_begin(),
518                                          Node->value_end());
519          Result = DAG.getNode(Node->getOpcode(), VTs, Ops);
520        }
521
522      for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
523        AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
524      return Result.getValue(Op.ResNo);
525    }
526    // Otherwise this is an unhandled builtin node.  splat.
527    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
528    assert(0 && "Do not know how to legalize this operator!");
529    abort();
530  case ISD::EntryToken:
531  case ISD::FrameIndex:
532  case ISD::TargetFrameIndex:
533  case ISD::Register:
534  case ISD::TargetConstant:
535  case ISD::TargetConstantPool:
536  case ISD::GlobalAddress:
537  case ISD::TargetGlobalAddress:
538  case ISD::ExternalSymbol:
539  case ISD::ConstantPool:           // Nothing to do.
540  case ISD::BasicBlock:
541  case ISD::CONDCODE:
542  case ISD::VALUETYPE:
543  case ISD::SRCVALUE:
544  case ISD::STRING:
545    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
546    default: assert(0 && "This action is not supported yet!");
547    case TargetLowering::Custom: {
548      SDOperand Tmp = TLI.LowerOperation(Op, DAG);
549      if (Tmp.Val) {
550        Result = LegalizeOp(Tmp);
551        break;
552      }
553    } // FALLTHROUGH if the target doesn't want to lower this op after all.
554    case TargetLowering::Legal:
555      assert(isTypeLegal(Node->getValueType(0)) && "This must be legal!");
556      break;
557    }
558    break;
559  case ISD::AssertSext:
560  case ISD::AssertZext:
561    Tmp1 = LegalizeOp(Node->getOperand(0));
562    if (Tmp1 != Node->getOperand(0))
563      Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
564                           Node->getOperand(1));
565    break;
566  case ISD::MERGE_VALUES:
567    return LegalizeOp(Node->getOperand(Op.ResNo));
568  case ISD::CopyFromReg:
569    Tmp1 = LegalizeOp(Node->getOperand(0));
570    if (Tmp1 != Node->getOperand(0))
571      Result = DAG.getCopyFromReg(Tmp1,
572                            cast<RegisterSDNode>(Node->getOperand(1))->getReg(),
573                                  Node->getValueType(0));
574    else
575      Result = Op.getValue(0);
576
577    // Since CopyFromReg produces two values, make sure to remember that we
578    // legalized both of them.
579    AddLegalizedOperand(Op.getValue(0), Result);
580    AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
581    return Result.getValue(Op.ResNo);
582  case ISD::ImplicitDef:
583    Tmp1 = LegalizeOp(Node->getOperand(0));
584    if (Tmp1 != Node->getOperand(0))
585      Result = DAG.getNode(ISD::ImplicitDef, MVT::Other,
586                           Tmp1, Node->getOperand(1));
587    break;
588  case ISD::UNDEF: {
589    MVT::ValueType VT = Op.getValueType();
590    switch (TLI.getOperationAction(ISD::UNDEF, VT)) {
591    default: assert(0 && "This action is not supported yet!");
592    case TargetLowering::Expand:
593    case TargetLowering::Promote:
594      if (MVT::isInteger(VT))
595        Result = DAG.getConstant(0, VT);
596      else if (MVT::isFloatingPoint(VT))
597        Result = DAG.getConstantFP(0, VT);
598      else
599        assert(0 && "Unknown value type!");
600      break;
601    case TargetLowering::Legal:
602      break;
603    }
604    break;
605  }
606
607  case ISD::LOCATION:
608    assert(Node->getNumOperands() == 5 && "Invalid LOCATION node!");
609    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the input chain.
610
611    switch (TLI.getOperationAction(ISD::LOCATION, MVT::Other)) {
612    case TargetLowering::Promote:
613    default: assert(0 && "This action is not supported yet!");
614    case TargetLowering::Expand: {
615        MachineDebugInfo &DebugInfo = DAG.getMachineFunction().getDebugInfo();
616        std::vector<SDOperand> Ops;
617        Ops.push_back(Tmp1);  // chain
618        Ops.push_back(Node->getOperand(1));  // line #
619        Ops.push_back(Node->getOperand(2));  // col #
620        const std::string &fname = cast<StringSDNode>(Node->getOperand(3))->getValue();
621        const std::string &dirname=cast<StringSDNode>(Node->getOperand(4))->getValue();
622        unsigned id = DebugInfo.RecordSource(fname, dirname);
623        Ops.push_back(DAG.getConstant(id, MVT::i32));  // source file id
624        Result = DAG.getNode(ISD::DEBUG_LOC, MVT::Other, Ops);
625      }
626      break;
627    case TargetLowering::Legal:
628      if (Tmp1 != Node->getOperand(0) ||
629          getTypeAction(Node->getOperand(1).getValueType()) == Promote) {
630        std::vector<SDOperand> Ops;
631        Ops.push_back(Tmp1);
632        if (getTypeAction(Node->getOperand(1).getValueType()) == Legal) {
633          Ops.push_back(Node->getOperand(1));  // line # must be legal.
634          Ops.push_back(Node->getOperand(2));  // col # must be legal.
635        } else {
636          // Otherwise promote them.
637          Ops.push_back(PromoteOp(Node->getOperand(1)));
638          Ops.push_back(PromoteOp(Node->getOperand(2)));
639        }
640        Ops.push_back(Node->getOperand(3));  // filename must be legal.
641        Ops.push_back(Node->getOperand(4));  // working dir # must be legal.
642        Result = DAG.getNode(ISD::LOCATION, MVT::Other, Ops);
643      }
644      break;
645    }
646    break;
647
648  case ISD::DEBUG_LOC:
649    assert(Node->getNumOperands() == 4 && "Invalid DEBUG_LOC node!");
650    switch (TLI.getOperationAction(ISD::DEBUG_LOC, MVT::Other)) {
651    case TargetLowering::Promote:
652    case TargetLowering::Expand:
653    default: assert(0 && "This action is not supported yet!");
654    case TargetLowering::Legal:
655      Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
656      Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the line #.
657      Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the col #.
658      Tmp4 = LegalizeOp(Node->getOperand(3));  // Legalize the source file id.
659
660      if (Tmp1 != Node->getOperand(0) ||
661          Tmp2 != Node->getOperand(1) ||
662          Tmp3 != Node->getOperand(2) ||
663          Tmp4 != Node->getOperand(3)) {
664        Result = DAG.getNode(ISD::DEBUG_LOC,MVT::Other, Tmp1, Tmp2, Tmp3, Tmp4);
665      }
666      break;
667    }
668    break;
669
670  case ISD::Constant:
671    // We know we don't need to expand constants here, constants only have one
672    // value and we check that it is fine above.
673
674    // FIXME: Maybe we should handle things like targets that don't support full
675    // 32-bit immediates?
676    break;
677  case ISD::ConstantFP: {
678    // Spill FP immediates to the constant pool if the target cannot directly
679    // codegen them.  Targets often have some immediate values that can be
680    // efficiently generated into an FP register without a load.  We explicitly
681    // leave these constants as ConstantFP nodes for the target to deal with.
682
683    ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
684
685    // Check to see if this FP immediate is already legal.
686    bool isLegal = false;
687    for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
688           E = TLI.legal_fpimm_end(); I != E; ++I)
689      if (CFP->isExactlyValue(*I)) {
690        isLegal = true;
691        break;
692      }
693
694    if (!isLegal) {
695      // Otherwise we need to spill the constant to memory.
696      bool Extend = false;
697
698      // If a FP immediate is precise when represented as a float, we put it
699      // into the constant pool as a float, even if it's is statically typed
700      // as a double.
701      MVT::ValueType VT = CFP->getValueType(0);
702      bool isDouble = VT == MVT::f64;
703      ConstantFP *LLVMC = ConstantFP::get(isDouble ? Type::DoubleTy :
704                                             Type::FloatTy, CFP->getValue());
705      if (isDouble && CFP->isExactlyValue((float)CFP->getValue()) &&
706          // Only do this if the target has a native EXTLOAD instruction from
707          // f32.
708          TLI.isOperationLegal(ISD::EXTLOAD, MVT::f32)) {
709        LLVMC = cast<ConstantFP>(ConstantExpr::getCast(LLVMC, Type::FloatTy));
710        VT = MVT::f32;
711        Extend = true;
712      }
713
714      SDOperand CPIdx =
715        LegalizeOp(DAG.getConstantPool(LLVMC, TLI.getPointerTy()));
716      if (Extend) {
717        Result = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
718                                CPIdx, DAG.getSrcValue(NULL), MVT::f32);
719      } else {
720        Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
721                             DAG.getSrcValue(NULL));
722      }
723    }
724    break;
725  }
726  case ISD::ConstantVec: {
727    // We assume that vector constants are not legal, and will be immediately
728    // spilled to the constant pool.
729    //
730    // FIXME: revisit this when we have some kind of mechanism by which targets
731    // can decided legality of vector constants, of which there may be very
732    // many.
733    //
734    // Create a ConstantPacked, and put it in the constant pool.
735    std::vector<Constant*> CV;
736    MVT::ValueType VT = Node->getValueType(0);
737    for (unsigned I = 0, E = Node->getNumOperands(); I < E; ++I) {
738      SDOperand OpN = Node->getOperand(I);
739      const Type* OpNTy = MVT::getTypeForValueType(OpN.getValueType());
740      if (MVT::isFloatingPoint(VT))
741        CV.push_back(ConstantFP::get(OpNTy,
742                                     cast<ConstantFPSDNode>(OpN)->getValue()));
743      else
744        CV.push_back(ConstantUInt::get(OpNTy,
745                                       cast<ConstantSDNode>(OpN)->getValue()));
746    }
747    Constant *CP = ConstantPacked::get(CV);
748    SDOperand CPIdx = LegalizeOp(DAG.getConstantPool(CP, TLI.getPointerTy()));
749    Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, DAG.getSrcValue(NULL));
750    break;
751  }
752  case ISD::TokenFactor:
753    if (Node->getNumOperands() == 2) {
754      bool Changed = false;
755      SDOperand Op0 = LegalizeOp(Node->getOperand(0));
756      SDOperand Op1 = LegalizeOp(Node->getOperand(1));
757      if (Op0 != Node->getOperand(0) || Op1 != Node->getOperand(1))
758        Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);
759    } else {
760      std::vector<SDOperand> Ops;
761      bool Changed = false;
762      // Legalize the operands.
763      for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
764        SDOperand Op = Node->getOperand(i);
765        Ops.push_back(LegalizeOp(Op));
766        Changed |= Ops[i] != Op;
767      }
768      if (Changed)
769        Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Ops);
770    }
771    break;
772
773  case ISD::CALLSEQ_START:
774  case ISD::CALLSEQ_END:
775    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
776    // Do not try to legalize the target-specific arguments (#1+)
777    Tmp2 = Node->getOperand(0);
778    if (Tmp1 != Tmp2)
779      Node->setAdjCallChain(Tmp1);
780
781    // Note that we do not create new CALLSEQ_DOWN/UP nodes here.  These
782    // nodes are treated specially and are mutated in place.  This makes the dag
783    // legalization process more efficient and also makes libcall insertion
784    // easier.
785    break;
786  case ISD::DYNAMIC_STACKALLOC:
787    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
788    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
789    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
790    if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
791        Tmp3 != Node->getOperand(2)) {
792      std::vector<MVT::ValueType> VTs(Node->value_begin(), Node->value_end());
793      std::vector<SDOperand> Ops;
794      Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
795      Result = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
796    } else
797      Result = Op.getValue(0);
798
799    // Since this op produces two values, make sure to remember that we
800    // legalized both of them.
801    AddLegalizedOperand(SDOperand(Node, 0), Result);
802    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
803    return Result.getValue(Op.ResNo);
804
805  case ISD::TAILCALL:
806  case ISD::CALL: {
807    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
808    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
809
810    bool Changed = false;
811    std::vector<SDOperand> Ops;
812    for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i) {
813      Ops.push_back(LegalizeOp(Node->getOperand(i)));
814      Changed |= Ops.back() != Node->getOperand(i);
815    }
816
817    if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) || Changed) {
818      std::vector<MVT::ValueType> RetTyVTs;
819      RetTyVTs.reserve(Node->getNumValues());
820      for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
821        RetTyVTs.push_back(Node->getValueType(i));
822      Result = SDOperand(DAG.getCall(RetTyVTs, Tmp1, Tmp2, Ops,
823                                     Node->getOpcode() == ISD::TAILCALL), 0);
824    } else {
825      Result = Result.getValue(0);
826    }
827    // Since calls produce multiple values, make sure to remember that we
828    // legalized all of them.
829    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
830      AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
831    return Result.getValue(Op.ResNo);
832  }
833  case ISD::BR:
834    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
835    if (Tmp1 != Node->getOperand(0))
836      Result = DAG.getNode(ISD::BR, MVT::Other, Tmp1, Node->getOperand(1));
837    break;
838
839  case ISD::BRCOND:
840    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
841
842    switch (getTypeAction(Node->getOperand(1).getValueType())) {
843    case Expand: assert(0 && "It's impossible to expand bools");
844    case Legal:
845      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
846      break;
847    case Promote:
848      Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
849      break;
850    }
851
852    switch (TLI.getOperationAction(ISD::BRCOND, MVT::Other)) {
853    default: assert(0 && "This action is not supported yet!");
854    case TargetLowering::Expand:
855      // Expand brcond's setcc into its constituent parts and create a BR_CC
856      // Node.
857      if (Tmp2.getOpcode() == ISD::SETCC) {
858        Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Tmp2.getOperand(2),
859                             Tmp2.getOperand(0), Tmp2.getOperand(1),
860                             Node->getOperand(2));
861      } else {
862        // Make sure the condition is either zero or one.  It may have been
863        // promoted from something else.
864        Tmp2 = DAG.getZeroExtendInReg(Tmp2, MVT::i1);
865
866        Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1,
867                             DAG.getCondCode(ISD::SETNE), Tmp2,
868                             DAG.getConstant(0, Tmp2.getValueType()),
869                             Node->getOperand(2));
870      }
871      break;
872    case TargetLowering::Legal:
873      // Basic block destination (Op#2) is always legal.
874      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
875        Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
876                             Node->getOperand(2));
877        break;
878    }
879    break;
880  case ISD::BR_CC:
881    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
882    if (!isTypeLegal(Node->getOperand(2).getValueType())) {
883      Tmp2 = LegalizeOp(DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),
884                                    Node->getOperand(2),  // LHS
885                                    Node->getOperand(3),  // RHS
886                                    Node->getOperand(1)));
887      // If we get a SETCC back from legalizing the SETCC node we just
888      // created, then use its LHS, RHS, and CC directly in creating a new
889      // node.  Otherwise, select between the true and false value based on
890      // comparing the result of the legalized with zero.
891      if (Tmp2.getOpcode() == ISD::SETCC) {
892        Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Tmp2.getOperand(2),
893                             Tmp2.getOperand(0), Tmp2.getOperand(1),
894                             Node->getOperand(4));
895      } else {
896        Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1,
897                             DAG.getCondCode(ISD::SETNE),
898                             Tmp2, DAG.getConstant(0, Tmp2.getValueType()),
899                             Node->getOperand(4));
900      }
901      break;
902    }
903
904    Tmp2 = LegalizeOp(Node->getOperand(2));   // LHS
905    Tmp3 = LegalizeOp(Node->getOperand(3));   // RHS
906
907    switch (TLI.getOperationAction(ISD::BR_CC, Tmp3.getValueType())) {
908    default: assert(0 && "Unexpected action for BR_CC!");
909    case TargetLowering::Custom: {
910      Tmp4 = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Node->getOperand(1),
911                         Tmp2, Tmp3, Node->getOperand(4));
912      Tmp4 = TLI.LowerOperation(Tmp4, DAG);
913      if (Tmp4.Val) {
914        Result = LegalizeOp(Tmp4);
915        break;
916      }
917    } // FALLTHROUGH if the target doesn't want to lower this op after all.
918    case TargetLowering::Legal:
919      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(2) ||
920          Tmp3 != Node->getOperand(3)) {
921        Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Node->getOperand(1),
922                             Tmp2, Tmp3, Node->getOperand(4));
923      }
924      break;
925    }
926    break;
927  case ISD::BRCONDTWOWAY:
928    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
929    switch (getTypeAction(Node->getOperand(1).getValueType())) {
930    case Expand: assert(0 && "It's impossible to expand bools");
931    case Legal:
932      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
933      break;
934    case Promote:
935      Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
936      break;
937    }
938    // If this target does not support BRCONDTWOWAY, lower it to a BRCOND/BR
939    // pair.
940    switch (TLI.getOperationAction(ISD::BRCONDTWOWAY, MVT::Other)) {
941    case TargetLowering::Promote:
942    default: assert(0 && "This action is not supported yet!");
943    case TargetLowering::Legal:
944      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1)) {
945        std::vector<SDOperand> Ops;
946        Ops.push_back(Tmp1);
947        Ops.push_back(Tmp2);
948        Ops.push_back(Node->getOperand(2));
949        Ops.push_back(Node->getOperand(3));
950        Result = DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops);
951      }
952      break;
953    case TargetLowering::Expand:
954      // If BRTWOWAY_CC is legal for this target, then simply expand this node
955      // to that.  Otherwise, skip BRTWOWAY_CC and expand directly to a
956      // BRCOND/BR pair.
957      if (TLI.isOperationLegal(ISD::BRTWOWAY_CC, MVT::Other)) {
958        if (Tmp2.getOpcode() == ISD::SETCC) {
959          Result = DAG.getBR2Way_CC(Tmp1, Tmp2.getOperand(2),
960                                    Tmp2.getOperand(0), Tmp2.getOperand(1),
961                                    Node->getOperand(2), Node->getOperand(3));
962        } else {
963          Result = DAG.getBR2Way_CC(Tmp1, DAG.getCondCode(ISD::SETNE), Tmp2,
964                                    DAG.getConstant(0, Tmp2.getValueType()),
965                                    Node->getOperand(2), Node->getOperand(3));
966        }
967      } else {
968        Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
969                           Node->getOperand(2));
970        Result = DAG.getNode(ISD::BR, MVT::Other, Result, Node->getOperand(3));
971      }
972      break;
973    }
974    break;
975  case ISD::BRTWOWAY_CC:
976    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
977    if (isTypeLegal(Node->getOperand(2).getValueType())) {
978      Tmp2 = LegalizeOp(Node->getOperand(2));   // LHS
979      Tmp3 = LegalizeOp(Node->getOperand(3));   // RHS
980      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(2) ||
981          Tmp3 != Node->getOperand(3)) {
982        Result = DAG.getBR2Way_CC(Tmp1, Node->getOperand(1), Tmp2, Tmp3,
983                                  Node->getOperand(4), Node->getOperand(5));
984      }
985      break;
986    } else {
987      Tmp2 = LegalizeOp(DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),
988                                    Node->getOperand(2),  // LHS
989                                    Node->getOperand(3),  // RHS
990                                    Node->getOperand(1)));
991      // If this target does not support BRTWOWAY_CC, lower it to a BRCOND/BR
992      // pair.
993      switch (TLI.getOperationAction(ISD::BRTWOWAY_CC, MVT::Other)) {
994      default: assert(0 && "This action is not supported yet!");
995      case TargetLowering::Legal:
996        // If we get a SETCC back from legalizing the SETCC node we just
997        // created, then use its LHS, RHS, and CC directly in creating a new
998        // node.  Otherwise, select between the true and false value based on
999        // comparing the result of the legalized with zero.
1000        if (Tmp2.getOpcode() == ISD::SETCC) {
1001          Result = DAG.getBR2Way_CC(Tmp1, Tmp2.getOperand(2),
1002                                    Tmp2.getOperand(0), Tmp2.getOperand(1),
1003                                    Node->getOperand(4), Node->getOperand(5));
1004        } else {
1005          Result = DAG.getBR2Way_CC(Tmp1, DAG.getCondCode(ISD::SETNE), Tmp2,
1006                                    DAG.getConstant(0, Tmp2.getValueType()),
1007                                    Node->getOperand(4), Node->getOperand(5));
1008        }
1009        break;
1010      case TargetLowering::Expand:
1011        Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
1012                             Node->getOperand(4));
1013        Result = DAG.getNode(ISD::BR, MVT::Other, Result, Node->getOperand(5));
1014        break;
1015      }
1016    }
1017    break;
1018  case ISD::LOAD:
1019    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1020    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1021
1022    if (Tmp1 != Node->getOperand(0) ||
1023        Tmp2 != Node->getOperand(1))
1024      Result = DAG.getLoad(Node->getValueType(0), Tmp1, Tmp2,
1025                           Node->getOperand(2));
1026    else
1027      Result = SDOperand(Node, 0);
1028
1029    // Since loads produce two values, make sure to remember that we legalized
1030    // both of them.
1031    AddLegalizedOperand(SDOperand(Node, 0), Result);
1032    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1033    return Result.getValue(Op.ResNo);
1034
1035  case ISD::EXTLOAD:
1036  case ISD::SEXTLOAD:
1037  case ISD::ZEXTLOAD: {
1038    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1039    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1040
1041    MVT::ValueType SrcVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
1042    switch (TLI.getOperationAction(Node->getOpcode(), SrcVT)) {
1043    default: assert(0 && "This action is not supported yet!");
1044    case TargetLowering::Promote:
1045      assert(SrcVT == MVT::i1 && "Can only promote EXTLOAD from i1 -> i8!");
1046      Result = DAG.getExtLoad(Node->getOpcode(), Node->getValueType(0),
1047                              Tmp1, Tmp2, Node->getOperand(2), MVT::i8);
1048      // Since loads produce two values, make sure to remember that we legalized
1049      // both of them.
1050      AddLegalizedOperand(SDOperand(Node, 0), Result);
1051      AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1052      return Result.getValue(Op.ResNo);
1053
1054    case TargetLowering::Legal:
1055      if (Tmp1 != Node->getOperand(0) ||
1056          Tmp2 != Node->getOperand(1))
1057        Result = DAG.getExtLoad(Node->getOpcode(), Node->getValueType(0),
1058                                Tmp1, Tmp2, Node->getOperand(2), SrcVT);
1059      else
1060        Result = SDOperand(Node, 0);
1061
1062      // Since loads produce two values, make sure to remember that we legalized
1063      // both of them.
1064      AddLegalizedOperand(SDOperand(Node, 0), Result);
1065      AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1066      return Result.getValue(Op.ResNo);
1067    case TargetLowering::Expand:
1068      //f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
1069      if (SrcVT == MVT::f32 && Node->getValueType(0) == MVT::f64) {
1070        SDOperand Load = DAG.getLoad(SrcVT, Tmp1, Tmp2, Node->getOperand(2));
1071        Result = DAG.getNode(ISD::FP_EXTEND, Node->getValueType(0), Load);
1072        if (Op.ResNo)
1073          return Load.getValue(1);
1074        return Result;
1075      }
1076      assert(Node->getOpcode() != ISD::EXTLOAD &&
1077             "EXTLOAD should always be supported!");
1078      // Turn the unsupported load into an EXTLOAD followed by an explicit
1079      // zero/sign extend inreg.
1080      Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
1081                              Tmp1, Tmp2, Node->getOperand(2), SrcVT);
1082      SDOperand ValRes;
1083      if (Node->getOpcode() == ISD::SEXTLOAD)
1084        ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1085                             Result, DAG.getValueType(SrcVT));
1086      else
1087        ValRes = DAG.getZeroExtendInReg(Result, SrcVT);
1088      AddLegalizedOperand(SDOperand(Node, 0), ValRes);
1089      AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1090      if (Op.ResNo)
1091        return Result.getValue(1);
1092      return ValRes;
1093    }
1094    assert(0 && "Unreachable");
1095  }
1096  case ISD::EXTRACT_ELEMENT: {
1097    MVT::ValueType OpTy = Node->getOperand(0).getValueType();
1098    switch (getTypeAction(OpTy)) {
1099    default:
1100      assert(0 && "EXTRACT_ELEMENT action for type unimplemented!");
1101      break;
1102    case Legal:
1103      if (cast<ConstantSDNode>(Node->getOperand(1))->getValue()) {
1104        // 1 -> Hi
1105        Result = DAG.getNode(ISD::SRL, OpTy, Node->getOperand(0),
1106                             DAG.getConstant(MVT::getSizeInBits(OpTy)/2,
1107                                             TLI.getShiftAmountTy()));
1108        Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Result);
1109      } else {
1110        // 0 -> Lo
1111        Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0),
1112                             Node->getOperand(0));
1113      }
1114      Result = LegalizeOp(Result);
1115      break;
1116    case Expand:
1117      // Get both the low and high parts.
1118      ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
1119      if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
1120        Result = Tmp2;  // 1 -> Hi
1121      else
1122        Result = Tmp1;  // 0 -> Lo
1123      break;
1124    }
1125    break;
1126  }
1127
1128  case ISD::CopyToReg:
1129    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1130
1131    assert(isTypeLegal(Node->getOperand(2).getValueType()) &&
1132           "Register type must be legal!");
1133    // Legalize the incoming value (must be legal).
1134    Tmp2 = LegalizeOp(Node->getOperand(2));
1135    if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(2))
1136      Result = DAG.getNode(ISD::CopyToReg, MVT::Other, Tmp1,
1137                           Node->getOperand(1), Tmp2);
1138    break;
1139
1140  case ISD::RET:
1141    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1142    switch (Node->getNumOperands()) {
1143    case 2:  // ret val
1144      switch (getTypeAction(Node->getOperand(1).getValueType())) {
1145      case Legal:
1146        Tmp2 = LegalizeOp(Node->getOperand(1));
1147        if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
1148          Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
1149        break;
1150      case Expand: {
1151        SDOperand Lo, Hi;
1152        ExpandOp(Node->getOperand(1), Lo, Hi);
1153        Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
1154        break;
1155      }
1156      case Promote:
1157        Tmp2 = PromoteOp(Node->getOperand(1));
1158        Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
1159        break;
1160      }
1161      break;
1162    case 1:  // ret void
1163      if (Tmp1 != Node->getOperand(0))
1164        Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1);
1165      break;
1166    default: { // ret <values>
1167      std::vector<SDOperand> NewValues;
1168      NewValues.push_back(Tmp1);
1169      for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1170        switch (getTypeAction(Node->getOperand(i).getValueType())) {
1171        case Legal:
1172          NewValues.push_back(LegalizeOp(Node->getOperand(i)));
1173          break;
1174        case Expand: {
1175          SDOperand Lo, Hi;
1176          ExpandOp(Node->getOperand(i), Lo, Hi);
1177          NewValues.push_back(Lo);
1178          NewValues.push_back(Hi);
1179          break;
1180        }
1181        case Promote:
1182          assert(0 && "Can't promote multiple return value yet!");
1183        }
1184      Result = DAG.getNode(ISD::RET, MVT::Other, NewValues);
1185      break;
1186    }
1187    }
1188    break;
1189  case ISD::STORE:
1190    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1191    Tmp2 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
1192
1193    // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
1194    if (ConstantFPSDNode *CFP =dyn_cast<ConstantFPSDNode>(Node->getOperand(1))){
1195      if (CFP->getValueType(0) == MVT::f32) {
1196        Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
1197                             DAG.getConstant(FloatToBits(CFP->getValue()),
1198                                             MVT::i32),
1199                             Tmp2,
1200                             Node->getOperand(3));
1201      } else {
1202        assert(CFP->getValueType(0) == MVT::f64 && "Unknown FP type!");
1203        Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
1204                             DAG.getConstant(DoubleToBits(CFP->getValue()),
1205                                             MVT::i64),
1206                             Tmp2,
1207                             Node->getOperand(3));
1208      }
1209      Node = Result.Val;
1210    }
1211
1212    switch (getTypeAction(Node->getOperand(1).getValueType())) {
1213    case Legal: {
1214      SDOperand Val = LegalizeOp(Node->getOperand(1));
1215      if (Val != Node->getOperand(1) || Tmp1 != Node->getOperand(0) ||
1216          Tmp2 != Node->getOperand(2))
1217        Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Val, Tmp2,
1218                             Node->getOperand(3));
1219      break;
1220    }
1221    case Promote:
1222      // Truncate the value and store the result.
1223      Tmp3 = PromoteOp(Node->getOperand(1));
1224      Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp3, Tmp2,
1225                           Node->getOperand(3),
1226                          DAG.getValueType(Node->getOperand(1).getValueType()));
1227      break;
1228
1229    case Expand:
1230      SDOperand Lo, Hi;
1231      unsigned IncrementSize;
1232      ExpandOp(Node->getOperand(1), Lo, Hi);
1233
1234      if (!TLI.isLittleEndian())
1235        std::swap(Lo, Hi);
1236
1237      Lo = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Lo, Tmp2,
1238                       Node->getOperand(3));
1239      // If this is a vector type, then we have to calculate the increment as
1240      // the product of the element size in bytes, and the number of elements
1241      // in the high half of the vector.
1242      if (MVT::Vector == Hi.getValueType()) {
1243        unsigned NumElems = cast<ConstantSDNode>(Hi.getOperand(2))->getValue();
1244        MVT::ValueType EVT = cast<VTSDNode>(Hi.getOperand(3))->getVT();
1245        IncrementSize = NumElems * MVT::getSizeInBits(EVT)/8;
1246      } else {
1247        IncrementSize = MVT::getSizeInBits(Hi.getValueType())/8;
1248      }
1249      Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
1250                         getIntPtrConstant(IncrementSize));
1251      assert(isTypeLegal(Tmp2.getValueType()) &&
1252             "Pointers must be legal!");
1253      //Again, claiming both parts of the store came form the same Instr
1254      Hi = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Hi, Tmp2,
1255                       Node->getOperand(3));
1256      Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
1257      break;
1258    }
1259    break;
1260  case ISD::PCMARKER:
1261    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1262    if (Tmp1 != Node->getOperand(0))
1263      Result = DAG.getNode(ISD::PCMARKER, MVT::Other, Tmp1,Node->getOperand(1));
1264    break;
1265  case ISD::READCYCLECOUNTER:
1266    Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain
1267    if (Tmp1 != Node->getOperand(0)) {
1268      std::vector<MVT::ValueType> rtypes;
1269      std::vector<SDOperand> rvals;
1270      rtypes.push_back(MVT::i64);
1271      rtypes.push_back(MVT::Other);
1272      rvals.push_back(Tmp1);
1273      Result = DAG.getNode(ISD::READCYCLECOUNTER, rtypes, rvals);
1274    }
1275
1276    // Since rdcc produce two values, make sure to remember that we legalized
1277    // both of them.
1278    AddLegalizedOperand(SDOperand(Node, 0), Result);
1279    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1280    return Result.getValue(Op.ResNo);
1281    break;
1282
1283  case ISD::TRUNCSTORE:
1284    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1285    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
1286
1287    switch (getTypeAction(Node->getOperand(1).getValueType())) {
1288    case Legal:
1289      Tmp2 = LegalizeOp(Node->getOperand(1));
1290
1291      // The only promote case we handle is TRUNCSTORE:i1 X into
1292      //   -> TRUNCSTORE:i8 (and X, 1)
1293      if (cast<VTSDNode>(Node->getOperand(4))->getVT() == MVT::i1 &&
1294          TLI.getOperationAction(ISD::TRUNCSTORE, MVT::i1) ==
1295                TargetLowering::Promote) {
1296        // Promote the bool to a mask then store.
1297        Tmp2 = DAG.getNode(ISD::AND, Tmp2.getValueType(), Tmp2,
1298                           DAG.getConstant(1, Tmp2.getValueType()));
1299        Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
1300                             Node->getOperand(3), DAG.getValueType(MVT::i8));
1301
1302      } else if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1303                 Tmp3 != Node->getOperand(2)) {
1304        Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
1305                             Node->getOperand(3), Node->getOperand(4));
1306      }
1307      break;
1308    case Promote:
1309    case Expand:
1310      assert(0 && "Cannot handle illegal TRUNCSTORE yet!");
1311    }
1312    break;
1313  case ISD::SELECT:
1314    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1315    case Expand: assert(0 && "It's impossible to expand bools");
1316    case Legal:
1317      Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
1318      break;
1319    case Promote:
1320      Tmp1 = PromoteOp(Node->getOperand(0));  // Promote the condition.
1321      break;
1322    }
1323    Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
1324    Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
1325
1326    switch (TLI.getOperationAction(ISD::SELECT, Tmp2.getValueType())) {
1327    default: assert(0 && "This action is not supported yet!");
1328    case TargetLowering::Expand:
1329      if (Tmp1.getOpcode() == ISD::SETCC) {
1330        Result = DAG.getSelectCC(Tmp1.getOperand(0), Tmp1.getOperand(1),
1331                              Tmp2, Tmp3,
1332                              cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
1333      } else {
1334        // Make sure the condition is either zero or one.  It may have been
1335        // promoted from something else.
1336        Tmp1 = DAG.getZeroExtendInReg(Tmp1, MVT::i1);
1337        Result = DAG.getSelectCC(Tmp1,
1338                                 DAG.getConstant(0, Tmp1.getValueType()),
1339                                 Tmp2, Tmp3, ISD::SETNE);
1340      }
1341      break;
1342    case TargetLowering::Custom: {
1343      SDOperand Tmp =
1344        TLI.LowerOperation(DAG.getNode(ISD::SELECT, Node->getValueType(0),
1345                                       Tmp1, Tmp2, Tmp3), DAG);
1346      if (Tmp.Val) {
1347        Result = LegalizeOp(Tmp);
1348        break;
1349      }
1350      // FALLTHROUGH if the target thinks it is legal.
1351    }
1352    case TargetLowering::Legal:
1353      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1354          Tmp3 != Node->getOperand(2))
1355        Result = DAG.getNode(ISD::SELECT, Node->getValueType(0),
1356                             Tmp1, Tmp2, Tmp3);
1357      break;
1358    case TargetLowering::Promote: {
1359      MVT::ValueType NVT =
1360        TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
1361      unsigned ExtOp, TruncOp;
1362      if (MVT::isInteger(Tmp2.getValueType())) {
1363        ExtOp = ISD::ANY_EXTEND;
1364        TruncOp  = ISD::TRUNCATE;
1365      } else {
1366        ExtOp = ISD::FP_EXTEND;
1367        TruncOp  = ISD::FP_ROUND;
1368      }
1369      // Promote each of the values to the new type.
1370      Tmp2 = DAG.getNode(ExtOp, NVT, Tmp2);
1371      Tmp3 = DAG.getNode(ExtOp, NVT, Tmp3);
1372      // Perform the larger operation, then round down.
1373      Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2,Tmp3);
1374      Result = DAG.getNode(TruncOp, Node->getValueType(0), Result);
1375      break;
1376    }
1377    }
1378    break;
1379  case ISD::SELECT_CC:
1380    Tmp3 = LegalizeOp(Node->getOperand(2));   // True
1381    Tmp4 = LegalizeOp(Node->getOperand(3));   // False
1382
1383    if (isTypeLegal(Node->getOperand(0).getValueType())) {
1384      // Everything is legal, see if we should expand this op or something.
1385      switch (TLI.getOperationAction(ISD::SELECT_CC,
1386                                     Node->getOperand(0).getValueType())) {
1387      default: assert(0 && "This action is not supported yet!");
1388      case TargetLowering::Custom: {
1389        SDOperand Tmp =
1390          TLI.LowerOperation(DAG.getNode(ISD::SELECT_CC, Node->getValueType(0),
1391                                         Node->getOperand(0),
1392                                         Node->getOperand(1), Tmp3, Tmp4,
1393                                         Node->getOperand(4)), DAG);
1394        if (Tmp.Val) {
1395          Result = LegalizeOp(Tmp);
1396          break;
1397        }
1398      } // FALLTHROUGH if the target can't lower this operation after all.
1399      case TargetLowering::Legal:
1400        Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
1401        Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
1402        if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1403            Tmp3 != Node->getOperand(2) || Tmp4 != Node->getOperand(3)) {
1404          Result = DAG.getNode(ISD::SELECT_CC, Node->getValueType(0), Tmp1, Tmp2,
1405                               Tmp3, Tmp4, Node->getOperand(4));
1406        }
1407        break;
1408      }
1409      break;
1410    } else {
1411      Tmp1 = LegalizeOp(DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),
1412                                    Node->getOperand(0),  // LHS
1413                                    Node->getOperand(1),  // RHS
1414                                    Node->getOperand(4)));
1415      // If we get a SETCC back from legalizing the SETCC node we just
1416      // created, then use its LHS, RHS, and CC directly in creating a new
1417      // node.  Otherwise, select between the true and false value based on
1418      // comparing the result of the legalized with zero.
1419      if (Tmp1.getOpcode() == ISD::SETCC) {
1420        Result = DAG.getNode(ISD::SELECT_CC, Tmp3.getValueType(),
1421                             Tmp1.getOperand(0), Tmp1.getOperand(1),
1422                             Tmp3, Tmp4, Tmp1.getOperand(2));
1423      } else {
1424        Result = DAG.getSelectCC(Tmp1,
1425                                 DAG.getConstant(0, Tmp1.getValueType()),
1426                                 Tmp3, Tmp4, ISD::SETNE);
1427      }
1428    }
1429    break;
1430  case ISD::SETCC:
1431    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1432    case Legal:
1433      Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
1434      Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
1435      break;
1436    case Promote:
1437      Tmp1 = PromoteOp(Node->getOperand(0));   // LHS
1438      Tmp2 = PromoteOp(Node->getOperand(1));   // RHS
1439
1440      // If this is an FP compare, the operands have already been extended.
1441      if (MVT::isInteger(Node->getOperand(0).getValueType())) {
1442        MVT::ValueType VT = Node->getOperand(0).getValueType();
1443        MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
1444
1445        // Otherwise, we have to insert explicit sign or zero extends.  Note
1446        // that we could insert sign extends for ALL conditions, but zero extend
1447        // is cheaper on many machines (an AND instead of two shifts), so prefer
1448        // it.
1449        switch (cast<CondCodeSDNode>(Node->getOperand(2))->get()) {
1450        default: assert(0 && "Unknown integer comparison!");
1451        case ISD::SETEQ:
1452        case ISD::SETNE:
1453        case ISD::SETUGE:
1454        case ISD::SETUGT:
1455        case ISD::SETULE:
1456        case ISD::SETULT:
1457          // ALL of these operations will work if we either sign or zero extend
1458          // the operands (including the unsigned comparisons!).  Zero extend is
1459          // usually a simpler/cheaper operation, so prefer it.
1460          Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
1461          Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
1462          break;
1463        case ISD::SETGE:
1464        case ISD::SETGT:
1465        case ISD::SETLT:
1466        case ISD::SETLE:
1467          Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
1468                             DAG.getValueType(VT));
1469          Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
1470                             DAG.getValueType(VT));
1471          break;
1472        }
1473      }
1474      break;
1475    case Expand:
1476      SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
1477      ExpandOp(Node->getOperand(0), LHSLo, LHSHi);
1478      ExpandOp(Node->getOperand(1), RHSLo, RHSHi);
1479      switch (cast<CondCodeSDNode>(Node->getOperand(2))->get()) {
1480      case ISD::SETEQ:
1481      case ISD::SETNE:
1482        if (RHSLo == RHSHi)
1483          if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo))
1484            if (RHSCST->isAllOnesValue()) {
1485              // Comparison to -1.
1486              Tmp1 = DAG.getNode(ISD::AND, LHSLo.getValueType(), LHSLo, LHSHi);
1487              Tmp2 = RHSLo;
1488              break;
1489            }
1490
1491        Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
1492        Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
1493        Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
1494        Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
1495        break;
1496      default:
1497        // If this is a comparison of the sign bit, just look at the top part.
1498        // X > -1,  x < 0
1499        if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Node->getOperand(1)))
1500          if ((cast<CondCodeSDNode>(Node->getOperand(2))->get() == ISD::SETLT &&
1501               CST->getValue() == 0) ||              // X < 0
1502              (cast<CondCodeSDNode>(Node->getOperand(2))->get() == ISD::SETGT &&
1503               (CST->isAllOnesValue()))) {            // X > -1
1504            Tmp1 = LHSHi;
1505            Tmp2 = RHSHi;
1506            break;
1507          }
1508
1509        // FIXME: This generated code sucks.
1510        ISD::CondCode LowCC;
1511        switch (cast<CondCodeSDNode>(Node->getOperand(2))->get()) {
1512        default: assert(0 && "Unknown integer setcc!");
1513        case ISD::SETLT:
1514        case ISD::SETULT: LowCC = ISD::SETULT; break;
1515        case ISD::SETGT:
1516        case ISD::SETUGT: LowCC = ISD::SETUGT; break;
1517        case ISD::SETLE:
1518        case ISD::SETULE: LowCC = ISD::SETULE; break;
1519        case ISD::SETGE:
1520        case ISD::SETUGE: LowCC = ISD::SETUGE; break;
1521        }
1522
1523        // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
1524        // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
1525        // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
1526
1527        // NOTE: on targets without efficient SELECT of bools, we can always use
1528        // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
1529        Tmp1 = DAG.getSetCC(Node->getValueType(0), LHSLo, RHSLo, LowCC);
1530        Tmp2 = DAG.getNode(ISD::SETCC, Node->getValueType(0), LHSHi, RHSHi,
1531                           Node->getOperand(2));
1532        Result = DAG.getSetCC(Node->getValueType(0), LHSHi, RHSHi, ISD::SETEQ);
1533        Result = LegalizeOp(DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
1534                                        Result, Tmp1, Tmp2));
1535        return Result;
1536      }
1537    }
1538
1539    switch(TLI.getOperationAction(ISD::SETCC, Node->getOperand(0).getValueType())) {
1540    default:
1541      assert(0 && "Cannot handle this action for SETCC yet!");
1542      break;
1543    case TargetLowering::Promote: {
1544      // First step, figure out the appropriate operation to use.
1545      // Allow SETCC to not be supported for all legal data types
1546      // Mostly this targets FP
1547      MVT::ValueType NewInTy = Node->getOperand(0).getValueType();
1548      MVT::ValueType OldVT = NewInTy;
1549
1550      // Scan for the appropriate larger type to use.
1551      while (1) {
1552        NewInTy = (MVT::ValueType)(NewInTy+1);
1553
1554        assert(MVT::isInteger(NewInTy) == MVT::isInteger(OldVT) &&
1555               "Fell off of the edge of the integer world");
1556        assert(MVT::isFloatingPoint(NewInTy) == MVT::isFloatingPoint(OldVT) &&
1557               "Fell off of the edge of the floating point world");
1558
1559        // If the target supports SETCC of this type, use it.
1560        if (TLI.getOperationAction(ISD::SETCC, NewInTy) == TargetLowering::Legal)
1561          break;
1562      }
1563      if (MVT::isInteger(NewInTy))
1564        assert(0 && "Cannot promote Legal Integer SETCC yet");
1565      else {
1566        Tmp1 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp1);
1567        Tmp2 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp2);
1568      }
1569
1570      Result = DAG.getNode(ISD::SETCC, Node->getValueType(0), Tmp1, Tmp2,
1571                           Node->getOperand(2));
1572      break;
1573    }
1574    case TargetLowering::Legal:
1575      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
1576        Result = DAG.getNode(ISD::SETCC, Node->getValueType(0), Tmp1, Tmp2,
1577                             Node->getOperand(2));
1578      break;
1579    case TargetLowering::Expand:
1580      // Expand a setcc node into a select_cc of the same condition, lhs, and
1581      // rhs that selects between const 1 (true) and const 0 (false).
1582      MVT::ValueType VT = Node->getValueType(0);
1583      Result = DAG.getNode(ISD::SELECT_CC, VT, Tmp1, Tmp2,
1584                           DAG.getConstant(1, VT), DAG.getConstant(0, VT),
1585                           Node->getOperand(2));
1586      Result = LegalizeOp(Result);
1587      break;
1588    }
1589    break;
1590
1591  case ISD::MEMSET:
1592  case ISD::MEMCPY:
1593  case ISD::MEMMOVE: {
1594    Tmp1 = LegalizeOp(Node->getOperand(0));      // Chain
1595    Tmp2 = LegalizeOp(Node->getOperand(1));      // Pointer
1596
1597    if (Node->getOpcode() == ISD::MEMSET) {      // memset = ubyte
1598      switch (getTypeAction(Node->getOperand(2).getValueType())) {
1599      case Expand: assert(0 && "Cannot expand a byte!");
1600      case Legal:
1601        Tmp3 = LegalizeOp(Node->getOperand(2));
1602        break;
1603      case Promote:
1604        Tmp3 = PromoteOp(Node->getOperand(2));
1605        break;
1606      }
1607    } else {
1608      Tmp3 = LegalizeOp(Node->getOperand(2));    // memcpy/move = pointer,
1609    }
1610
1611    SDOperand Tmp4;
1612    switch (getTypeAction(Node->getOperand(3).getValueType())) {
1613    case Expand: {
1614      // Length is too big, just take the lo-part of the length.
1615      SDOperand HiPart;
1616      ExpandOp(Node->getOperand(3), HiPart, Tmp4);
1617      break;
1618    }
1619    case Legal:
1620      Tmp4 = LegalizeOp(Node->getOperand(3));
1621      break;
1622    case Promote:
1623      Tmp4 = PromoteOp(Node->getOperand(3));
1624      break;
1625    }
1626
1627    SDOperand Tmp5;
1628    switch (getTypeAction(Node->getOperand(4).getValueType())) {  // uint
1629    case Expand: assert(0 && "Cannot expand this yet!");
1630    case Legal:
1631      Tmp5 = LegalizeOp(Node->getOperand(4));
1632      break;
1633    case Promote:
1634      Tmp5 = PromoteOp(Node->getOperand(4));
1635      break;
1636    }
1637
1638    switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
1639    default: assert(0 && "This action not implemented for this operation!");
1640    case TargetLowering::Custom: {
1641      SDOperand Tmp =
1642        TLI.LowerOperation(DAG.getNode(Node->getOpcode(), MVT::Other, Tmp1,
1643                                       Tmp2, Tmp3, Tmp4, Tmp5), DAG);
1644      if (Tmp.Val) {
1645        Result = LegalizeOp(Tmp);
1646        break;
1647      }
1648      // FALLTHROUGH if the target thinks it is legal.
1649    }
1650    case TargetLowering::Legal:
1651      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1652          Tmp3 != Node->getOperand(2) || Tmp4 != Node->getOperand(3) ||
1653          Tmp5 != Node->getOperand(4)) {
1654        std::vector<SDOperand> Ops;
1655        Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
1656        Ops.push_back(Tmp4); Ops.push_back(Tmp5);
1657        Result = DAG.getNode(Node->getOpcode(), MVT::Other, Ops);
1658      }
1659      break;
1660    case TargetLowering::Expand: {
1661      // Otherwise, the target does not support this operation.  Lower the
1662      // operation to an explicit libcall as appropriate.
1663      MVT::ValueType IntPtr = TLI.getPointerTy();
1664      const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
1665      std::vector<std::pair<SDOperand, const Type*> > Args;
1666
1667      const char *FnName = 0;
1668      if (Node->getOpcode() == ISD::MEMSET) {
1669        Args.push_back(std::make_pair(Tmp2, IntPtrTy));
1670        // Extend the ubyte argument to be an int value for the call.
1671        Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Tmp3);
1672        Args.push_back(std::make_pair(Tmp3, Type::IntTy));
1673        Args.push_back(std::make_pair(Tmp4, IntPtrTy));
1674
1675        FnName = "memset";
1676      } else if (Node->getOpcode() == ISD::MEMCPY ||
1677                 Node->getOpcode() == ISD::MEMMOVE) {
1678        Args.push_back(std::make_pair(Tmp2, IntPtrTy));
1679        Args.push_back(std::make_pair(Tmp3, IntPtrTy));
1680        Args.push_back(std::make_pair(Tmp4, IntPtrTy));
1681        FnName = Node->getOpcode() == ISD::MEMMOVE ? "memmove" : "memcpy";
1682      } else {
1683        assert(0 && "Unknown op!");
1684      }
1685
1686      std::pair<SDOperand,SDOperand> CallResult =
1687        TLI.LowerCallTo(Tmp1, Type::VoidTy, false, CallingConv::C, false,
1688                        DAG.getExternalSymbol(FnName, IntPtr), Args, DAG);
1689      Result = CallResult.second;
1690      NeedsAnotherIteration = true;
1691      break;
1692    }
1693    }
1694    break;
1695  }
1696
1697  case ISD::READPORT:
1698    Tmp1 = LegalizeOp(Node->getOperand(0));
1699    Tmp2 = LegalizeOp(Node->getOperand(1));
1700
1701    if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1)) {
1702      std::vector<MVT::ValueType> VTs(Node->value_begin(), Node->value_end());
1703      std::vector<SDOperand> Ops;
1704      Ops.push_back(Tmp1);
1705      Ops.push_back(Tmp2);
1706      Result = DAG.getNode(ISD::READPORT, VTs, Ops);
1707    } else
1708      Result = SDOperand(Node, 0);
1709    // Since these produce two values, make sure to remember that we legalized
1710    // both of them.
1711    AddLegalizedOperand(SDOperand(Node, 0), Result);
1712    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1713    return Result.getValue(Op.ResNo);
1714  case ISD::WRITEPORT:
1715    Tmp1 = LegalizeOp(Node->getOperand(0));
1716    Tmp2 = LegalizeOp(Node->getOperand(1));
1717    Tmp3 = LegalizeOp(Node->getOperand(2));
1718    if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1719        Tmp3 != Node->getOperand(2))
1720      Result = DAG.getNode(Node->getOpcode(), MVT::Other, Tmp1, Tmp2, Tmp3);
1721    break;
1722
1723  case ISD::READIO:
1724    Tmp1 = LegalizeOp(Node->getOperand(0));
1725    Tmp2 = LegalizeOp(Node->getOperand(1));
1726
1727    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1728    case TargetLowering::Custom:
1729    default: assert(0 && "This action not implemented for this operation!");
1730    case TargetLowering::Legal:
1731      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1)) {
1732        std::vector<MVT::ValueType> VTs(Node->value_begin(), Node->value_end());
1733        std::vector<SDOperand> Ops;
1734        Ops.push_back(Tmp1);
1735        Ops.push_back(Tmp2);
1736        Result = DAG.getNode(ISD::READPORT, VTs, Ops);
1737      } else
1738        Result = SDOperand(Node, 0);
1739      break;
1740    case TargetLowering::Expand:
1741      // Replace this with a load from memory.
1742      Result = DAG.getLoad(Node->getValueType(0), Node->getOperand(0),
1743                           Node->getOperand(1), DAG.getSrcValue(NULL));
1744      Result = LegalizeOp(Result);
1745      break;
1746    }
1747
1748    // Since these produce two values, make sure to remember that we legalized
1749    // both of them.
1750    AddLegalizedOperand(SDOperand(Node, 0), Result);
1751    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1752    return Result.getValue(Op.ResNo);
1753
1754  case ISD::WRITEIO:
1755    Tmp1 = LegalizeOp(Node->getOperand(0));
1756    Tmp2 = LegalizeOp(Node->getOperand(1));
1757    Tmp3 = LegalizeOp(Node->getOperand(2));
1758
1759    switch (TLI.getOperationAction(Node->getOpcode(),
1760                                   Node->getOperand(1).getValueType())) {
1761    case TargetLowering::Custom:
1762    default: assert(0 && "This action not implemented for this operation!");
1763    case TargetLowering::Legal:
1764      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1765          Tmp3 != Node->getOperand(2))
1766        Result = DAG.getNode(Node->getOpcode(), MVT::Other, Tmp1, Tmp2, Tmp3);
1767      break;
1768    case TargetLowering::Expand:
1769      // Replace this with a store to memory.
1770      Result = DAG.getNode(ISD::STORE, MVT::Other, Node->getOperand(0),
1771                           Node->getOperand(1), Node->getOperand(2),
1772                           DAG.getSrcValue(NULL));
1773      Result = LegalizeOp(Result);
1774      break;
1775    }
1776    break;
1777
1778  case ISD::ADD_PARTS:
1779  case ISD::SUB_PARTS:
1780  case ISD::SHL_PARTS:
1781  case ISD::SRA_PARTS:
1782  case ISD::SRL_PARTS: {
1783    std::vector<SDOperand> Ops;
1784    bool Changed = false;
1785    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1786      Ops.push_back(LegalizeOp(Node->getOperand(i)));
1787      Changed |= Ops.back() != Node->getOperand(i);
1788    }
1789    if (Changed) {
1790      std::vector<MVT::ValueType> VTs(Node->value_begin(), Node->value_end());
1791      Result = DAG.getNode(Node->getOpcode(), VTs, Ops);
1792    }
1793
1794    // Since these produce multiple values, make sure to remember that we
1795    // legalized all of them.
1796    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
1797      AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
1798    return Result.getValue(Op.ResNo);
1799  }
1800
1801    // Binary operators
1802  case ISD::ADD:
1803  case ISD::SUB:
1804  case ISD::MUL:
1805  case ISD::MULHS:
1806  case ISD::MULHU:
1807  case ISD::UDIV:
1808  case ISD::SDIV:
1809  case ISD::AND:
1810  case ISD::OR:
1811  case ISD::XOR:
1812  case ISD::SHL:
1813  case ISD::SRL:
1814  case ISD::SRA:
1815  case ISD::FADD:
1816  case ISD::FSUB:
1817  case ISD::FMUL:
1818  case ISD::FDIV:
1819    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
1820    switch (getTypeAction(Node->getOperand(1).getValueType())) {
1821    case Expand: assert(0 && "Not possible");
1822    case Legal:
1823      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
1824      break;
1825    case Promote:
1826      Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
1827      break;
1828    }
1829    if (Tmp1 != Node->getOperand(0) ||
1830        Tmp2 != Node->getOperand(1))
1831      Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,Tmp2);
1832    break;
1833
1834  case ISD::BUILD_PAIR: {
1835    MVT::ValueType PairTy = Node->getValueType(0);
1836    // TODO: handle the case where the Lo and Hi operands are not of legal type
1837    Tmp1 = LegalizeOp(Node->getOperand(0));   // Lo
1838    Tmp2 = LegalizeOp(Node->getOperand(1));   // Hi
1839    switch (TLI.getOperationAction(ISD::BUILD_PAIR, PairTy)) {
1840    case TargetLowering::Legal:
1841      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
1842        Result = DAG.getNode(ISD::BUILD_PAIR, PairTy, Tmp1, Tmp2);
1843      break;
1844    case TargetLowering::Promote:
1845    case TargetLowering::Custom:
1846      assert(0 && "Cannot promote/custom this yet!");
1847    case TargetLowering::Expand:
1848      Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, PairTy, Tmp1);
1849      Tmp2 = DAG.getNode(ISD::ANY_EXTEND, PairTy, Tmp2);
1850      Tmp2 = DAG.getNode(ISD::SHL, PairTy, Tmp2,
1851                         DAG.getConstant(MVT::getSizeInBits(PairTy)/2,
1852                                         TLI.getShiftAmountTy()));
1853      Result = LegalizeOp(DAG.getNode(ISD::OR, PairTy, Tmp1, Tmp2));
1854      break;
1855    }
1856    break;
1857  }
1858
1859  case ISD::UREM:
1860  case ISD::SREM:
1861  case ISD::FREM:
1862    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
1863    Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
1864    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1865    case TargetLowering::Legal:
1866      if (Tmp1 != Node->getOperand(0) ||
1867          Tmp2 != Node->getOperand(1))
1868        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
1869                             Tmp2);
1870      break;
1871    case TargetLowering::Promote:
1872    case TargetLowering::Custom:
1873      assert(0 && "Cannot promote/custom handle this yet!");
1874    case TargetLowering::Expand:
1875      if (MVT::isInteger(Node->getValueType(0))) {
1876        MVT::ValueType VT = Node->getValueType(0);
1877        unsigned Opc = (Node->getOpcode() == ISD::UREM) ? ISD::UDIV : ISD::SDIV;
1878        Result = DAG.getNode(Opc, VT, Tmp1, Tmp2);
1879        Result = DAG.getNode(ISD::MUL, VT, Result, Tmp2);
1880        Result = DAG.getNode(ISD::SUB, VT, Tmp1, Result);
1881      } else {
1882        // Floating point mod -> fmod libcall.
1883        const char *FnName = Node->getValueType(0) == MVT::f32 ? "fmodf":"fmod";
1884        SDOperand Dummy;
1885        Result = ExpandLibCall(FnName, Node, Dummy);
1886      }
1887      break;
1888    }
1889    break;
1890
1891  case ISD::CTPOP:
1892  case ISD::CTTZ:
1893  case ISD::CTLZ:
1894    Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
1895    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1896    case TargetLowering::Legal:
1897      if (Tmp1 != Node->getOperand(0))
1898        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1899      break;
1900    case TargetLowering::Promote: {
1901      MVT::ValueType OVT = Tmp1.getValueType();
1902      MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
1903
1904      // Zero extend the argument.
1905      Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
1906      // Perform the larger operation, then subtract if needed.
1907      Tmp1 = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1908      switch(Node->getOpcode())
1909      {
1910      case ISD::CTPOP:
1911        Result = Tmp1;
1912        break;
1913      case ISD::CTTZ:
1914        //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
1915        Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
1916                            DAG.getConstant(getSizeInBits(NVT), NVT),
1917                            ISD::SETEQ);
1918        Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
1919                           DAG.getConstant(getSizeInBits(OVT),NVT), Tmp1);
1920        break;
1921      case ISD::CTLZ:
1922        //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
1923        Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
1924                             DAG.getConstant(getSizeInBits(NVT) -
1925                                             getSizeInBits(OVT), NVT));
1926        break;
1927      }
1928      break;
1929    }
1930    case TargetLowering::Custom:
1931      assert(0 && "Cannot custom handle this yet!");
1932    case TargetLowering::Expand:
1933      switch(Node->getOpcode())
1934      {
1935      case ISD::CTPOP: {
1936        static const uint64_t mask[6] = {
1937          0x5555555555555555ULL, 0x3333333333333333ULL,
1938          0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
1939          0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
1940        };
1941        MVT::ValueType VT = Tmp1.getValueType();
1942        MVT::ValueType ShVT = TLI.getShiftAmountTy();
1943        unsigned len = getSizeInBits(VT);
1944        for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
1945          //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
1946          Tmp2 = DAG.getConstant(mask[i], VT);
1947          Tmp3 = DAG.getConstant(1ULL << i, ShVT);
1948          Tmp1 = DAG.getNode(ISD::ADD, VT,
1949                             DAG.getNode(ISD::AND, VT, Tmp1, Tmp2),
1950                             DAG.getNode(ISD::AND, VT,
1951                                         DAG.getNode(ISD::SRL, VT, Tmp1, Tmp3),
1952                                         Tmp2));
1953        }
1954        Result = Tmp1;
1955        break;
1956      }
1957      case ISD::CTLZ: {
1958        /* for now, we do this:
1959           x = x | (x >> 1);
1960           x = x | (x >> 2);
1961           ...
1962           x = x | (x >>16);
1963           x = x | (x >>32); // for 64-bit input
1964           return popcount(~x);
1965
1966           but see also: http://www.hackersdelight.org/HDcode/nlz.cc */
1967        MVT::ValueType VT = Tmp1.getValueType();
1968        MVT::ValueType ShVT = TLI.getShiftAmountTy();
1969        unsigned len = getSizeInBits(VT);
1970        for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
1971          Tmp3 = DAG.getConstant(1ULL << i, ShVT);
1972          Tmp1 = DAG.getNode(ISD::OR, VT, Tmp1,
1973                             DAG.getNode(ISD::SRL, VT, Tmp1, Tmp3));
1974        }
1975        Tmp3 = DAG.getNode(ISD::XOR, VT, Tmp1, DAG.getConstant(~0ULL, VT));
1976        Result = LegalizeOp(DAG.getNode(ISD::CTPOP, VT, Tmp3));
1977        break;
1978      }
1979      case ISD::CTTZ: {
1980        // for now, we use: { return popcount(~x & (x - 1)); }
1981        // unless the target has ctlz but not ctpop, in which case we use:
1982        // { return 32 - nlz(~x & (x-1)); }
1983        // see also http://www.hackersdelight.org/HDcode/ntz.cc
1984        MVT::ValueType VT = Tmp1.getValueType();
1985        Tmp2 = DAG.getConstant(~0ULL, VT);
1986        Tmp3 = DAG.getNode(ISD::AND, VT,
1987                           DAG.getNode(ISD::XOR, VT, Tmp1, Tmp2),
1988                           DAG.getNode(ISD::SUB, VT, Tmp1,
1989                                       DAG.getConstant(1, VT)));
1990        // If ISD::CTLZ is legal and CTPOP isn't, then do that instead
1991        if (!TLI.isOperationLegal(ISD::CTPOP, VT) &&
1992            TLI.isOperationLegal(ISD::CTLZ, VT)) {
1993          Result = LegalizeOp(DAG.getNode(ISD::SUB, VT,
1994                                        DAG.getConstant(getSizeInBits(VT), VT),
1995                                        DAG.getNode(ISD::CTLZ, VT, Tmp3)));
1996        } else {
1997          Result = LegalizeOp(DAG.getNode(ISD::CTPOP, VT, Tmp3));
1998        }
1999        break;
2000      }
2001      default:
2002        assert(0 && "Cannot expand this yet!");
2003        break;
2004      }
2005      break;
2006    }
2007    break;
2008
2009    // Unary operators
2010  case ISD::FABS:
2011  case ISD::FNEG:
2012  case ISD::FSQRT:
2013  case ISD::FSIN:
2014  case ISD::FCOS:
2015    Tmp1 = LegalizeOp(Node->getOperand(0));
2016    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2017    case TargetLowering::Legal:
2018      if (Tmp1 != Node->getOperand(0))
2019        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2020      break;
2021    case TargetLowering::Promote:
2022    case TargetLowering::Custom:
2023      assert(0 && "Cannot promote/custom handle this yet!");
2024    case TargetLowering::Expand:
2025      switch(Node->getOpcode()) {
2026      case ISD::FNEG: {
2027        // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
2028        Tmp2 = DAG.getConstantFP(-0.0, Node->getValueType(0));
2029        Result = LegalizeOp(DAG.getNode(ISD::FSUB, Node->getValueType(0),
2030                                        Tmp2, Tmp1));
2031        break;
2032      }
2033      case ISD::FABS: {
2034        // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
2035        MVT::ValueType VT = Node->getValueType(0);
2036        Tmp2 = DAG.getConstantFP(0.0, VT);
2037        Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1, Tmp2, ISD::SETUGT);
2038        Tmp3 = DAG.getNode(ISD::FNEG, VT, Tmp1);
2039        Result = DAG.getNode(ISD::SELECT, VT, Tmp2, Tmp1, Tmp3);
2040        Result = LegalizeOp(Result);
2041        break;
2042      }
2043      case ISD::FSQRT:
2044      case ISD::FSIN:
2045      case ISD::FCOS: {
2046        MVT::ValueType VT = Node->getValueType(0);
2047        const char *FnName = 0;
2048        switch(Node->getOpcode()) {
2049        case ISD::FSQRT: FnName = VT == MVT::f32 ? "sqrtf" : "sqrt"; break;
2050        case ISD::FSIN:  FnName = VT == MVT::f32 ? "sinf"  : "sin"; break;
2051        case ISD::FCOS:  FnName = VT == MVT::f32 ? "cosf"  : "cos"; break;
2052        default: assert(0 && "Unreachable!");
2053        }
2054        SDOperand Dummy;
2055        Result = ExpandLibCall(FnName, Node, Dummy);
2056        break;
2057      }
2058      default:
2059        assert(0 && "Unreachable!");
2060      }
2061      break;
2062    }
2063    break;
2064
2065    // Conversion operators.  The source and destination have different types.
2066  case ISD::SINT_TO_FP:
2067  case ISD::UINT_TO_FP: {
2068    bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
2069    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2070    case Legal:
2071      switch (TLI.getOperationAction(Node->getOpcode(),
2072                                     Node->getOperand(0).getValueType())) {
2073      default: assert(0 && "Unknown operation action!");
2074      case TargetLowering::Expand:
2075        Result = ExpandLegalINT_TO_FP(isSigned,
2076                                      LegalizeOp(Node->getOperand(0)),
2077                                      Node->getValueType(0));
2078        AddLegalizedOperand(Op, Result);
2079        return Result;
2080      case TargetLowering::Promote:
2081        Result = PromoteLegalINT_TO_FP(LegalizeOp(Node->getOperand(0)),
2082                                       Node->getValueType(0),
2083                                       isSigned);
2084        AddLegalizedOperand(Op, Result);
2085        return Result;
2086      case TargetLowering::Legal:
2087        break;
2088      case TargetLowering::Custom: {
2089        Tmp1 = LegalizeOp(Node->getOperand(0));
2090        SDOperand Tmp =
2091          DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2092        Tmp = TLI.LowerOperation(Tmp, DAG);
2093        if (Tmp.Val) {
2094          AddLegalizedOperand(Op, Tmp);
2095          NeedsAnotherIteration = true;
2096          return Tmp;
2097        } else {
2098          assert(0 && "Target Must Lower this");
2099        }
2100      }
2101      }
2102
2103      Tmp1 = LegalizeOp(Node->getOperand(0));
2104      if (Tmp1 != Node->getOperand(0))
2105        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2106      break;
2107    case Expand:
2108      Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP,
2109                             Node->getValueType(0), Node->getOperand(0));
2110      break;
2111    case Promote:
2112      if (isSigned) {
2113        Result = PromoteOp(Node->getOperand(0));
2114        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2115                 Result, DAG.getValueType(Node->getOperand(0).getValueType()));
2116        Result = DAG.getNode(ISD::SINT_TO_FP, Op.getValueType(), Result);
2117      } else {
2118        Result = PromoteOp(Node->getOperand(0));
2119        Result = DAG.getZeroExtendInReg(Result,
2120                                        Node->getOperand(0).getValueType());
2121        Result = DAG.getNode(ISD::UINT_TO_FP, Op.getValueType(), Result);
2122      }
2123      break;
2124    }
2125    break;
2126  }
2127  case ISD::TRUNCATE:
2128    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2129    case Legal:
2130      Tmp1 = LegalizeOp(Node->getOperand(0));
2131      if (Tmp1 != Node->getOperand(0))
2132        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2133      break;
2134    case Expand:
2135      ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
2136
2137      // Since the result is legal, we should just be able to truncate the low
2138      // part of the source.
2139      Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
2140      break;
2141    case Promote:
2142      Result = PromoteOp(Node->getOperand(0));
2143      Result = DAG.getNode(ISD::TRUNCATE, Op.getValueType(), Result);
2144      break;
2145    }
2146    break;
2147
2148  case ISD::FP_TO_SINT:
2149  case ISD::FP_TO_UINT:
2150    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2151    case Legal:
2152      Tmp1 = LegalizeOp(Node->getOperand(0));
2153
2154      switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))){
2155      default: assert(0 && "Unknown operation action!");
2156      case TargetLowering::Expand:
2157        if (Node->getOpcode() == ISD::FP_TO_UINT) {
2158          SDOperand True, False;
2159          MVT::ValueType VT =  Node->getOperand(0).getValueType();
2160          MVT::ValueType NVT = Node->getValueType(0);
2161          unsigned ShiftAmt = MVT::getSizeInBits(Node->getValueType(0))-1;
2162          Tmp2 = DAG.getConstantFP((double)(1ULL << ShiftAmt), VT);
2163          Tmp3 = DAG.getSetCC(TLI.getSetCCResultTy(),
2164                            Node->getOperand(0), Tmp2, ISD::SETLT);
2165          True = DAG.getNode(ISD::FP_TO_SINT, NVT, Node->getOperand(0));
2166          False = DAG.getNode(ISD::FP_TO_SINT, NVT,
2167                              DAG.getNode(ISD::FSUB, VT, Node->getOperand(0),
2168                                          Tmp2));
2169          False = DAG.getNode(ISD::XOR, NVT, False,
2170                              DAG.getConstant(1ULL << ShiftAmt, NVT));
2171          Result = LegalizeOp(DAG.getNode(ISD::SELECT, NVT, Tmp3, True, False));
2172          return Result;
2173        } else {
2174          assert(0 && "Do not know how to expand FP_TO_SINT yet!");
2175        }
2176        break;
2177      case TargetLowering::Promote:
2178        Result = PromoteLegalFP_TO_INT(Tmp1, Node->getValueType(0),
2179                                       Node->getOpcode() == ISD::FP_TO_SINT);
2180        AddLegalizedOperand(Op, Result);
2181        return Result;
2182      case TargetLowering::Custom: {
2183        SDOperand Tmp =
2184          DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2185        Tmp = TLI.LowerOperation(Tmp, DAG);
2186        if (Tmp.Val) {
2187          AddLegalizedOperand(Op, Tmp);
2188          NeedsAnotherIteration = true;
2189          return Tmp;
2190        } else {
2191          // The target thinks this is legal afterall.
2192          break;
2193        }
2194      }
2195      case TargetLowering::Legal:
2196        break;
2197      }
2198
2199      if (Tmp1 != Node->getOperand(0))
2200        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2201      break;
2202    case Expand:
2203      assert(0 && "Shouldn't need to expand other operators here!");
2204    case Promote:
2205      Result = PromoteOp(Node->getOperand(0));
2206      Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
2207      break;
2208    }
2209    break;
2210
2211  case ISD::ANY_EXTEND:
2212  case ISD::ZERO_EXTEND:
2213  case ISD::SIGN_EXTEND:
2214  case ISD::FP_EXTEND:
2215  case ISD::FP_ROUND:
2216    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2217    case Legal:
2218      Tmp1 = LegalizeOp(Node->getOperand(0));
2219      if (Tmp1 != Node->getOperand(0))
2220        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2221      break;
2222    case Expand:
2223      assert(0 && "Shouldn't need to expand other operators here!");
2224
2225    case Promote:
2226      switch (Node->getOpcode()) {
2227      case ISD::ANY_EXTEND:
2228        Result = PromoteOp(Node->getOperand(0));
2229        Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
2230        break;
2231      case ISD::ZERO_EXTEND:
2232        Result = PromoteOp(Node->getOperand(0));
2233        Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
2234        Result = DAG.getZeroExtendInReg(Result,
2235                                        Node->getOperand(0).getValueType());
2236        break;
2237      case ISD::SIGN_EXTEND:
2238        Result = PromoteOp(Node->getOperand(0));
2239        Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
2240        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2241                             Result,
2242                          DAG.getValueType(Node->getOperand(0).getValueType()));
2243        break;
2244      case ISD::FP_EXTEND:
2245        Result = PromoteOp(Node->getOperand(0));
2246        if (Result.getValueType() != Op.getValueType())
2247          // Dynamically dead while we have only 2 FP types.
2248          Result = DAG.getNode(ISD::FP_EXTEND, Op.getValueType(), Result);
2249        break;
2250      case ISD::FP_ROUND:
2251        Result = PromoteOp(Node->getOperand(0));
2252        Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
2253        break;
2254      }
2255    }
2256    break;
2257  case ISD::FP_ROUND_INREG:
2258  case ISD::SIGN_EXTEND_INREG: {
2259    Tmp1 = LegalizeOp(Node->getOperand(0));
2260    MVT::ValueType ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2261
2262    // If this operation is not supported, convert it to a shl/shr or load/store
2263    // pair.
2264    switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
2265    default: assert(0 && "This action not supported for this op yet!");
2266    case TargetLowering::Legal:
2267      if (Tmp1 != Node->getOperand(0))
2268        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
2269                             DAG.getValueType(ExtraVT));
2270      break;
2271    case TargetLowering::Expand:
2272      // If this is an integer extend and shifts are supported, do that.
2273      if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
2274        // NOTE: we could fall back on load/store here too for targets without
2275        // SAR.  However, it is doubtful that any exist.
2276        unsigned BitsDiff = MVT::getSizeInBits(Node->getValueType(0)) -
2277                            MVT::getSizeInBits(ExtraVT);
2278        SDOperand ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
2279        Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
2280                             Node->getOperand(0), ShiftCst);
2281        Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
2282                             Result, ShiftCst);
2283      } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
2284        // The only way we can lower this is to turn it into a STORETRUNC,
2285        // EXTLOAD pair, targetting a temporary location (a stack slot).
2286
2287        // NOTE: there is a choice here between constantly creating new stack
2288        // slots and always reusing the same one.  We currently always create
2289        // new ones, as reuse may inhibit scheduling.
2290        const Type *Ty = MVT::getTypeForValueType(ExtraVT);
2291        unsigned TySize = (unsigned)TLI.getTargetData().getTypeSize(Ty);
2292        unsigned Align  = TLI.getTargetData().getTypeAlignment(Ty);
2293        MachineFunction &MF = DAG.getMachineFunction();
2294        int SSFI =
2295          MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
2296        SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
2297        Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, DAG.getEntryNode(),
2298                             Node->getOperand(0), StackSlot,
2299                             DAG.getSrcValue(NULL), DAG.getValueType(ExtraVT));
2300        Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
2301                                Result, StackSlot, DAG.getSrcValue(NULL),
2302                                ExtraVT);
2303      } else {
2304        assert(0 && "Unknown op");
2305      }
2306      Result = LegalizeOp(Result);
2307      break;
2308    }
2309    break;
2310  }
2311  }
2312
2313  // Note that LegalizeOp may be reentered even from single-use nodes, which
2314  // means that we always must cache transformed nodes.
2315  AddLegalizedOperand(Op, Result);
2316  return Result;
2317}
2318
2319/// PromoteOp - Given an operation that produces a value in an invalid type,
2320/// promote it to compute the value into a larger type.  The produced value will
2321/// have the correct bits for the low portion of the register, but no guarantee
2322/// is made about the top bits: it may be zero, sign-extended, or garbage.
2323SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
2324  MVT::ValueType VT = Op.getValueType();
2325  MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
2326  assert(getTypeAction(VT) == Promote &&
2327         "Caller should expand or legalize operands that are not promotable!");
2328  assert(NVT > VT && MVT::isInteger(NVT) == MVT::isInteger(VT) &&
2329         "Cannot promote to smaller type!");
2330
2331  SDOperand Tmp1, Tmp2, Tmp3;
2332
2333  SDOperand Result;
2334  SDNode *Node = Op.Val;
2335
2336  std::map<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
2337  if (I != PromotedNodes.end()) return I->second;
2338
2339  // Promotion needs an optimization step to clean up after it, and is not
2340  // careful to avoid operations the target does not support.  Make sure that
2341  // all generated operations are legalized in the next iteration.
2342  NeedsAnotherIteration = true;
2343
2344  switch (Node->getOpcode()) {
2345  case ISD::CopyFromReg:
2346    assert(0 && "CopyFromReg must be legal!");
2347  default:
2348    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
2349    assert(0 && "Do not know how to promote this operator!");
2350    abort();
2351  case ISD::UNDEF:
2352    Result = DAG.getNode(ISD::UNDEF, NVT);
2353    break;
2354  case ISD::Constant:
2355    if (VT != MVT::i1)
2356      Result = DAG.getNode(ISD::SIGN_EXTEND, NVT, Op);
2357    else
2358      Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
2359    assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
2360    break;
2361  case ISD::ConstantFP:
2362    Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
2363    assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
2364    break;
2365
2366  case ISD::SETCC:
2367    assert(isTypeLegal(TLI.getSetCCResultTy()) && "SetCC type is not legal??");
2368    Result = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),Node->getOperand(0),
2369                         Node->getOperand(1), Node->getOperand(2));
2370    Result = LegalizeOp(Result);
2371    break;
2372
2373  case ISD::TRUNCATE:
2374    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2375    case Legal:
2376      Result = LegalizeOp(Node->getOperand(0));
2377      assert(Result.getValueType() >= NVT &&
2378             "This truncation doesn't make sense!");
2379      if (Result.getValueType() > NVT)    // Truncate to NVT instead of VT
2380        Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
2381      break;
2382    case Promote:
2383      // The truncation is not required, because we don't guarantee anything
2384      // about high bits anyway.
2385      Result = PromoteOp(Node->getOperand(0));
2386      break;
2387    case Expand:
2388      ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
2389      // Truncate the low part of the expanded value to the result type
2390      Result = DAG.getNode(ISD::TRUNCATE, NVT, Tmp1);
2391    }
2392    break;
2393  case ISD::SIGN_EXTEND:
2394  case ISD::ZERO_EXTEND:
2395  case ISD::ANY_EXTEND:
2396    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2397    case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
2398    case Legal:
2399      // Input is legal?  Just do extend all the way to the larger type.
2400      Result = LegalizeOp(Node->getOperand(0));
2401      Result = DAG.getNode(Node->getOpcode(), NVT, Result);
2402      break;
2403    case Promote:
2404      // Promote the reg if it's smaller.
2405      Result = PromoteOp(Node->getOperand(0));
2406      // The high bits are not guaranteed to be anything.  Insert an extend.
2407      if (Node->getOpcode() == ISD::SIGN_EXTEND)
2408        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
2409                         DAG.getValueType(Node->getOperand(0).getValueType()));
2410      else if (Node->getOpcode() == ISD::ZERO_EXTEND)
2411        Result = DAG.getZeroExtendInReg(Result,
2412                                        Node->getOperand(0).getValueType());
2413      break;
2414    }
2415    break;
2416
2417  case ISD::FP_EXTEND:
2418    assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
2419  case ISD::FP_ROUND:
2420    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2421    case Expand: assert(0 && "BUG: Cannot expand FP regs!");
2422    case Promote:  assert(0 && "Unreachable with 2 FP types!");
2423    case Legal:
2424      // Input is legal?  Do an FP_ROUND_INREG.
2425      Result = LegalizeOp(Node->getOperand(0));
2426      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2427                           DAG.getValueType(VT));
2428      break;
2429    }
2430    break;
2431
2432  case ISD::SINT_TO_FP:
2433  case ISD::UINT_TO_FP:
2434    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2435    case Legal:
2436      Result = LegalizeOp(Node->getOperand(0));
2437      // No extra round required here.
2438      Result = DAG.getNode(Node->getOpcode(), NVT, Result);
2439      break;
2440
2441    case Promote:
2442      Result = PromoteOp(Node->getOperand(0));
2443      if (Node->getOpcode() == ISD::SINT_TO_FP)
2444        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2445                             Result,
2446                         DAG.getValueType(Node->getOperand(0).getValueType()));
2447      else
2448        Result = DAG.getZeroExtendInReg(Result,
2449                                        Node->getOperand(0).getValueType());
2450      // No extra round required here.
2451      Result = DAG.getNode(Node->getOpcode(), NVT, Result);
2452      break;
2453    case Expand:
2454      Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, NVT,
2455                             Node->getOperand(0));
2456      // Round if we cannot tolerate excess precision.
2457      if (NoExcessFPPrecision)
2458        Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2459                             DAG.getValueType(VT));
2460      break;
2461    }
2462    break;
2463
2464  case ISD::SIGN_EXTEND_INREG:
2465    Result = PromoteOp(Node->getOperand(0));
2466    Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
2467                         Node->getOperand(1));
2468    break;
2469  case ISD::FP_TO_SINT:
2470  case ISD::FP_TO_UINT:
2471    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2472    case Legal:
2473      Tmp1 = LegalizeOp(Node->getOperand(0));
2474      break;
2475    case Promote:
2476      // The input result is prerounded, so we don't have to do anything
2477      // special.
2478      Tmp1 = PromoteOp(Node->getOperand(0));
2479      break;
2480    case Expand:
2481      assert(0 && "not implemented");
2482    }
2483    // If we're promoting a UINT to a larger size, check to see if the new node
2484    // will be legal.  If it isn't, check to see if FP_TO_SINT is legal, since
2485    // we can use that instead.  This allows us to generate better code for
2486    // FP_TO_UINT for small destination sizes on targets where FP_TO_UINT is not
2487    // legal, such as PowerPC.
2488    if (Node->getOpcode() == ISD::FP_TO_UINT &&
2489        !TLI.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
2490        (TLI.isOperationLegal(ISD::FP_TO_SINT, NVT) ||
2491         TLI.getOperationAction(ISD::FP_TO_SINT, NVT)==TargetLowering::Custom)){
2492      Result = DAG.getNode(ISD::FP_TO_SINT, NVT, Tmp1);
2493    } else {
2494      Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2495    }
2496    break;
2497
2498  case ISD::FABS:
2499  case ISD::FNEG:
2500    Tmp1 = PromoteOp(Node->getOperand(0));
2501    assert(Tmp1.getValueType() == NVT);
2502    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2503    // NOTE: we do not have to do any extra rounding here for
2504    // NoExcessFPPrecision, because we know the input will have the appropriate
2505    // precision, and these operations don't modify precision at all.
2506    break;
2507
2508  case ISD::FSQRT:
2509  case ISD::FSIN:
2510  case ISD::FCOS:
2511    Tmp1 = PromoteOp(Node->getOperand(0));
2512    assert(Tmp1.getValueType() == NVT);
2513    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2514    if(NoExcessFPPrecision)
2515      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2516                           DAG.getValueType(VT));
2517    break;
2518
2519  case ISD::AND:
2520  case ISD::OR:
2521  case ISD::XOR:
2522  case ISD::ADD:
2523  case ISD::SUB:
2524  case ISD::MUL:
2525    // The input may have strange things in the top bits of the registers, but
2526    // these operations don't care.  They may have weird bits going out, but
2527    // that too is okay if they are integer operations.
2528    Tmp1 = PromoteOp(Node->getOperand(0));
2529    Tmp2 = PromoteOp(Node->getOperand(1));
2530    assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
2531    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2532    break;
2533  case ISD::FADD:
2534  case ISD::FSUB:
2535  case ISD::FMUL:
2536    // The input may have strange things in the top bits of the registers, but
2537    // these operations don't care.
2538    Tmp1 = PromoteOp(Node->getOperand(0));
2539    Tmp2 = PromoteOp(Node->getOperand(1));
2540    assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
2541    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2542
2543    // Floating point operations will give excess precision that we may not be
2544    // able to tolerate.  If we DO allow excess precision, just leave it,
2545    // otherwise excise it.
2546    // FIXME: Why would we need to round FP ops more than integer ones?
2547    //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
2548    if (NoExcessFPPrecision)
2549      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2550                           DAG.getValueType(VT));
2551    break;
2552
2553  case ISD::SDIV:
2554  case ISD::SREM:
2555    // These operators require that their input be sign extended.
2556    Tmp1 = PromoteOp(Node->getOperand(0));
2557    Tmp2 = PromoteOp(Node->getOperand(1));
2558    if (MVT::isInteger(NVT)) {
2559      Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
2560                         DAG.getValueType(VT));
2561      Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
2562                         DAG.getValueType(VT));
2563    }
2564    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2565
2566    // Perform FP_ROUND: this is probably overly pessimistic.
2567    if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
2568      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2569                           DAG.getValueType(VT));
2570    break;
2571  case ISD::FDIV:
2572  case ISD::FREM:
2573    // These operators require that their input be fp extended.
2574    Tmp1 = PromoteOp(Node->getOperand(0));
2575    Tmp2 = PromoteOp(Node->getOperand(1));
2576    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2577
2578    // Perform FP_ROUND: this is probably overly pessimistic.
2579    if (NoExcessFPPrecision)
2580      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2581                           DAG.getValueType(VT));
2582    break;
2583
2584  case ISD::UDIV:
2585  case ISD::UREM:
2586    // These operators require that their input be zero extended.
2587    Tmp1 = PromoteOp(Node->getOperand(0));
2588    Tmp2 = PromoteOp(Node->getOperand(1));
2589    assert(MVT::isInteger(NVT) && "Operators don't apply to FP!");
2590    Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
2591    Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
2592    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2593    break;
2594
2595  case ISD::SHL:
2596    Tmp1 = PromoteOp(Node->getOperand(0));
2597    Tmp2 = LegalizeOp(Node->getOperand(1));
2598    Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Tmp2);
2599    break;
2600  case ISD::SRA:
2601    // The input value must be properly sign extended.
2602    Tmp1 = PromoteOp(Node->getOperand(0));
2603    Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
2604                       DAG.getValueType(VT));
2605    Tmp2 = LegalizeOp(Node->getOperand(1));
2606    Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Tmp2);
2607    break;
2608  case ISD::SRL:
2609    // The input value must be properly zero extended.
2610    Tmp1 = PromoteOp(Node->getOperand(0));
2611    Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
2612    Tmp2 = LegalizeOp(Node->getOperand(1));
2613    Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Tmp2);
2614    break;
2615  case ISD::LOAD:
2616    Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
2617    Tmp2 = LegalizeOp(Node->getOperand(1));   // Legalize the pointer.
2618    Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Tmp1, Tmp2,
2619                            Node->getOperand(2), VT);
2620    // Remember that we legalized the chain.
2621    AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
2622    break;
2623  case ISD::SEXTLOAD:
2624  case ISD::ZEXTLOAD:
2625  case ISD::EXTLOAD:
2626    Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
2627    Tmp2 = LegalizeOp(Node->getOperand(1));   // Legalize the pointer.
2628    Result = DAG.getExtLoad(Node->getOpcode(), NVT, Tmp1, Tmp2,
2629                         Node->getOperand(2),
2630                            cast<VTSDNode>(Node->getOperand(3))->getVT());
2631    // Remember that we legalized the chain.
2632    AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
2633    break;
2634  case ISD::SELECT:
2635    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2636    case Expand: assert(0 && "It's impossible to expand bools");
2637    case Legal:
2638      Tmp1 = LegalizeOp(Node->getOperand(0));// Legalize the condition.
2639      break;
2640    case Promote:
2641      Tmp1 = PromoteOp(Node->getOperand(0)); // Promote the condition.
2642      break;
2643    }
2644    Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
2645    Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
2646    Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2, Tmp3);
2647    break;
2648  case ISD::SELECT_CC:
2649    Tmp2 = PromoteOp(Node->getOperand(2));   // True
2650    Tmp3 = PromoteOp(Node->getOperand(3));   // False
2651    Result = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
2652                         Node->getOperand(1), Tmp2, Tmp3,
2653                         Node->getOperand(4));
2654    break;
2655  case ISD::TAILCALL:
2656  case ISD::CALL: {
2657    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2658    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
2659
2660    std::vector<SDOperand> Ops;
2661    for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i)
2662      Ops.push_back(LegalizeOp(Node->getOperand(i)));
2663
2664    assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
2665           "Can only promote single result calls");
2666    std::vector<MVT::ValueType> RetTyVTs;
2667    RetTyVTs.reserve(2);
2668    RetTyVTs.push_back(NVT);
2669    RetTyVTs.push_back(MVT::Other);
2670    SDNode *NC = DAG.getCall(RetTyVTs, Tmp1, Tmp2, Ops,
2671                             Node->getOpcode() == ISD::TAILCALL);
2672    Result = SDOperand(NC, 0);
2673
2674    // Insert the new chain mapping.
2675    AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
2676    break;
2677  }
2678  case ISD::CTPOP:
2679  case ISD::CTTZ:
2680  case ISD::CTLZ:
2681    Tmp1 = Node->getOperand(0);
2682    //Zero extend the argument
2683    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
2684    // Perform the larger operation, then subtract if needed.
2685    Tmp1 = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2686    switch(Node->getOpcode())
2687    {
2688    case ISD::CTPOP:
2689      Result = Tmp1;
2690      break;
2691    case ISD::CTTZ:
2692      //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
2693      Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
2694                          DAG.getConstant(getSizeInBits(NVT), NVT), ISD::SETEQ);
2695      Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
2696                           DAG.getConstant(getSizeInBits(VT),NVT), Tmp1);
2697      break;
2698    case ISD::CTLZ:
2699      //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
2700      Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
2701                           DAG.getConstant(getSizeInBits(NVT) -
2702                                           getSizeInBits(VT), NVT));
2703      break;
2704    }
2705    break;
2706  }
2707
2708  assert(Result.Val && "Didn't set a result!");
2709  AddPromotedOperand(Op, Result);
2710  return Result;
2711}
2712
2713/// ExpandAddSub - Find a clever way to expand this add operation into
2714/// subcomponents.
2715void SelectionDAGLegalize::
2716ExpandByParts(unsigned NodeOp, SDOperand LHS, SDOperand RHS,
2717              SDOperand &Lo, SDOperand &Hi) {
2718  // Expand the subcomponents.
2719  SDOperand LHSL, LHSH, RHSL, RHSH;
2720  ExpandOp(LHS, LHSL, LHSH);
2721  ExpandOp(RHS, RHSL, RHSH);
2722
2723  std::vector<SDOperand> Ops;
2724  Ops.push_back(LHSL);
2725  Ops.push_back(LHSH);
2726  Ops.push_back(RHSL);
2727  Ops.push_back(RHSH);
2728  std::vector<MVT::ValueType> VTs(2, LHSL.getValueType());
2729  Lo = DAG.getNode(NodeOp, VTs, Ops);
2730  Hi = Lo.getValue(1);
2731}
2732
2733void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
2734                                            SDOperand Op, SDOperand Amt,
2735                                            SDOperand &Lo, SDOperand &Hi) {
2736  // Expand the subcomponents.
2737  SDOperand LHSL, LHSH;
2738  ExpandOp(Op, LHSL, LHSH);
2739
2740  std::vector<SDOperand> Ops;
2741  Ops.push_back(LHSL);
2742  Ops.push_back(LHSH);
2743  Ops.push_back(Amt);
2744  std::vector<MVT::ValueType> VTs(2, LHSL.getValueType());
2745  Lo = DAG.getNode(NodeOp, VTs, Ops);
2746  Hi = Lo.getValue(1);
2747}
2748
2749
2750/// ExpandShift - Try to find a clever way to expand this shift operation out to
2751/// smaller elements.  If we can't find a way that is more efficient than a
2752/// libcall on this target, return false.  Otherwise, return true with the
2753/// low-parts expanded into Lo and Hi.
2754bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDOperand Op,SDOperand Amt,
2755                                       SDOperand &Lo, SDOperand &Hi) {
2756  assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
2757         "This is not a shift!");
2758
2759  MVT::ValueType NVT = TLI.getTypeToTransformTo(Op.getValueType());
2760  SDOperand ShAmt = LegalizeOp(Amt);
2761  MVT::ValueType ShTy = ShAmt.getValueType();
2762  unsigned VTBits = MVT::getSizeInBits(Op.getValueType());
2763  unsigned NVTBits = MVT::getSizeInBits(NVT);
2764
2765  // Handle the case when Amt is an immediate.  Other cases are currently broken
2766  // and are disabled.
2767  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Amt.Val)) {
2768    unsigned Cst = CN->getValue();
2769    // Expand the incoming operand to be shifted, so that we have its parts
2770    SDOperand InL, InH;
2771    ExpandOp(Op, InL, InH);
2772    switch(Opc) {
2773    case ISD::SHL:
2774      if (Cst > VTBits) {
2775        Lo = DAG.getConstant(0, NVT);
2776        Hi = DAG.getConstant(0, NVT);
2777      } else if (Cst > NVTBits) {
2778        Lo = DAG.getConstant(0, NVT);
2779        Hi = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst-NVTBits,ShTy));
2780      } else if (Cst == NVTBits) {
2781        Lo = DAG.getConstant(0, NVT);
2782        Hi = InL;
2783      } else {
2784        Lo = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst, ShTy));
2785        Hi = DAG.getNode(ISD::OR, NVT,
2786           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(Cst, ShTy)),
2787           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(NVTBits-Cst, ShTy)));
2788      }
2789      return true;
2790    case ISD::SRL:
2791      if (Cst > VTBits) {
2792        Lo = DAG.getConstant(0, NVT);
2793        Hi = DAG.getConstant(0, NVT);
2794      } else if (Cst > NVTBits) {
2795        Lo = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst-NVTBits,ShTy));
2796        Hi = DAG.getConstant(0, NVT);
2797      } else if (Cst == NVTBits) {
2798        Lo = InH;
2799        Hi = DAG.getConstant(0, NVT);
2800      } else {
2801        Lo = DAG.getNode(ISD::OR, NVT,
2802           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
2803           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
2804        Hi = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst, ShTy));
2805      }
2806      return true;
2807    case ISD::SRA:
2808      if (Cst > VTBits) {
2809        Hi = Lo = DAG.getNode(ISD::SRA, NVT, InH,
2810                              DAG.getConstant(NVTBits-1, ShTy));
2811      } else if (Cst > NVTBits) {
2812        Lo = DAG.getNode(ISD::SRA, NVT, InH,
2813                           DAG.getConstant(Cst-NVTBits, ShTy));
2814        Hi = DAG.getNode(ISD::SRA, NVT, InH,
2815                              DAG.getConstant(NVTBits-1, ShTy));
2816      } else if (Cst == NVTBits) {
2817        Lo = InH;
2818        Hi = DAG.getNode(ISD::SRA, NVT, InH,
2819                              DAG.getConstant(NVTBits-1, ShTy));
2820      } else {
2821        Lo = DAG.getNode(ISD::OR, NVT,
2822           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
2823           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
2824        Hi = DAG.getNode(ISD::SRA, NVT, InH, DAG.getConstant(Cst, ShTy));
2825      }
2826      return true;
2827    }
2828  }
2829  // FIXME: The following code for expanding shifts using ISD::SELECT is buggy,
2830  // so disable it for now.  Currently targets are handling this via SHL_PARTS
2831  // and friends.
2832  return false;
2833
2834  // If we have an efficient select operation (or if the selects will all fold
2835  // away), lower to some complex code, otherwise just emit the libcall.
2836  if (!TLI.isOperationLegal(ISD::SELECT, NVT) && !isa<ConstantSDNode>(Amt))
2837    return false;
2838
2839  SDOperand InL, InH;
2840  ExpandOp(Op, InL, InH);
2841  SDOperand NAmt = DAG.getNode(ISD::SUB, ShTy,           // NAmt = 32-ShAmt
2842                               DAG.getConstant(NVTBits, ShTy), ShAmt);
2843
2844  // Compare the unmasked shift amount against 32.
2845  SDOperand Cond = DAG.getSetCC(TLI.getSetCCResultTy(), ShAmt,
2846                                DAG.getConstant(NVTBits, ShTy), ISD::SETGE);
2847
2848  if (TLI.getShiftAmountFlavor() != TargetLowering::Mask) {
2849    ShAmt = DAG.getNode(ISD::AND, ShTy, ShAmt,             // ShAmt &= 31
2850                        DAG.getConstant(NVTBits-1, ShTy));
2851    NAmt  = DAG.getNode(ISD::AND, ShTy, NAmt,              // NAmt &= 31
2852                        DAG.getConstant(NVTBits-1, ShTy));
2853  }
2854
2855  if (Opc == ISD::SHL) {
2856    SDOperand T1 = DAG.getNode(ISD::OR, NVT,// T1 = (Hi << Amt) | (Lo >> NAmt)
2857                               DAG.getNode(ISD::SHL, NVT, InH, ShAmt),
2858                               DAG.getNode(ISD::SRL, NVT, InL, NAmt));
2859    SDOperand T2 = DAG.getNode(ISD::SHL, NVT, InL, ShAmt); // T2 = Lo << Amt&31
2860
2861    Hi = DAG.getNode(ISD::SELECT, NVT, Cond, T2, T1);
2862    Lo = DAG.getNode(ISD::SELECT, NVT, Cond, DAG.getConstant(0, NVT), T2);
2863  } else {
2864    SDOperand HiLoPart = DAG.getNode(ISD::SELECT, NVT,
2865                                     DAG.getSetCC(TLI.getSetCCResultTy(), NAmt,
2866                                                  DAG.getConstant(32, ShTy),
2867                                                  ISD::SETEQ),
2868                                     DAG.getConstant(0, NVT),
2869                                     DAG.getNode(ISD::SHL, NVT, InH, NAmt));
2870    SDOperand T1 = DAG.getNode(ISD::OR, NVT,// T1 = (Hi << NAmt) | (Lo >> Amt)
2871                               HiLoPart,
2872                               DAG.getNode(ISD::SRL, NVT, InL, ShAmt));
2873    SDOperand T2 = DAG.getNode(Opc, NVT, InH, ShAmt);  // T2 = InH >> ShAmt&31
2874
2875    SDOperand HiPart;
2876    if (Opc == ISD::SRA)
2877      HiPart = DAG.getNode(ISD::SRA, NVT, InH,
2878                           DAG.getConstant(NVTBits-1, ShTy));
2879    else
2880      HiPart = DAG.getConstant(0, NVT);
2881    Lo = DAG.getNode(ISD::SELECT, NVT, Cond, T2, T1);
2882    Hi = DAG.getNode(ISD::SELECT, NVT, Cond, HiPart, T2);
2883  }
2884  return true;
2885}
2886
2887/// FindLatestCallSeqStart - Scan up the dag to find the latest (highest
2888/// NodeDepth) node that is an CallSeqStart operation and occurs later than
2889/// Found.
2890static void FindLatestCallSeqStart(SDNode *Node, SDNode *&Found) {
2891  if (Node->getNodeDepth() <= Found->getNodeDepth()) return;
2892
2893  // If we found an CALLSEQ_START, we already know this node occurs later
2894  // than the Found node. Just remember this node and return.
2895  if (Node->getOpcode() == ISD::CALLSEQ_START) {
2896    Found = Node;
2897    return;
2898  }
2899
2900  // Otherwise, scan the operands of Node to see if any of them is a call.
2901  assert(Node->getNumOperands() != 0 &&
2902         "All leaves should have depth equal to the entry node!");
2903  for (unsigned i = 0, e = Node->getNumOperands()-1; i != e; ++i)
2904    FindLatestCallSeqStart(Node->getOperand(i).Val, Found);
2905
2906  // Tail recurse for the last iteration.
2907  FindLatestCallSeqStart(Node->getOperand(Node->getNumOperands()-1).Val,
2908                             Found);
2909}
2910
2911
2912/// FindEarliestCallSeqEnd - Scan down the dag to find the earliest (lowest
2913/// NodeDepth) node that is an CallSeqEnd operation and occurs more recent
2914/// than Found.
2915static void FindEarliestCallSeqEnd(SDNode *Node, SDNode *&Found,
2916                                   std::set<SDNode*> &Visited) {
2917  if ((Found && Node->getNodeDepth() >= Found->getNodeDepth()) ||
2918      !Visited.insert(Node).second) return;
2919
2920  // If we found an CALLSEQ_END, we already know this node occurs earlier
2921  // than the Found node. Just remember this node and return.
2922  if (Node->getOpcode() == ISD::CALLSEQ_END) {
2923    Found = Node;
2924    return;
2925  }
2926
2927  // Otherwise, scan the operands of Node to see if any of them is a call.
2928  SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
2929  if (UI == E) return;
2930  for (--E; UI != E; ++UI)
2931    FindEarliestCallSeqEnd(*UI, Found, Visited);
2932
2933  // Tail recurse for the last iteration.
2934  FindEarliestCallSeqEnd(*UI, Found, Visited);
2935}
2936
2937/// FindCallSeqEnd - Given a chained node that is part of a call sequence,
2938/// find the CALLSEQ_END node that terminates the call sequence.
2939static SDNode *FindCallSeqEnd(SDNode *Node) {
2940  if (Node->getOpcode() == ISD::CALLSEQ_END)
2941    return Node;
2942  if (Node->use_empty())
2943    return 0;   // No CallSeqEnd
2944
2945  SDOperand TheChain(Node, Node->getNumValues()-1);
2946  if (TheChain.getValueType() != MVT::Other)
2947    TheChain = SDOperand(Node, 0);
2948  if (TheChain.getValueType() != MVT::Other)
2949    return 0;
2950
2951  for (SDNode::use_iterator UI = Node->use_begin(),
2952         E = Node->use_end(); UI != E; ++UI) {
2953
2954    // Make sure to only follow users of our token chain.
2955    SDNode *User = *UI;
2956    for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
2957      if (User->getOperand(i) == TheChain)
2958        if (SDNode *Result = FindCallSeqEnd(User))
2959          return Result;
2960  }
2961  return 0;
2962}
2963
2964/// FindCallSeqStart - Given a chained node that is part of a call sequence,
2965/// find the CALLSEQ_START node that initiates the call sequence.
2966static SDNode *FindCallSeqStart(SDNode *Node) {
2967  assert(Node && "Didn't find callseq_start for a call??");
2968  if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
2969
2970  assert(Node->getOperand(0).getValueType() == MVT::Other &&
2971         "Node doesn't have a token chain argument!");
2972  return FindCallSeqStart(Node->getOperand(0).Val);
2973}
2974
2975
2976/// FindInputOutputChains - If we are replacing an operation with a call we need
2977/// to find the call that occurs before and the call that occurs after it to
2978/// properly serialize the calls in the block.  The returned operand is the
2979/// input chain value for the new call (e.g. the entry node or the previous
2980/// call), and OutChain is set to be the chain node to update to point to the
2981/// end of the call chain.
2982static SDOperand FindInputOutputChains(SDNode *OpNode, SDNode *&OutChain,
2983                                       SDOperand Entry) {
2984  SDNode *LatestCallSeqStart = Entry.Val;
2985  SDNode *LatestCallSeqEnd = 0;
2986  FindLatestCallSeqStart(OpNode, LatestCallSeqStart);
2987  //std::cerr<<"Found node: "; LatestCallSeqStart->dump(); std::cerr <<"\n";
2988
2989  // It is possible that no ISD::CALLSEQ_START was found because there is no
2990  // previous call in the function.  LatestCallStackDown may in that case be
2991  // the entry node itself.  Do not attempt to find a matching CALLSEQ_END
2992  // unless LatestCallStackDown is an CALLSEQ_START.
2993  if (LatestCallSeqStart->getOpcode() == ISD::CALLSEQ_START) {
2994    LatestCallSeqEnd = FindCallSeqEnd(LatestCallSeqStart);
2995    //std::cerr<<"Found end node: "; LatestCallSeqEnd->dump(); std::cerr <<"\n";
2996  } else {
2997    LatestCallSeqEnd = Entry.Val;
2998  }
2999  assert(LatestCallSeqEnd && "NULL return from FindCallSeqEnd");
3000
3001  // Finally, find the first call that this must come before, first we find the
3002  // CallSeqEnd that ends the call.
3003  OutChain = 0;
3004  std::set<SDNode*> Visited;
3005  FindEarliestCallSeqEnd(OpNode, OutChain, Visited);
3006
3007  // If we found one, translate from the adj up to the callseq_start.
3008  if (OutChain)
3009    OutChain = FindCallSeqStart(OutChain);
3010
3011  return SDOperand(LatestCallSeqEnd, 0);
3012}
3013
3014/// SpliceCallInto - Given the result chain of a libcall (CallResult), and a
3015void SelectionDAGLegalize::SpliceCallInto(const SDOperand &CallResult,
3016                                          SDNode *OutChain) {
3017  // Nothing to splice it into?
3018  if (OutChain == 0) return;
3019
3020  assert(OutChain->getOperand(0).getValueType() == MVT::Other);
3021  //OutChain->dump();
3022
3023  // Form a token factor node merging the old inval and the new inval.
3024  SDOperand InToken = DAG.getNode(ISD::TokenFactor, MVT::Other, CallResult,
3025                                  OutChain->getOperand(0));
3026  // Change the node to refer to the new token.
3027  OutChain->setAdjCallChain(InToken);
3028}
3029
3030
3031// ExpandLibCall - Expand a node into a call to a libcall.  If the result value
3032// does not fit into a register, return the lo part and set the hi part to the
3033// by-reg argument.  If it does fit into a single register, return the result
3034// and leave the Hi part unset.
3035SDOperand SelectionDAGLegalize::ExpandLibCall(const char *Name, SDNode *Node,
3036                                              SDOperand &Hi) {
3037  SDNode *OutChain;
3038  SDOperand InChain = FindInputOutputChains(Node, OutChain,
3039                                            DAG.getEntryNode());
3040  if (InChain.Val == 0)
3041    InChain = DAG.getEntryNode();
3042
3043  TargetLowering::ArgListTy Args;
3044  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
3045    MVT::ValueType ArgVT = Node->getOperand(i).getValueType();
3046    const Type *ArgTy = MVT::getTypeForValueType(ArgVT);
3047    Args.push_back(std::make_pair(Node->getOperand(i), ArgTy));
3048  }
3049  SDOperand Callee = DAG.getExternalSymbol(Name, TLI.getPointerTy());
3050
3051  // Splice the libcall in wherever FindInputOutputChains tells us to.
3052  const Type *RetTy = MVT::getTypeForValueType(Node->getValueType(0));
3053  std::pair<SDOperand,SDOperand> CallInfo =
3054    TLI.LowerCallTo(InChain, RetTy, false, CallingConv::C, false,
3055                    Callee, Args, DAG);
3056
3057  SDOperand Result;
3058  switch (getTypeAction(CallInfo.first.getValueType())) {
3059  default: assert(0 && "Unknown thing");
3060  case Legal:
3061    Result = CallInfo.first;
3062    break;
3063  case Promote:
3064    assert(0 && "Cannot promote this yet!");
3065  case Expand:
3066    ExpandOp(CallInfo.first, Result, Hi);
3067    CallInfo.second = LegalizeOp(CallInfo.second);
3068    break;
3069  }
3070
3071  SpliceCallInto(CallInfo.second, OutChain);
3072  NeedsAnotherIteration = true;
3073  return Result;
3074}
3075
3076
3077/// ExpandIntToFP - Expand a [US]INT_TO_FP operation, assuming that the
3078/// destination type is legal.
3079SDOperand SelectionDAGLegalize::
3080ExpandIntToFP(bool isSigned, MVT::ValueType DestTy, SDOperand Source) {
3081  assert(isTypeLegal(DestTy) && "Destination type is not legal!");
3082  assert(getTypeAction(Source.getValueType()) == Expand &&
3083         "This is not an expansion!");
3084  assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
3085
3086  if (!isSigned) {
3087    assert(Source.getValueType() == MVT::i64 &&
3088           "This only works for 64-bit -> FP");
3089    // The 64-bit value loaded will be incorrectly if the 'sign bit' of the
3090    // incoming integer is set.  To handle this, we dynamically test to see if
3091    // it is set, and, if so, add a fudge factor.
3092    SDOperand Lo, Hi;
3093    ExpandOp(Source, Lo, Hi);
3094
3095    // If this is unsigned, and not supported, first perform the conversion to
3096    // signed, then adjust the result if the sign bit is set.
3097    SDOperand SignedConv = ExpandIntToFP(true, DestTy,
3098                   DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), Lo, Hi));
3099
3100    SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Hi,
3101                                     DAG.getConstant(0, Hi.getValueType()),
3102                                     ISD::SETLT);
3103    SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
3104    SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
3105                                      SignSet, Four, Zero);
3106    uint64_t FF = 0x5f800000ULL;
3107    if (TLI.isLittleEndian()) FF <<= 32;
3108    static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
3109
3110    SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
3111    CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
3112    SDOperand FudgeInReg;
3113    if (DestTy == MVT::f32)
3114      FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
3115                               DAG.getSrcValue(NULL));
3116    else {
3117      assert(DestTy == MVT::f64 && "Unexpected conversion");
3118      FudgeInReg = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
3119                                  CPIdx, DAG.getSrcValue(NULL), MVT::f32);
3120    }
3121    return DAG.getNode(ISD::FADD, DestTy, SignedConv, FudgeInReg);
3122  }
3123
3124  // Check to see if the target has a custom way to lower this.  If so, use it.
3125  switch (TLI.getOperationAction(ISD::SINT_TO_FP, Source.getValueType())) {
3126  default: assert(0 && "This action not implemented for this operation!");
3127  case TargetLowering::Legal:
3128  case TargetLowering::Expand:
3129    break;   // This case is handled below.
3130  case TargetLowering::Custom: {
3131    SDOperand NV = TLI.LowerOperation(DAG.getNode(ISD::SINT_TO_FP, DestTy,
3132                                                  Source), DAG);
3133    if (NV.Val)
3134      return LegalizeOp(NV);
3135    break;   // The target decided this was legal after all
3136  }
3137  }
3138
3139  // Expand the source, then glue it back together for the call.  We must expand
3140  // the source in case it is shared (this pass of legalize must traverse it).
3141  SDOperand SrcLo, SrcHi;
3142  ExpandOp(Source, SrcLo, SrcHi);
3143  Source = DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), SrcLo, SrcHi);
3144
3145  SDNode *OutChain = 0;
3146  SDOperand InChain = FindInputOutputChains(Source.Val, OutChain,
3147                                            DAG.getEntryNode());
3148  const char *FnName = 0;
3149  if (DestTy == MVT::f32)
3150    FnName = "__floatdisf";
3151  else {
3152    assert(DestTy == MVT::f64 && "Unknown fp value type!");
3153    FnName = "__floatdidf";
3154  }
3155
3156  SDOperand Callee = DAG.getExternalSymbol(FnName, TLI.getPointerTy());
3157
3158  TargetLowering::ArgListTy Args;
3159  const Type *ArgTy = MVT::getTypeForValueType(Source.getValueType());
3160
3161  Args.push_back(std::make_pair(Source, ArgTy));
3162
3163  // We don't care about token chains for libcalls.  We just use the entry
3164  // node as our input and ignore the output chain.  This allows us to place
3165  // calls wherever we need them to satisfy data dependences.
3166  const Type *RetTy = MVT::getTypeForValueType(DestTy);
3167
3168  std::pair<SDOperand,SDOperand> CallResult =
3169    TLI.LowerCallTo(InChain, RetTy, false, CallingConv::C, true,
3170                    Callee, Args, DAG);
3171
3172  SpliceCallInto(CallResult.second, OutChain);
3173  return CallResult.first;
3174}
3175
3176
3177
3178/// ExpandOp - Expand the specified SDOperand into its two component pieces
3179/// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
3180/// LegalizeNodes map is filled in for any results that are not expanded, the
3181/// ExpandedNodes map is filled in for any results that are expanded, and the
3182/// Lo/Hi values are returned.
3183void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
3184  MVT::ValueType VT = Op.getValueType();
3185  MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
3186  SDNode *Node = Op.Val;
3187  assert(getTypeAction(VT) == Expand && "Not an expanded type!");
3188  assert((MVT::isInteger(VT) || VT == MVT::Vector) &&
3189         "Cannot expand FP values!");
3190  assert(((MVT::isInteger(NVT) && NVT < VT) || VT == MVT::Vector) &&
3191         "Cannot expand to FP value or to larger int value!");
3192
3193  // See if we already expanded it.
3194  std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
3195    = ExpandedNodes.find(Op);
3196  if (I != ExpandedNodes.end()) {
3197    Lo = I->second.first;
3198    Hi = I->second.second;
3199    return;
3200  }
3201
3202  // Expanding to multiple registers needs to perform an optimization step, and
3203  // is not careful to avoid operations the target does not support.  Make sure
3204  // that all generated operations are legalized in the next iteration.
3205  NeedsAnotherIteration = true;
3206
3207  switch (Node->getOpcode()) {
3208   case ISD::CopyFromReg:
3209      assert(0 && "CopyFromReg must be legal!");
3210   default:
3211    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
3212    assert(0 && "Do not know how to expand this operator!");
3213    abort();
3214  case ISD::UNDEF:
3215    Lo = DAG.getNode(ISD::UNDEF, NVT);
3216    Hi = DAG.getNode(ISD::UNDEF, NVT);
3217    break;
3218  case ISD::Constant: {
3219    uint64_t Cst = cast<ConstantSDNode>(Node)->getValue();
3220    Lo = DAG.getConstant(Cst, NVT);
3221    Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
3222    break;
3223  }
3224  case ISD::ConstantVec: {
3225    unsigned NumElements = Node->getNumOperands();
3226    // If we only have two elements left in the constant vector, just break it
3227    // apart into the two scalar constants it contains.  Otherwise, bisect the
3228    // ConstantVec, and return each half as a new ConstantVec.
3229    // FIXME: this is hard coded as big endian, it may have to change to support
3230    // SSE and Alpha MVI
3231    if (NumElements == 2) {
3232      Hi = Node->getOperand(0);
3233      Lo = Node->getOperand(1);
3234    } else {
3235      NumElements /= 2;
3236      std::vector<SDOperand> LoOps, HiOps;
3237      for (unsigned I = 0, E = NumElements; I < E; ++I) {
3238        HiOps.push_back(Node->getOperand(I));
3239        LoOps.push_back(Node->getOperand(I+NumElements));
3240      }
3241      Lo = DAG.getNode(ISD::ConstantVec, MVT::Vector, LoOps);
3242      Hi = DAG.getNode(ISD::ConstantVec, MVT::Vector, HiOps);
3243    }
3244    break;
3245  }
3246
3247  case ISD::BUILD_PAIR:
3248    // Legalize both operands.  FIXME: in the future we should handle the case
3249    // where the two elements are not legal.
3250    assert(isTypeLegal(NVT) && "Cannot expand this multiple times yet!");
3251    Lo = LegalizeOp(Node->getOperand(0));
3252    Hi = LegalizeOp(Node->getOperand(1));
3253    break;
3254
3255  case ISD::SIGN_EXTEND_INREG:
3256    ExpandOp(Node->getOperand(0), Lo, Hi);
3257    // Sign extend the lo-part.
3258    Hi = DAG.getNode(ISD::SRA, NVT, Lo,
3259                     DAG.getConstant(MVT::getSizeInBits(NVT)-1,
3260                                     TLI.getShiftAmountTy()));
3261    // sext_inreg the low part if needed.
3262    Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Lo, Node->getOperand(1));
3263    break;
3264
3265  case ISD::CTPOP:
3266    ExpandOp(Node->getOperand(0), Lo, Hi);
3267    Lo = DAG.getNode(ISD::ADD, NVT,          // ctpop(HL) -> ctpop(H)+ctpop(L)
3268                     DAG.getNode(ISD::CTPOP, NVT, Lo),
3269                     DAG.getNode(ISD::CTPOP, NVT, Hi));
3270    Hi = DAG.getConstant(0, NVT);
3271    break;
3272
3273  case ISD::CTLZ: {
3274    // ctlz (HL) -> ctlz(H) != 32 ? ctlz(H) : (ctlz(L)+32)
3275    ExpandOp(Node->getOperand(0), Lo, Hi);
3276    SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
3277    SDOperand HLZ = DAG.getNode(ISD::CTLZ, NVT, Hi);
3278    SDOperand TopNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), HLZ, BitsC,
3279                                        ISD::SETNE);
3280    SDOperand LowPart = DAG.getNode(ISD::CTLZ, NVT, Lo);
3281    LowPart = DAG.getNode(ISD::ADD, NVT, LowPart, BitsC);
3282
3283    Lo = DAG.getNode(ISD::SELECT, NVT, TopNotZero, HLZ, LowPart);
3284    Hi = DAG.getConstant(0, NVT);
3285    break;
3286  }
3287
3288  case ISD::CTTZ: {
3289    // cttz (HL) -> cttz(L) != 32 ? cttz(L) : (cttz(H)+32)
3290    ExpandOp(Node->getOperand(0), Lo, Hi);
3291    SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
3292    SDOperand LTZ = DAG.getNode(ISD::CTTZ, NVT, Lo);
3293    SDOperand BotNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), LTZ, BitsC,
3294                                        ISD::SETNE);
3295    SDOperand HiPart = DAG.getNode(ISD::CTTZ, NVT, Hi);
3296    HiPart = DAG.getNode(ISD::ADD, NVT, HiPart, BitsC);
3297
3298    Lo = DAG.getNode(ISD::SELECT, NVT, BotNotZero, LTZ, HiPart);
3299    Hi = DAG.getConstant(0, NVT);
3300    break;
3301  }
3302
3303  case ISD::LOAD: {
3304    SDOperand Ch = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
3305    SDOperand Ptr = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
3306    Lo = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
3307
3308    // Increment the pointer to the other half.
3309    unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
3310    Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
3311                      getIntPtrConstant(IncrementSize));
3312    //Is this safe?  declaring that the two parts of the split load
3313    //are from the same instruction?
3314    Hi = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
3315
3316    // Build a factor node to remember that this load is independent of the
3317    // other one.
3318    SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
3319                               Hi.getValue(1));
3320
3321    // Remember that we legalized the chain.
3322    AddLegalizedOperand(Op.getValue(1), TF);
3323    if (!TLI.isLittleEndian())
3324      std::swap(Lo, Hi);
3325    break;
3326  }
3327  case ISD::VLOAD: {
3328    SDOperand Ch = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
3329    SDOperand Ptr = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
3330    unsigned NumElements =cast<ConstantSDNode>(Node->getOperand(2))->getValue();
3331    MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
3332
3333    // If we only have two elements, turn into a pair of scalar loads.
3334    // FIXME: handle case where a vector of two elements is fine, such as
3335    //   2 x double on SSE2.
3336    if (NumElements == 2) {
3337      Lo = DAG.getLoad(EVT, Ch, Ptr, Node->getOperand(4));
3338      // Increment the pointer to the other half.
3339      unsigned IncrementSize = MVT::getSizeInBits(EVT)/8;
3340      Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
3341                        getIntPtrConstant(IncrementSize));
3342      //Is this safe?  declaring that the two parts of the split load
3343      //are from the same instruction?
3344      Hi = DAG.getLoad(EVT, Ch, Ptr, Node->getOperand(4));
3345    } else {
3346      NumElements /= 2; // Split the vector in half
3347      Lo = DAG.getVecLoad(NumElements, EVT, Ch, Ptr, Node->getOperand(4));
3348      unsigned IncrementSize = NumElements * MVT::getSizeInBits(EVT)/8;
3349      Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
3350                        getIntPtrConstant(IncrementSize));
3351      //Is this safe?  declaring that the two parts of the split load
3352      //are from the same instruction?
3353      Hi = DAG.getVecLoad(NumElements, EVT, Ch, Ptr, Node->getOperand(4));
3354    }
3355
3356    // Build a factor node to remember that this load is independent of the
3357    // other one.
3358    SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
3359                               Hi.getValue(1));
3360
3361    // Remember that we legalized the chain.
3362    AddLegalizedOperand(Op.getValue(1), TF);
3363    if (!TLI.isLittleEndian())
3364      std::swap(Lo, Hi);
3365    break;
3366  }
3367  case ISD::VADD:
3368  case ISD::VSUB:
3369  case ISD::VMUL: {
3370    unsigned NumElements =cast<ConstantSDNode>(Node->getOperand(2))->getValue();
3371    MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
3372    SDOperand LL, LH, RL, RH;
3373
3374    ExpandOp(Node->getOperand(0), LL, LH);
3375    ExpandOp(Node->getOperand(1), RL, RH);
3376
3377    // If we only have two elements, turn into a pair of scalar loads.
3378    // FIXME: handle case where a vector of two elements is fine, such as
3379    //   2 x double on SSE2.
3380    if (NumElements == 2) {
3381      unsigned Opc = getScalarizedOpcode(Node->getOpcode(), EVT);
3382      Lo = DAG.getNode(Opc, EVT, LL, RL);
3383      Hi = DAG.getNode(Opc, EVT, LH, RH);
3384    } else {
3385      Lo = DAG.getNode(Node->getOpcode(), MVT::Vector, LL, RL, LL.getOperand(2),
3386                       LL.getOperand(3));
3387      Hi = DAG.getNode(Node->getOpcode(), MVT::Vector, LH, RH, LH.getOperand(2),
3388                       LH.getOperand(3));
3389    }
3390    break;
3391  }
3392  case ISD::TAILCALL:
3393  case ISD::CALL: {
3394    SDOperand Chain  = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
3395    SDOperand Callee = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
3396
3397    bool Changed = false;
3398    std::vector<SDOperand> Ops;
3399    for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i) {
3400      Ops.push_back(LegalizeOp(Node->getOperand(i)));
3401      Changed |= Ops.back() != Node->getOperand(i);
3402    }
3403
3404    assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
3405           "Can only expand a call once so far, not i64 -> i16!");
3406
3407    std::vector<MVT::ValueType> RetTyVTs;
3408    RetTyVTs.reserve(3);
3409    RetTyVTs.push_back(NVT);
3410    RetTyVTs.push_back(NVT);
3411    RetTyVTs.push_back(MVT::Other);
3412    SDNode *NC = DAG.getCall(RetTyVTs, Chain, Callee, Ops,
3413                             Node->getOpcode() == ISD::TAILCALL);
3414    Lo = SDOperand(NC, 0);
3415    Hi = SDOperand(NC, 1);
3416
3417    // Insert the new chain mapping.
3418    AddLegalizedOperand(Op.getValue(1), Hi.getValue(2));
3419    break;
3420  }
3421  case ISD::AND:
3422  case ISD::OR:
3423  case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
3424    SDOperand LL, LH, RL, RH;
3425    ExpandOp(Node->getOperand(0), LL, LH);
3426    ExpandOp(Node->getOperand(1), RL, RH);
3427    Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
3428    Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
3429    break;
3430  }
3431  case ISD::SELECT: {
3432    SDOperand C, LL, LH, RL, RH;
3433
3434    switch (getTypeAction(Node->getOperand(0).getValueType())) {
3435    case Expand: assert(0 && "It's impossible to expand bools");
3436    case Legal:
3437      C = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
3438      break;
3439    case Promote:
3440      C = PromoteOp(Node->getOperand(0));  // Promote the condition.
3441      break;
3442    }
3443    ExpandOp(Node->getOperand(1), LL, LH);
3444    ExpandOp(Node->getOperand(2), RL, RH);
3445    Lo = DAG.getNode(ISD::SELECT, NVT, C, LL, RL);
3446    Hi = DAG.getNode(ISD::SELECT, NVT, C, LH, RH);
3447    break;
3448  }
3449  case ISD::SELECT_CC: {
3450    SDOperand TL, TH, FL, FH;
3451    ExpandOp(Node->getOperand(2), TL, TH);
3452    ExpandOp(Node->getOperand(3), FL, FH);
3453    Lo = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
3454                     Node->getOperand(1), TL, FL, Node->getOperand(4));
3455    Hi = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
3456                     Node->getOperand(1), TH, FH, Node->getOperand(4));
3457    Lo = LegalizeOp(Lo);
3458    Hi = LegalizeOp(Hi);
3459    break;
3460  }
3461  case ISD::SEXTLOAD: {
3462    SDOperand Chain = LegalizeOp(Node->getOperand(0));
3463    SDOperand Ptr   = LegalizeOp(Node->getOperand(1));
3464    MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
3465
3466    if (EVT == NVT)
3467      Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
3468    else
3469      Lo = DAG.getExtLoad(ISD::SEXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
3470                          EVT);
3471
3472    // Remember that we legalized the chain.
3473    AddLegalizedOperand(SDOperand(Node, 1), Lo.getValue(1));
3474
3475    // The high part is obtained by SRA'ing all but one of the bits of the lo
3476    // part.
3477    unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
3478    Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1,
3479                                                       TLI.getShiftAmountTy()));
3480    Lo = LegalizeOp(Lo);
3481    Hi = LegalizeOp(Hi);
3482    break;
3483  }
3484  case ISD::ZEXTLOAD: {
3485    SDOperand Chain = LegalizeOp(Node->getOperand(0));
3486    SDOperand Ptr   = LegalizeOp(Node->getOperand(1));
3487    MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
3488
3489    if (EVT == NVT)
3490      Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
3491    else
3492      Lo = DAG.getExtLoad(ISD::ZEXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
3493                          EVT);
3494
3495    // Remember that we legalized the chain.
3496    AddLegalizedOperand(SDOperand(Node, 1), Lo.getValue(1));
3497
3498    // The high part is just a zero.
3499    Hi = LegalizeOp(DAG.getConstant(0, NVT));
3500    Lo = LegalizeOp(Lo);
3501    break;
3502  }
3503  case ISD::EXTLOAD: {
3504    SDOperand Chain = LegalizeOp(Node->getOperand(0));
3505    SDOperand Ptr   = LegalizeOp(Node->getOperand(1));
3506    MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
3507
3508    if (EVT == NVT)
3509      Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
3510    else
3511      Lo = DAG.getExtLoad(ISD::EXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
3512                          EVT);
3513
3514    // Remember that we legalized the chain.
3515    AddLegalizedOperand(SDOperand(Node, 1), Lo.getValue(1));
3516
3517    // The high part is undefined.
3518    Hi = LegalizeOp(DAG.getNode(ISD::UNDEF, NVT));
3519    Lo = LegalizeOp(Lo);
3520    break;
3521  }
3522  case ISD::ANY_EXTEND: {
3523    SDOperand In;
3524    switch (getTypeAction(Node->getOperand(0).getValueType())) {
3525    case Expand: assert(0 && "expand-expand not implemented yet!");
3526    case Legal: In = LegalizeOp(Node->getOperand(0)); break;
3527    case Promote:
3528      In = PromoteOp(Node->getOperand(0));
3529      break;
3530    }
3531
3532    // The low part is any extension of the input (which degenerates to a copy).
3533    Lo = DAG.getNode(ISD::ANY_EXTEND, NVT, In);
3534    // The high part is undefined.
3535    Hi = DAG.getNode(ISD::UNDEF, NVT);
3536    break;
3537  }
3538  case ISD::SIGN_EXTEND: {
3539    SDOperand In;
3540    switch (getTypeAction(Node->getOperand(0).getValueType())) {
3541    case Expand: assert(0 && "expand-expand not implemented yet!");
3542    case Legal: In = LegalizeOp(Node->getOperand(0)); break;
3543    case Promote:
3544      In = PromoteOp(Node->getOperand(0));
3545      // Emit the appropriate sign_extend_inreg to get the value we want.
3546      In = DAG.getNode(ISD::SIGN_EXTEND_INREG, In.getValueType(), In,
3547                       DAG.getValueType(Node->getOperand(0).getValueType()));
3548      break;
3549    }
3550
3551    // The low part is just a sign extension of the input (which degenerates to
3552    // a copy).
3553    Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, In);
3554
3555    // The high part is obtained by SRA'ing all but one of the bits of the lo
3556    // part.
3557    unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
3558    Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1,
3559                                                       TLI.getShiftAmountTy()));
3560    break;
3561  }
3562  case ISD::ZERO_EXTEND: {
3563    SDOperand In;
3564    switch (getTypeAction(Node->getOperand(0).getValueType())) {
3565    case Expand: assert(0 && "expand-expand not implemented yet!");
3566    case Legal: In = LegalizeOp(Node->getOperand(0)); break;
3567    case Promote:
3568      In = PromoteOp(Node->getOperand(0));
3569      // Emit the appropriate zero_extend_inreg to get the value we want.
3570      In = DAG.getZeroExtendInReg(In, Node->getOperand(0).getValueType());
3571      break;
3572    }
3573
3574    // The low part is just a zero extension of the input (which degenerates to
3575    // a copy).
3576    Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, In);
3577
3578    // The high part is just a zero.
3579    Hi = DAG.getConstant(0, NVT);
3580    break;
3581  }
3582
3583  case ISD::READCYCLECOUNTER: {
3584    assert(TLI.getOperationAction(ISD::READCYCLECOUNTER, VT) ==
3585                 TargetLowering::Custom &&
3586           "Must custom expand ReadCycleCounter");
3587    SDOperand T = TLI.LowerOperation(Op, DAG);
3588    assert(T.Val && "Node must be custom expanded!");
3589    Lo = LegalizeOp(T.getValue(0));
3590    Hi = LegalizeOp(T.getValue(1));
3591    AddLegalizedOperand(SDOperand(Node, 1), // Remember we legalized the chain.
3592                        LegalizeOp(T.getValue(2)));
3593    break;
3594  }
3595
3596    // These operators cannot be expanded directly, emit them as calls to
3597    // library functions.
3598  case ISD::FP_TO_SINT:
3599    if (TLI.getOperationAction(ISD::FP_TO_SINT, VT) == TargetLowering::Custom) {
3600      SDOperand Op;
3601      switch (getTypeAction(Node->getOperand(0).getValueType())) {
3602      case Expand: assert(0 && "cannot expand FP!");
3603      case Legal: Op = LegalizeOp(Node->getOperand(0)); break;
3604      case Promote: Op = PromoteOp(Node->getOperand(0)); break;
3605      }
3606
3607      Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_SINT, VT, Op), DAG);
3608
3609      // Now that the custom expander is done, expand the result, which is still
3610      // VT.
3611      if (Op.Val) {
3612        ExpandOp(Op, Lo, Hi);
3613        break;
3614      }
3615    }
3616
3617    if (Node->getOperand(0).getValueType() == MVT::f32)
3618      Lo = ExpandLibCall("__fixsfdi", Node, Hi);
3619    else
3620      Lo = ExpandLibCall("__fixdfdi", Node, Hi);
3621    break;
3622
3623  case ISD::FP_TO_UINT:
3624    if (TLI.getOperationAction(ISD::FP_TO_UINT, VT) == TargetLowering::Custom) {
3625      SDOperand Op = DAG.getNode(ISD::FP_TO_UINT, VT,
3626                                 LegalizeOp(Node->getOperand(0)));
3627      // Now that the custom expander is done, expand the result, which is still
3628      // VT.
3629      Op = TLI.LowerOperation(Op, DAG);
3630      if (Op.Val) {
3631        ExpandOp(Op, Lo, Hi);
3632        break;
3633      }
3634    }
3635
3636    if (Node->getOperand(0).getValueType() == MVT::f32)
3637      Lo = ExpandLibCall("__fixunssfdi", Node, Hi);
3638    else
3639      Lo = ExpandLibCall("__fixunsdfdi", Node, Hi);
3640    break;
3641
3642  case ISD::SHL:
3643    // If the target wants custom lowering, do so.
3644    if (TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Custom) {
3645      SDOperand Op = DAG.getNode(ISD::SHL, VT, Node->getOperand(0),
3646                                 LegalizeOp(Node->getOperand(1)));
3647      Op = TLI.LowerOperation(Op, DAG);
3648      if (Op.Val) {
3649        // Now that the custom expander is done, expand the result, which is
3650        // still VT.
3651        ExpandOp(Op, Lo, Hi);
3652        break;
3653      }
3654    }
3655
3656    // If we can emit an efficient shift operation, do so now.
3657    if (ExpandShift(ISD::SHL, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
3658      break;
3659
3660    // If this target supports SHL_PARTS, use it.
3661    if (TLI.isOperationLegal(ISD::SHL_PARTS, NVT)) {
3662      ExpandShiftParts(ISD::SHL_PARTS, Node->getOperand(0), Node->getOperand(1),
3663                       Lo, Hi);
3664      break;
3665    }
3666
3667    // Otherwise, emit a libcall.
3668    Lo = ExpandLibCall("__ashldi3", Node, Hi);
3669    break;
3670
3671  case ISD::SRA:
3672    // If the target wants custom lowering, do so.
3673    if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Custom) {
3674      SDOperand Op = DAG.getNode(ISD::SRA, VT, Node->getOperand(0),
3675                                 LegalizeOp(Node->getOperand(1)));
3676      Op = TLI.LowerOperation(Op, DAG);
3677      if (Op.Val) {
3678        // Now that the custom expander is done, expand the result, which is
3679        // still VT.
3680        ExpandOp(Op, Lo, Hi);
3681        break;
3682      }
3683    }
3684
3685    // If we can emit an efficient shift operation, do so now.
3686    if (ExpandShift(ISD::SRA, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
3687      break;
3688
3689    // If this target supports SRA_PARTS, use it.
3690    if (TLI.isOperationLegal(ISD::SRA_PARTS, NVT)) {
3691      ExpandShiftParts(ISD::SRA_PARTS, Node->getOperand(0), Node->getOperand(1),
3692                       Lo, Hi);
3693      break;
3694    }
3695
3696    // Otherwise, emit a libcall.
3697    Lo = ExpandLibCall("__ashrdi3", Node, Hi);
3698    break;
3699  case ISD::SRL:
3700    // If the target wants custom lowering, do so.
3701    if (TLI.getOperationAction(ISD::SRL, VT) == TargetLowering::Custom) {
3702      SDOperand Op = DAG.getNode(ISD::SRL, VT, Node->getOperand(0),
3703                                 LegalizeOp(Node->getOperand(1)));
3704      Op = TLI.LowerOperation(Op, DAG);
3705      if (Op.Val) {
3706        // Now that the custom expander is done, expand the result, which is
3707        // still VT.
3708        ExpandOp(Op, Lo, Hi);
3709        break;
3710      }
3711    }
3712
3713    // If we can emit an efficient shift operation, do so now.
3714    if (ExpandShift(ISD::SRL, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
3715      break;
3716
3717    // If this target supports SRL_PARTS, use it.
3718    if (TLI.isOperationLegal(ISD::SRL_PARTS, NVT)) {
3719      ExpandShiftParts(ISD::SRL_PARTS, Node->getOperand(0), Node->getOperand(1),
3720                       Lo, Hi);
3721      break;
3722    }
3723
3724    // Otherwise, emit a libcall.
3725    Lo = ExpandLibCall("__lshrdi3", Node, Hi);
3726    break;
3727
3728  case ISD::ADD:
3729    ExpandByParts(ISD::ADD_PARTS, Node->getOperand(0), Node->getOperand(1),
3730                  Lo, Hi);
3731    break;
3732  case ISD::SUB:
3733    ExpandByParts(ISD::SUB_PARTS, Node->getOperand(0), Node->getOperand(1),
3734                  Lo, Hi);
3735    break;
3736  case ISD::MUL: {
3737    if (TLI.isOperationLegal(ISD::MULHU, NVT)) {
3738      SDOperand LL, LH, RL, RH;
3739      ExpandOp(Node->getOperand(0), LL, LH);
3740      ExpandOp(Node->getOperand(1), RL, RH);
3741      unsigned SH = MVT::getSizeInBits(RH.getValueType())-1;
3742      // MULHS implicitly sign extends its inputs.  Check to see if ExpandOp
3743      // extended the sign bit of the low half through the upper half, and if so
3744      // emit a MULHS instead of the alternate sequence that is valid for any
3745      // i64 x i64 multiply.
3746      if (TLI.isOperationLegal(ISD::MULHS, NVT) &&
3747          // is RH an extension of the sign bit of RL?
3748          RH.getOpcode() == ISD::SRA && RH.getOperand(0) == RL &&
3749          RH.getOperand(1).getOpcode() == ISD::Constant &&
3750          cast<ConstantSDNode>(RH.getOperand(1))->getValue() == SH &&
3751          // is LH an extension of the sign bit of LL?
3752          LH.getOpcode() == ISD::SRA && LH.getOperand(0) == LL &&
3753          LH.getOperand(1).getOpcode() == ISD::Constant &&
3754          cast<ConstantSDNode>(LH.getOperand(1))->getValue() == SH) {
3755        Hi = DAG.getNode(ISD::MULHS, NVT, LL, RL);
3756      } else {
3757        Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
3758        RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
3759        LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
3760        Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
3761        Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
3762      }
3763      Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
3764    } else {
3765      Lo = ExpandLibCall("__muldi3" , Node, Hi); break;
3766    }
3767    break;
3768  }
3769  case ISD::SDIV: Lo = ExpandLibCall("__divdi3" , Node, Hi); break;
3770  case ISD::UDIV: Lo = ExpandLibCall("__udivdi3", Node, Hi); break;
3771  case ISD::SREM: Lo = ExpandLibCall("__moddi3" , Node, Hi); break;
3772  case ISD::UREM: Lo = ExpandLibCall("__umoddi3", Node, Hi); break;
3773  }
3774
3775  // Remember in a map if the values will be reused later.
3776  bool isNew = ExpandedNodes.insert(std::make_pair(Op,
3777                                          std::make_pair(Lo, Hi))).second;
3778  assert(isNew && "Value already expanded?!?");
3779}
3780
3781
3782// SelectionDAG::Legalize - This is the entry point for the file.
3783//
3784void SelectionDAG::Legalize() {
3785  /// run - This is the main entry point to this class.
3786  ///
3787  SelectionDAGLegalize(*this).Run();
3788}
3789
3790