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