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