LegalizeDAG.cpp revision 509150f973ae650a57b79010a3ec36e60e40f41d
1//===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// 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/CodeGen/MachineJumpTableInfo.h"
18#include "llvm/CodeGen/MachineModuleInfo.h"
19#include "llvm/CodeGen/DwarfWriter.h"
20#include "llvm/Analysis/DebugInfo.h"
21#include "llvm/CodeGen/PseudoSourceValue.h"
22#include "llvm/Target/TargetFrameInfo.h"
23#include "llvm/Target/TargetLowering.h"
24#include "llvm/Target/TargetData.h"
25#include "llvm/Target/TargetMachine.h"
26#include "llvm/Target/TargetOptions.h"
27#include "llvm/Target/TargetSubtarget.h"
28#include "llvm/CallingConv.h"
29#include "llvm/Constants.h"
30#include "llvm/DerivedTypes.h"
31#include "llvm/Function.h"
32#include "llvm/GlobalVariable.h"
33#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Compiler.h"
35#include "llvm/Support/MathExtras.h"
36#include "llvm/ADT/DenseMap.h"
37#include "llvm/ADT/SmallVector.h"
38#include "llvm/ADT/SmallPtrSet.h"
39#include <map>
40using namespace llvm;
41
42//===----------------------------------------------------------------------===//
43/// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
44/// hacks on it until the target machine can handle it.  This involves
45/// eliminating value sizes the machine cannot handle (promoting small sizes to
46/// large sizes or splitting up large values into small values) as well as
47/// eliminating operations the machine cannot handle.
48///
49/// This code also does a small amount of optimization and recognition of idioms
50/// as part of its processing.  For example, if a target does not support a
51/// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
52/// will attempt merge setcc and brc instructions into brcc's.
53///
54namespace {
55class VISIBILITY_HIDDEN SelectionDAGLegalize {
56  TargetLowering &TLI;
57  SelectionDAG &DAG;
58  CodeGenOpt::Level OptLevel;
59
60  // Libcall insertion helpers.
61
62  /// LastCALLSEQ_END - This keeps track of the CALLSEQ_END node that has been
63  /// legalized.  We use this to ensure that calls are properly serialized
64  /// against each other, including inserted libcalls.
65  SDValue LastCALLSEQ_END;
66
67  /// IsLegalizingCall - This member is used *only* for purposes of providing
68  /// helpful assertions that a libcall isn't created while another call is
69  /// being legalized (which could lead to non-serialized call sequences).
70  bool IsLegalizingCall;
71
72  enum LegalizeAction {
73    Legal,      // The target natively supports this operation.
74    Promote,    // This operation should be executed in a larger type.
75    Expand      // Try to expand this to other ops, otherwise use a libcall.
76  };
77
78  /// ValueTypeActions - This is a bitvector that contains two bits for each
79  /// value type, where the two bits correspond to the LegalizeAction enum.
80  /// This can be queried with "getTypeAction(VT)".
81  TargetLowering::ValueTypeActionImpl ValueTypeActions;
82
83  /// LegalizedNodes - For nodes that are of legal width, and that have more
84  /// than one use, this map indicates what regularized operand to use.  This
85  /// allows us to avoid legalizing the same thing more than once.
86  DenseMap<SDValue, SDValue> LegalizedNodes;
87
88  void AddLegalizedOperand(SDValue From, SDValue To) {
89    LegalizedNodes.insert(std::make_pair(From, To));
90    // If someone requests legalization of the new node, return itself.
91    if (From != To)
92      LegalizedNodes.insert(std::make_pair(To, To));
93  }
94
95public:
96  SelectionDAGLegalize(SelectionDAG &DAG, CodeGenOpt::Level ol);
97
98  /// getTypeAction - Return how we should legalize values of this type, either
99  /// it is already legal or we need to expand it into multiple registers of
100  /// smaller integer type, or we need to promote it to a larger type.
101  LegalizeAction getTypeAction(MVT VT) const {
102    return (LegalizeAction)ValueTypeActions.getTypeAction(VT);
103  }
104
105  /// isTypeLegal - Return true if this type is legal on this target.
106  ///
107  bool isTypeLegal(MVT VT) const {
108    return getTypeAction(VT) == Legal;
109  }
110
111  void LegalizeDAG();
112
113private:
114  /// HandleOp - Legalize, Promote, or Expand the specified operand as
115  /// appropriate for its type.
116  void HandleOp(SDValue Op);
117
118  /// LegalizeOp - We know that the specified value has a legal type.
119  /// Recursively ensure that the operands have legal types, then return the
120  /// result.
121  SDValue LegalizeOp(SDValue O);
122
123  /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
124  /// insertion index for the INSERT_VECTOR_ELT instruction.  In this case, it
125  /// is necessary to spill the vector being inserted into to memory, perform
126  /// the insert there, and then read the result back.
127  SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val,
128                                         SDValue Idx, DebugLoc dl);
129  SDValue ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val,
130                                  SDValue Idx, DebugLoc dl);
131
132  /// Useful 16 element vector type that is used to pass operands for widening.
133  typedef SmallVector<SDValue, 16> SDValueVector;
134
135  /// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
136  /// performs the same shuffe in terms of order or result bytes, but on a type
137  /// whose vector element type is narrower than the original shuffle type.
138  /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
139  SDValue ShuffleWithNarrowerEltType(MVT NVT, MVT VT, DebugLoc dl,
140                                     SDValue N1, SDValue N2,
141                                     SmallVectorImpl<int> &Mask) const;
142
143  bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
144                                    SmallPtrSet<SDNode*, 32> &NodesLeadingTo);
145
146  void LegalizeSetCCOperands(SDValue &LHS, SDValue &RHS, SDValue &CC,
147                             DebugLoc dl);
148  void LegalizeSetCCCondCode(MVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC,
149                             DebugLoc dl);
150  void LegalizeSetCC(MVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC,
151                     DebugLoc dl) {
152    LegalizeSetCCOperands(LHS, RHS, CC, dl);
153    LegalizeSetCCCondCode(VT, LHS, RHS, CC, dl);
154  }
155
156  SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned);
157  SDValue ExpandFPLibCall(SDNode *Node, RTLIB::Libcall Call_F32,
158                          RTLIB::Libcall Call_F64, RTLIB::Libcall Call_F80,
159                          RTLIB::Libcall Call_PPCF128);
160  SDValue ExpandIntLibCall(SDNode *Node, bool isSigned, RTLIB::Libcall Call_I16,
161                           RTLIB::Libcall Call_I32, RTLIB::Libcall Call_I64,
162                           RTLIB::Libcall Call_I128);
163
164  SDValue EmitStackConvert(SDValue SrcOp, MVT SlotVT, MVT DestVT, DebugLoc dl);
165  SDValue ExpandBUILD_VECTOR(SDNode *Node);
166  SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
167  SDValue ExpandLegalINT_TO_FP(bool isSigned, SDValue LegalOp, MVT DestVT,
168                               DebugLoc dl);
169  SDValue PromoteLegalINT_TO_FP(SDValue LegalOp, MVT DestVT, bool isSigned,
170                                DebugLoc dl);
171  SDValue PromoteLegalFP_TO_INT(SDValue LegalOp, MVT DestVT, bool isSigned,
172                                DebugLoc dl);
173
174  SDValue ExpandBSWAP(SDValue Op, DebugLoc dl);
175  SDValue ExpandBitCount(unsigned Opc, SDValue Op, DebugLoc dl);
176
177  SDValue ExpandExtractFromVectorThroughStack(SDValue Op);
178
179  void ExpandNode(SDNode *Node, SmallVectorImpl<SDValue> &Results);
180  void PromoteNode(SDNode *Node, SmallVectorImpl<SDValue> &Results);
181};
182}
183
184/// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
185/// performs the same shuffe in terms of order or result bytes, but on a type
186/// whose vector element type is narrower than the original shuffle type.
187/// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
188SDValue
189SelectionDAGLegalize::ShuffleWithNarrowerEltType(MVT NVT, MVT VT,  DebugLoc dl,
190                                                 SDValue N1, SDValue N2,
191                                             SmallVectorImpl<int> &Mask) const {
192  MVT EltVT = NVT.getVectorElementType();
193  unsigned NumMaskElts = VT.getVectorNumElements();
194  unsigned NumDestElts = NVT.getVectorNumElements();
195  unsigned NumEltsGrowth = NumDestElts / NumMaskElts;
196
197  assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
198
199  if (NumEltsGrowth == 1)
200    return DAG.getVectorShuffle(NVT, dl, N1, N2, &Mask[0]);
201
202  SmallVector<int, 8> NewMask;
203  for (unsigned i = 0; i != NumMaskElts; ++i) {
204    int Idx = Mask[i];
205    for (unsigned j = 0; j != NumEltsGrowth; ++j) {
206      if (Idx < 0)
207        NewMask.push_back(-1);
208      else
209        NewMask.push_back(Idx * NumEltsGrowth + j);
210    }
211  }
212  assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?");
213  assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?");
214  return DAG.getVectorShuffle(NVT, dl, N1, N2, &NewMask[0]);
215}
216
217SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag,
218                                           CodeGenOpt::Level ol)
219  : TLI(dag.getTargetLoweringInfo()), DAG(dag), OptLevel(ol),
220    ValueTypeActions(TLI.getValueTypeActions()) {
221  assert(MVT::LAST_VALUETYPE <= 32 &&
222         "Too many value types for ValueTypeActions to hold!");
223}
224
225void SelectionDAGLegalize::LegalizeDAG() {
226  LastCALLSEQ_END = DAG.getEntryNode();
227  IsLegalizingCall = false;
228
229  // The legalize process is inherently a bottom-up recursive process (users
230  // legalize their uses before themselves).  Given infinite stack space, we
231  // could just start legalizing on the root and traverse the whole graph.  In
232  // practice however, this causes us to run out of stack space on large basic
233  // blocks.  To avoid this problem, compute an ordering of the nodes where each
234  // node is only legalized after all of its operands are legalized.
235  DAG.AssignTopologicalOrder();
236  for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
237       E = prior(DAG.allnodes_end()); I != next(E); ++I)
238    HandleOp(SDValue(I, 0));
239
240  // Finally, it's possible the root changed.  Get the new root.
241  SDValue OldRoot = DAG.getRoot();
242  assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
243  DAG.setRoot(LegalizedNodes[OldRoot]);
244
245  LegalizedNodes.clear();
246
247  // Remove dead nodes now.
248  DAG.RemoveDeadNodes();
249}
250
251
252/// FindCallEndFromCallStart - Given a chained node that is part of a call
253/// sequence, find the CALLSEQ_END node that terminates the call sequence.
254static SDNode *FindCallEndFromCallStart(SDNode *Node) {
255  if (Node->getOpcode() == ISD::CALLSEQ_END)
256    return Node;
257  if (Node->use_empty())
258    return 0;   // No CallSeqEnd
259
260  // The chain is usually at the end.
261  SDValue TheChain(Node, Node->getNumValues()-1);
262  if (TheChain.getValueType() != MVT::Other) {
263    // Sometimes it's at the beginning.
264    TheChain = SDValue(Node, 0);
265    if (TheChain.getValueType() != MVT::Other) {
266      // Otherwise, hunt for it.
267      for (unsigned i = 1, e = Node->getNumValues(); i != e; ++i)
268        if (Node->getValueType(i) == MVT::Other) {
269          TheChain = SDValue(Node, i);
270          break;
271        }
272
273      // Otherwise, we walked into a node without a chain.
274      if (TheChain.getValueType() != MVT::Other)
275        return 0;
276    }
277  }
278
279  for (SDNode::use_iterator UI = Node->use_begin(),
280       E = Node->use_end(); UI != E; ++UI) {
281
282    // Make sure to only follow users of our token chain.
283    SDNode *User = *UI;
284    for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
285      if (User->getOperand(i) == TheChain)
286        if (SDNode *Result = FindCallEndFromCallStart(User))
287          return Result;
288  }
289  return 0;
290}
291
292/// FindCallStartFromCallEnd - Given a chained node that is part of a call
293/// sequence, find the CALLSEQ_START node that initiates the call sequence.
294static SDNode *FindCallStartFromCallEnd(SDNode *Node) {
295  assert(Node && "Didn't find callseq_start for a call??");
296  if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
297
298  assert(Node->getOperand(0).getValueType() == MVT::Other &&
299         "Node doesn't have a token chain argument!");
300  return FindCallStartFromCallEnd(Node->getOperand(0).getNode());
301}
302
303/// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking to
304/// see if any uses can reach Dest.  If no dest operands can get to dest,
305/// legalize them, legalize ourself, and return false, otherwise, return true.
306///
307/// Keep track of the nodes we fine that actually do lead to Dest in
308/// NodesLeadingTo.  This avoids retraversing them exponential number of times.
309///
310bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
311                                     SmallPtrSet<SDNode*, 32> &NodesLeadingTo) {
312  if (N == Dest) return true;  // N certainly leads to Dest :)
313
314  // If we've already processed this node and it does lead to Dest, there is no
315  // need to reprocess it.
316  if (NodesLeadingTo.count(N)) return true;
317
318  // If the first result of this node has been already legalized, then it cannot
319  // reach N.
320  if (LegalizedNodes.count(SDValue(N, 0))) return false;
321
322  // Okay, this node has not already been legalized.  Check and legalize all
323  // operands.  If none lead to Dest, then we can legalize this node.
324  bool OperandsLeadToDest = false;
325  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
326    OperandsLeadToDest |=     // If an operand leads to Dest, so do we.
327      LegalizeAllNodesNotLeadingTo(N->getOperand(i).getNode(), Dest, NodesLeadingTo);
328
329  if (OperandsLeadToDest) {
330    NodesLeadingTo.insert(N);
331    return true;
332  }
333
334  // Okay, this node looks safe, legalize it and return false.
335  HandleOp(SDValue(N, 0));
336  return false;
337}
338
339/// HandleOp - Legalize, Promote, Widen, or Expand the specified operand as
340/// appropriate for its type.
341void SelectionDAGLegalize::HandleOp(SDValue Op) {
342  // Don't touch TargetConstants
343  if (Op.getOpcode() == ISD::TargetConstant)
344    return;
345  MVT VT = Op.getValueType();
346  // We should never see any illegal result types here.
347  assert(isTypeLegal(VT) && "Illegal type introduced after type legalization?");
348  (void)LegalizeOp(Op);
349}
350
351/// ExpandConstantFP - Expands the ConstantFP node to an integer constant or
352/// a load from the constant pool.
353static SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP,
354                                SelectionDAG &DAG, const TargetLowering &TLI) {
355  bool Extend = false;
356  DebugLoc dl = CFP->getDebugLoc();
357
358  // If a FP immediate is precise when represented as a float and if the
359  // target can do an extending load from float to double, we put it into
360  // the constant pool as a float, even if it's is statically typed as a
361  // double.  This shrinks FP constants and canonicalizes them for targets where
362  // an FP extending load is the same cost as a normal load (such as on the x87
363  // fp stack or PPC FP unit).
364  MVT VT = CFP->getValueType(0);
365  ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
366  if (!UseCP) {
367    assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion");
368    return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(),
369                           (VT == MVT::f64) ? MVT::i64 : MVT::i32);
370  }
371
372  MVT OrigVT = VT;
373  MVT SVT = VT;
374  while (SVT != MVT::f32) {
375    SVT = (MVT::SimpleValueType)(SVT.getSimpleVT() - 1);
376    if (CFP->isValueValidForType(SVT, CFP->getValueAPF()) &&
377        // Only do this if the target has a native EXTLOAD instruction from
378        // smaller type.
379        TLI.isLoadExtLegal(ISD::EXTLOAD, SVT) &&
380        TLI.ShouldShrinkFPConstant(OrigVT)) {
381      const Type *SType = SVT.getTypeForMVT();
382      LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
383      VT = SVT;
384      Extend = true;
385    }
386  }
387
388  SDValue CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
389  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
390  if (Extend)
391    return DAG.getExtLoad(ISD::EXTLOAD, dl,
392                          OrigVT, DAG.getEntryNode(),
393                          CPIdx, PseudoSourceValue::getConstantPool(),
394                          0, VT, false, Alignment);
395  return DAG.getLoad(OrigVT, dl, DAG.getEntryNode(), CPIdx,
396                     PseudoSourceValue::getConstantPool(), 0, false, Alignment);
397}
398
399/// ExpandUnalignedStore - Expands an unaligned store to 2 half-size stores.
400static
401SDValue ExpandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG,
402                             const TargetLowering &TLI) {
403  SDValue Chain = ST->getChain();
404  SDValue Ptr = ST->getBasePtr();
405  SDValue Val = ST->getValue();
406  MVT VT = Val.getValueType();
407  int Alignment = ST->getAlignment();
408  int SVOffset = ST->getSrcValueOffset();
409  DebugLoc dl = ST->getDebugLoc();
410  if (ST->getMemoryVT().isFloatingPoint() ||
411      ST->getMemoryVT().isVector()) {
412    MVT intVT = MVT::getIntegerVT(VT.getSizeInBits());
413    if (TLI.isTypeLegal(intVT)) {
414      // Expand to a bitconvert of the value to the integer type of the
415      // same size, then a (misaligned) int store.
416      // FIXME: Does not handle truncating floating point stores!
417      SDValue Result = DAG.getNode(ISD::BIT_CONVERT, dl, intVT, Val);
418      return DAG.getStore(Chain, dl, Result, Ptr, ST->getSrcValue(),
419                          SVOffset, ST->isVolatile(), Alignment);
420    } else {
421      // Do a (aligned) store to a stack slot, then copy from the stack slot
422      // to the final destination using (unaligned) integer loads and stores.
423      MVT StoredVT = ST->getMemoryVT();
424      MVT RegVT =
425        TLI.getRegisterType(MVT::getIntegerVT(StoredVT.getSizeInBits()));
426      unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
427      unsigned RegBytes = RegVT.getSizeInBits() / 8;
428      unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
429
430      // Make sure the stack slot is also aligned for the register type.
431      SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
432
433      // Perform the original store, only redirected to the stack slot.
434      SDValue Store = DAG.getTruncStore(Chain, dl,
435                                        Val, StackPtr, NULL, 0, StoredVT);
436      SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
437      SmallVector<SDValue, 8> Stores;
438      unsigned Offset = 0;
439
440      // Do all but one copies using the full register width.
441      for (unsigned i = 1; i < NumRegs; i++) {
442        // Load one integer register's worth from the stack slot.
443        SDValue Load = DAG.getLoad(RegVT, dl, Store, StackPtr, NULL, 0);
444        // Store it to the final location.  Remember the store.
445        Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
446                                      ST->getSrcValue(), SVOffset + Offset,
447                                      ST->isVolatile(),
448                                      MinAlign(ST->getAlignment(), Offset)));
449        // Increment the pointers.
450        Offset += RegBytes;
451        StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
452                               Increment);
453        Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
454      }
455
456      // The last store may be partial.  Do a truncating store.  On big-endian
457      // machines this requires an extending load from the stack slot to ensure
458      // that the bits are in the right place.
459      MVT MemVT = MVT::getIntegerVT(8 * (StoredBytes - Offset));
460
461      // Load from the stack slot.
462      SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
463                                    NULL, 0, MemVT);
464
465      Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
466                                         ST->getSrcValue(), SVOffset + Offset,
467                                         MemVT, ST->isVolatile(),
468                                         MinAlign(ST->getAlignment(), Offset)));
469      // The order of the stores doesn't matter - say it with a TokenFactor.
470      return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
471                         Stores.size());
472    }
473  }
474  assert(ST->getMemoryVT().isInteger() &&
475         !ST->getMemoryVT().isVector() &&
476         "Unaligned store of unknown type.");
477  // Get the half-size VT
478  MVT NewStoredVT =
479    (MVT::SimpleValueType)(ST->getMemoryVT().getSimpleVT() - 1);
480  int NumBits = NewStoredVT.getSizeInBits();
481  int IncrementSize = NumBits / 8;
482
483  // Divide the stored value in two parts.
484  SDValue ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
485  SDValue Lo = Val;
486  SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
487
488  // Store the two parts
489  SDValue Store1, Store2;
490  Store1 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Lo:Hi, Ptr,
491                             ST->getSrcValue(), SVOffset, NewStoredVT,
492                             ST->isVolatile(), Alignment);
493  Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
494                    DAG.getConstant(IncrementSize, TLI.getPointerTy()));
495  Alignment = MinAlign(Alignment, IncrementSize);
496  Store2 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Hi:Lo, Ptr,
497                             ST->getSrcValue(), SVOffset + IncrementSize,
498                             NewStoredVT, ST->isVolatile(), Alignment);
499
500  return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
501}
502
503/// ExpandUnalignedLoad - Expands an unaligned load to 2 half-size loads.
504static
505SDValue ExpandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG,
506                            const TargetLowering &TLI) {
507  int SVOffset = LD->getSrcValueOffset();
508  SDValue Chain = LD->getChain();
509  SDValue Ptr = LD->getBasePtr();
510  MVT VT = LD->getValueType(0);
511  MVT LoadedVT = LD->getMemoryVT();
512  DebugLoc dl = LD->getDebugLoc();
513  if (VT.isFloatingPoint() || VT.isVector()) {
514    MVT intVT = MVT::getIntegerVT(LoadedVT.getSizeInBits());
515    if (TLI.isTypeLegal(intVT)) {
516      // Expand to a (misaligned) integer load of the same size,
517      // then bitconvert to floating point or vector.
518      SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, LD->getSrcValue(),
519                                    SVOffset, LD->isVolatile(),
520                                    LD->getAlignment());
521      SDValue Result = DAG.getNode(ISD::BIT_CONVERT, dl, LoadedVT, newLoad);
522      if (VT.isFloatingPoint() && LoadedVT != VT)
523        Result = DAG.getNode(ISD::FP_EXTEND, dl, VT, Result);
524
525      SDValue Ops[] = { Result, Chain };
526      return DAG.getMergeValues(Ops, 2, dl);
527    } else {
528      // Copy the value to a (aligned) stack slot using (unaligned) integer
529      // loads and stores, then do a (aligned) load from the stack slot.
530      MVT RegVT = TLI.getRegisterType(intVT);
531      unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
532      unsigned RegBytes = RegVT.getSizeInBits() / 8;
533      unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
534
535      // Make sure the stack slot is also aligned for the register type.
536      SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
537
538      SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
539      SmallVector<SDValue, 8> Stores;
540      SDValue StackPtr = StackBase;
541      unsigned Offset = 0;
542
543      // Do all but one copies using the full register width.
544      for (unsigned i = 1; i < NumRegs; i++) {
545        // Load one integer register's worth from the original location.
546        SDValue Load = DAG.getLoad(RegVT, dl, Chain, Ptr, LD->getSrcValue(),
547                                   SVOffset + Offset, LD->isVolatile(),
548                                   MinAlign(LD->getAlignment(), Offset));
549        // Follow the load with a store to the stack slot.  Remember the store.
550        Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
551                                      NULL, 0));
552        // Increment the pointers.
553        Offset += RegBytes;
554        Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
555        StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
556                               Increment);
557      }
558
559      // The last copy may be partial.  Do an extending load.
560      MVT MemVT = MVT::getIntegerVT(8 * (LoadedBytes - Offset));
561      SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
562                                    LD->getSrcValue(), SVOffset + Offset,
563                                    MemVT, LD->isVolatile(),
564                                    MinAlign(LD->getAlignment(), Offset));
565      // Follow the load with a store to the stack slot.  Remember the store.
566      // On big-endian machines this requires a truncating store to ensure
567      // that the bits end up in the right place.
568      Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
569                                         NULL, 0, MemVT));
570
571      // The order of the stores doesn't matter - say it with a TokenFactor.
572      SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
573                               Stores.size());
574
575      // Finally, perform the original load only redirected to the stack slot.
576      Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
577                            NULL, 0, LoadedVT);
578
579      // Callers expect a MERGE_VALUES node.
580      SDValue Ops[] = { Load, TF };
581      return DAG.getMergeValues(Ops, 2, dl);
582    }
583  }
584  assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
585         "Unaligned load of unsupported type.");
586
587  // Compute the new VT that is half the size of the old one.  This is an
588  // integer MVT.
589  unsigned NumBits = LoadedVT.getSizeInBits();
590  MVT NewLoadedVT;
591  NewLoadedVT = MVT::getIntegerVT(NumBits/2);
592  NumBits >>= 1;
593
594  unsigned Alignment = LD->getAlignment();
595  unsigned IncrementSize = NumBits / 8;
596  ISD::LoadExtType HiExtType = LD->getExtensionType();
597
598  // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
599  if (HiExtType == ISD::NON_EXTLOAD)
600    HiExtType = ISD::ZEXTLOAD;
601
602  // Load the value in two parts
603  SDValue Lo, Hi;
604  if (TLI.isLittleEndian()) {
605    Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getSrcValue(),
606                        SVOffset, NewLoadedVT, LD->isVolatile(), Alignment);
607    Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
608                      DAG.getConstant(IncrementSize, TLI.getPointerTy()));
609    Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getSrcValue(),
610                        SVOffset + IncrementSize, NewLoadedVT, LD->isVolatile(),
611                        MinAlign(Alignment, IncrementSize));
612  } else {
613    Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getSrcValue(),
614                        SVOffset, NewLoadedVT, LD->isVolatile(), Alignment);
615    Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
616                      DAG.getConstant(IncrementSize, TLI.getPointerTy()));
617    Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getSrcValue(),
618                        SVOffset + IncrementSize, NewLoadedVT, LD->isVolatile(),
619                        MinAlign(Alignment, IncrementSize));
620  }
621
622  // aggregate the two parts
623  SDValue ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
624  SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
625  Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
626
627  SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
628                             Hi.getValue(1));
629
630  SDValue Ops[] = { Result, TF };
631  return DAG.getMergeValues(Ops, 2, dl);
632}
633
634/// PerformInsertVectorEltInMemory - Some target cannot handle a variable
635/// insertion index for the INSERT_VECTOR_ELT instruction.  In this case, it
636/// is necessary to spill the vector being inserted into to memory, perform
637/// the insert there, and then read the result back.
638SDValue SelectionDAGLegalize::
639PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx,
640                               DebugLoc dl) {
641  SDValue Tmp1 = Vec;
642  SDValue Tmp2 = Val;
643  SDValue Tmp3 = Idx;
644
645  // If the target doesn't support this, we have to spill the input vector
646  // to a temporary stack slot, update the element, then reload it.  This is
647  // badness.  We could also load the value into a vector register (either
648  // with a "move to register" or "extload into register" instruction, then
649  // permute it into place, if the idx is a constant and if the idx is
650  // supported by the target.
651  MVT VT    = Tmp1.getValueType();
652  MVT EltVT = VT.getVectorElementType();
653  MVT IdxVT = Tmp3.getValueType();
654  MVT PtrVT = TLI.getPointerTy();
655  SDValue StackPtr = DAG.CreateStackTemporary(VT);
656
657  int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
658
659  // Store the vector.
660  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Tmp1, StackPtr,
661                            PseudoSourceValue::getFixedStack(SPFI), 0);
662
663  // Truncate or zero extend offset to target pointer type.
664  unsigned CastOpc = IdxVT.bitsGT(PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
665  Tmp3 = DAG.getNode(CastOpc, dl, PtrVT, Tmp3);
666  // Add the offset to the index.
667  unsigned EltSize = EltVT.getSizeInBits()/8;
668  Tmp3 = DAG.getNode(ISD::MUL, dl, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
669  SDValue StackPtr2 = DAG.getNode(ISD::ADD, dl, IdxVT, Tmp3, StackPtr);
670  // Store the scalar value.
671  Ch = DAG.getTruncStore(Ch, dl, Tmp2, StackPtr2,
672                         PseudoSourceValue::getFixedStack(SPFI), 0, EltVT);
673  // Load the updated vector.
674  return DAG.getLoad(VT, dl, Ch, StackPtr,
675                     PseudoSourceValue::getFixedStack(SPFI), 0);
676}
677
678
679SDValue SelectionDAGLegalize::
680ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, SDValue Idx, DebugLoc dl) {
681  if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) {
682    // SCALAR_TO_VECTOR requires that the type of the value being inserted
683    // match the element type of the vector being created, except for
684    // integers in which case the inserted value can be over width.
685    MVT EltVT = Vec.getValueType().getVectorElementType();
686    if (Val.getValueType() == EltVT ||
687        (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) {
688      SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
689                                  Vec.getValueType(), Val);
690
691      unsigned NumElts = Vec.getValueType().getVectorNumElements();
692      // We generate a shuffle of InVec and ScVec, so the shuffle mask
693      // should be 0,1,2,3,4,5... with the appropriate element replaced with
694      // elt 0 of the RHS.
695      SmallVector<int, 8> ShufOps;
696      for (unsigned i = 0; i != NumElts; ++i)
697        ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts);
698
699      return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec,
700                                  &ShufOps[0]);
701    }
702  }
703  return PerformInsertVectorEltInMemory(Vec, Val, Idx, dl);
704}
705
706/// LegalizeOp - We know that the specified value has a legal type, and
707/// that its operands are legal.  Now ensure that the operation itself
708/// is legal, recursively ensuring that the operands' operations remain
709/// legal.
710SDValue SelectionDAGLegalize::LegalizeOp(SDValue Op) {
711  if (Op.getOpcode() == ISD::TargetConstant) // Allow illegal target nodes.
712    return Op;
713
714  SDNode *Node = Op.getNode();
715  DebugLoc dl = Node->getDebugLoc();
716
717  for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
718    assert(getTypeAction(Node->getValueType(i)) == Legal &&
719           "Unexpected illegal type!");
720
721  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
722    assert((isTypeLegal(Node->getOperand(i).getValueType()) ||
723            Node->getOperand(i).getOpcode() == ISD::TargetConstant) &&
724           "Unexpected illegal type!");
725
726  // Note that LegalizeOp may be reentered even from single-use nodes, which
727  // means that we always must cache transformed nodes.
728  DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
729  if (I != LegalizedNodes.end()) return I->second;
730
731  SDValue Tmp1, Tmp2, Tmp3, Tmp4;
732  SDValue Result = Op;
733  bool isCustom = false;
734
735  // Figure out the correct action; the way to query this varies by opcode
736  TargetLowering::LegalizeAction Action;
737  bool SimpleFinishLegalizing = true;
738  switch (Node->getOpcode()) {
739  case ISD::INTRINSIC_W_CHAIN:
740  case ISD::INTRINSIC_WO_CHAIN:
741  case ISD::INTRINSIC_VOID:
742  case ISD::VAARG:
743  case ISD::STACKSAVE:
744    Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
745    break;
746  case ISD::SINT_TO_FP:
747  case ISD::UINT_TO_FP:
748  case ISD::EXTRACT_VECTOR_ELT:
749    Action = TLI.getOperationAction(Node->getOpcode(),
750                                    Node->getOperand(0).getValueType());
751    break;
752  case ISD::FP_ROUND_INREG:
753  case ISD::SIGN_EXTEND_INREG: {
754    MVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT();
755    Action = TLI.getOperationAction(Node->getOpcode(), InnerType);
756    break;
757  }
758  case ISD::LOAD:
759  case ISD::STORE:
760  case ISD::BR_CC:
761  case ISD::FORMAL_ARGUMENTS:
762  case ISD::CALL:
763  case ISD::CALLSEQ_START:
764  case ISD::CALLSEQ_END:
765  case ISD::SELECT_CC:
766  case ISD::SETCC:
767    // These instructions have properties that aren't modeled in the
768    // generic codepath
769    SimpleFinishLegalizing = false;
770    break;
771  case ISD::EXTRACT_ELEMENT:
772  case ISD::FLT_ROUNDS_:
773  case ISD::SADDO:
774  case ISD::SSUBO:
775  case ISD::UADDO:
776  case ISD::USUBO:
777  case ISD::SMULO:
778  case ISD::UMULO:
779  case ISD::FPOWI:
780  case ISD::MERGE_VALUES:
781  case ISD::EH_RETURN:
782  case ISD::FRAME_TO_ARGS_OFFSET:
783    // These operations lie about being legal: when they claim to be legal,
784    // they should actually be expanded.
785    Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
786    if (Action == TargetLowering::Legal)
787      Action = TargetLowering::Expand;
788    break;
789  case ISD::TRAMPOLINE:
790  case ISD::FRAMEADDR:
791  case ISD::RETURNADDR:
792    // These operations lie about being legal: they must always be
793    // custom-lowered.
794    Action = TargetLowering::Custom;
795    break;
796  case ISD::BUILD_VECTOR:
797    // A weird case: when a BUILD_VECTOR is custom-lowered, it doesn't legalize
798    // its operands first!
799    SimpleFinishLegalizing = false;
800    break;
801  default:
802    if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
803      Action = TargetLowering::Legal;
804    } else {
805      Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
806    }
807    break;
808  }
809
810  if (SimpleFinishLegalizing) {
811    SmallVector<SDValue, 8> Ops, ResultVals;
812    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
813      Ops.push_back(LegalizeOp(Node->getOperand(i)));
814    switch (Node->getOpcode()) {
815    default: break;
816    case ISD::BR:
817    case ISD::BRIND:
818    case ISD::BR_JT:
819    case ISD::BR_CC:
820    case ISD::BRCOND:
821    case ISD::RET:
822      // Branches tweak the chain to include LastCALLSEQ_END
823      Ops[0] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ops[0],
824                            LastCALLSEQ_END);
825      Ops[0] = LegalizeOp(Ops[0]);
826      LastCALLSEQ_END = DAG.getEntryNode();
827      break;
828    case ISD::SHL:
829    case ISD::SRL:
830    case ISD::SRA:
831    case ISD::ROTL:
832    case ISD::ROTR:
833      // Legalizing shifts/rotates requires adjusting the shift amount
834      // to the appropriate width.
835      if (!Ops[1].getValueType().isVector())
836        Ops[1] = LegalizeOp(DAG.getShiftAmountOperand(Ops[1]));
837      break;
838    }
839
840    Result = DAG.UpdateNodeOperands(Result.getValue(0), Ops.data(),
841                                    Ops.size());
842    switch (Action) {
843    case TargetLowering::Legal:
844      for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
845        ResultVals.push_back(Result.getValue(i));
846      break;
847    case TargetLowering::Custom:
848      // FIXME: The handling for custom lowering with multiple results is
849      // a complete mess.
850      Tmp1 = TLI.LowerOperation(Result, DAG);
851      if (Tmp1.getNode()) {
852        for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
853          if (e == 1)
854            ResultVals.push_back(Tmp1);
855          else
856            ResultVals.push_back(Tmp1.getValue(i));
857        }
858        break;
859      }
860
861      // FALL THROUGH
862    case TargetLowering::Expand:
863      ExpandNode(Result.getNode(), ResultVals);
864      break;
865    case TargetLowering::Promote:
866      PromoteNode(Result.getNode(), ResultVals);
867      break;
868    }
869    if (!ResultVals.empty()) {
870      for (unsigned i = 0, e = ResultVals.size(); i != e; ++i) {
871        if (ResultVals[i] != SDValue(Node, i))
872          ResultVals[i] = LegalizeOp(ResultVals[i]);
873        AddLegalizedOperand(SDValue(Node, i), ResultVals[i]);
874      }
875      return ResultVals[Op.getResNo()];
876    }
877  }
878
879  switch (Node->getOpcode()) {
880  default:
881#ifndef NDEBUG
882    cerr << "NODE: "; Node->dump(&DAG); cerr << "\n";
883#endif
884    assert(0 && "Do not know how to legalize this operator!");
885    abort();
886  case ISD::DBG_STOPPOINT:
887    assert(Node->getNumOperands() == 1 && "Invalid DBG_STOPPOINT node!");
888    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the input chain.
889
890    switch (TLI.getOperationAction(ISD::DBG_STOPPOINT, MVT::Other)) {
891    case TargetLowering::Promote:
892    default: assert(0 && "This action is not supported yet!");
893    case TargetLowering::Expand: {
894      DwarfWriter *DW = DAG.getDwarfWriter();
895      bool useDEBUG_LOC = TLI.isOperationLegalOrCustom(ISD::DEBUG_LOC,
896                                                       MVT::Other);
897      bool useLABEL = TLI.isOperationLegalOrCustom(ISD::DBG_LABEL, MVT::Other);
898
899      const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(Node);
900      GlobalVariable *CU_GV = cast<GlobalVariable>(DSP->getCompileUnit());
901      if (DW && (useDEBUG_LOC || useLABEL) && !CU_GV->isDeclaration()) {
902        DICompileUnit CU(cast<GlobalVariable>(DSP->getCompileUnit()));
903
904        unsigned Line = DSP->getLine();
905        unsigned Col = DSP->getColumn();
906
907        if (OptLevel == CodeGenOpt::None) {
908          // A bit self-referential to have DebugLoc on Debug_Loc nodes, but it
909          // won't hurt anything.
910          if (useDEBUG_LOC) {
911            SDValue Ops[] = { Tmp1, DAG.getConstant(Line, MVT::i32),
912                              DAG.getConstant(Col, MVT::i32),
913                              DAG.getSrcValue(CU.getGV()) };
914            Result = DAG.getNode(ISD::DEBUG_LOC, dl, MVT::Other, Ops, 4);
915          } else {
916            unsigned ID = DW->RecordSourceLine(Line, Col, CU);
917            Result = DAG.getLabel(ISD::DBG_LABEL, dl, Tmp1, ID);
918          }
919        } else {
920          Result = Tmp1;  // chain
921        }
922      } else {
923        Result = Tmp1;  // chain
924      }
925      break;
926    }
927   case TargetLowering::Custom:
928      Result = TLI.LowerOperation(Op, DAG);
929      if (Result.getNode())
930        break;
931    case TargetLowering::Legal: {
932      if (Tmp1 == Node->getOperand(0))
933        break;
934
935      SmallVector<SDValue, 8> Ops;
936      Ops.push_back(Tmp1);
937      Ops.push_back(Node->getOperand(1));  // line # must be legal.
938      Ops.push_back(Node->getOperand(2));  // col # must be legal.
939      Ops.push_back(Node->getOperand(3));  // filename must be legal.
940      Ops.push_back(Node->getOperand(4));  // working dir # must be legal.
941      Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
942      break;
943    }
944    }
945    break;
946  case ISD::FORMAL_ARGUMENTS:
947  case ISD::CALL:
948    // The only option for this is to custom lower it.
949    Tmp3 = TLI.LowerOperation(Result.getValue(0), DAG);
950    assert(Tmp3.getNode() && "Target didn't custom lower this node!");
951    // A call within a calling sequence must be legalized to something
952    // other than the normal CALLSEQ_END.  Violating this gets Legalize
953    // into an infinite loop.
954    assert ((!IsLegalizingCall ||
955             Node->getOpcode() != ISD::CALL ||
956             Tmp3.getNode()->getOpcode() != ISD::CALLSEQ_END) &&
957            "Nested CALLSEQ_START..CALLSEQ_END not supported.");
958
959    // The number of incoming and outgoing values should match; unless the final
960    // outgoing value is a flag.
961    assert((Tmp3.getNode()->getNumValues() == Result.getNode()->getNumValues() ||
962            (Tmp3.getNode()->getNumValues() == Result.getNode()->getNumValues() + 1 &&
963             Tmp3.getNode()->getValueType(Tmp3.getNode()->getNumValues() - 1) ==
964               MVT::Flag)) &&
965           "Lowering call/formal_arguments produced unexpected # results!");
966
967    // Since CALL/FORMAL_ARGUMENTS nodes produce multiple values, make sure to
968    // remember that we legalized all of them, so it doesn't get relegalized.
969    for (unsigned i = 0, e = Tmp3.getNode()->getNumValues(); i != e; ++i) {
970      if (Tmp3.getNode()->getValueType(i) == MVT::Flag)
971        continue;
972      Tmp1 = LegalizeOp(Tmp3.getValue(i));
973      if (Op.getResNo() == i)
974        Tmp2 = Tmp1;
975      AddLegalizedOperand(SDValue(Node, i), Tmp1);
976    }
977    return Tmp2;
978  case ISD::BUILD_VECTOR:
979    switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
980    default: assert(0 && "This action is not supported yet!");
981    case TargetLowering::Custom:
982      Tmp3 = TLI.LowerOperation(Result, DAG);
983      if (Tmp3.getNode()) {
984        Result = Tmp3;
985        break;
986      }
987      // FALLTHROUGH
988    case TargetLowering::Expand:
989      Result = ExpandBUILD_VECTOR(Result.getNode());
990      break;
991    }
992    break;
993  case ISD::CALLSEQ_START: {
994    SDNode *CallEnd = FindCallEndFromCallStart(Node);
995
996    // Recursively Legalize all of the inputs of the call end that do not lead
997    // to this call start.  This ensures that any libcalls that need be inserted
998    // are inserted *before* the CALLSEQ_START.
999    {SmallPtrSet<SDNode*, 32> NodesLeadingTo;
1000    for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
1001      LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).getNode(), Node,
1002                                   NodesLeadingTo);
1003    }
1004
1005    // Now that we legalized all of the inputs (which may have inserted
1006    // libcalls) create the new CALLSEQ_START node.
1007    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1008
1009    // Merge in the last call, to ensure that this call start after the last
1010    // call ended.
1011    if (LastCALLSEQ_END.getOpcode() != ISD::EntryToken) {
1012      Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1013                         Tmp1, LastCALLSEQ_END);
1014      Tmp1 = LegalizeOp(Tmp1);
1015    }
1016
1017    // Do not try to legalize the target-specific arguments (#1+).
1018    if (Tmp1 != Node->getOperand(0)) {
1019      SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1020      Ops[0] = Tmp1;
1021      Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1022    }
1023
1024    // Remember that the CALLSEQ_START is legalized.
1025    AddLegalizedOperand(Op.getValue(0), Result);
1026    if (Node->getNumValues() == 2)    // If this has a flag result, remember it.
1027      AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1028
1029    // Now that the callseq_start and all of the non-call nodes above this call
1030    // sequence have been legalized, legalize the call itself.  During this
1031    // process, no libcalls can/will be inserted, guaranteeing that no calls
1032    // can overlap.
1033    assert(!IsLegalizingCall && "Inconsistent sequentialization of calls!");
1034    // Note that we are selecting this call!
1035    LastCALLSEQ_END = SDValue(CallEnd, 0);
1036    IsLegalizingCall = true;
1037
1038    // Legalize the call, starting from the CALLSEQ_END.
1039    LegalizeOp(LastCALLSEQ_END);
1040    assert(!IsLegalizingCall && "CALLSEQ_END should have cleared this!");
1041    return Result;
1042  }
1043  case ISD::CALLSEQ_END:
1044    // If the CALLSEQ_START node hasn't been legalized first, legalize it.  This
1045    // will cause this node to be legalized as well as handling libcalls right.
1046    if (LastCALLSEQ_END.getNode() != Node) {
1047      LegalizeOp(SDValue(FindCallStartFromCallEnd(Node), 0));
1048      DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
1049      assert(I != LegalizedNodes.end() &&
1050             "Legalizing the call start should have legalized this node!");
1051      return I->second;
1052    }
1053
1054    // Otherwise, the call start has been legalized and everything is going
1055    // according to plan.  Just legalize ourselves normally here.
1056    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1057    // Do not try to legalize the target-specific arguments (#1+), except for
1058    // an optional flag input.
1059    if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Flag){
1060      if (Tmp1 != Node->getOperand(0)) {
1061        SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1062        Ops[0] = Tmp1;
1063        Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1064      }
1065    } else {
1066      Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
1067      if (Tmp1 != Node->getOperand(0) ||
1068          Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
1069        SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1070        Ops[0] = Tmp1;
1071        Ops.back() = Tmp2;
1072        Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1073      }
1074    }
1075    assert(IsLegalizingCall && "Call sequence imbalance between start/end?");
1076    // This finishes up call legalization.
1077    IsLegalizingCall = false;
1078
1079    // If the CALLSEQ_END node has a flag, remember that we legalized it.
1080    AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1081    if (Node->getNumValues() == 2)
1082      AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1083    return Result.getValue(Op.getResNo());
1084  case ISD::DYNAMIC_STACKALLOC: {
1085    MVT VT = Node->getValueType(0);
1086    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1087    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
1088    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
1089    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1090
1091    Tmp1 = Result.getValue(0);
1092    Tmp2 = Result.getValue(1);
1093    switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1094    default: assert(0 && "This action is not supported yet!");
1095    case TargetLowering::Expand: {
1096      unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1097      assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1098             " not tell us which reg is the stack pointer!");
1099      SDValue Chain = Tmp1.getOperand(0);
1100
1101      // Chain the dynamic stack allocation so that it doesn't modify the stack
1102      // pointer when other instructions are using the stack.
1103      Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
1104
1105      SDValue Size  = Tmp2.getOperand(1);
1106      SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
1107      Chain = SP.getValue(1);
1108      unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
1109      unsigned StackAlign =
1110        TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1111      if (Align > StackAlign)
1112        SP = DAG.getNode(ISD::AND, dl, VT, SP,
1113                         DAG.getConstant(-(uint64_t)Align, VT));
1114      Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size);       // Value
1115      Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);     // Output chain
1116
1117      Tmp2 = DAG.getCALLSEQ_END(Chain,  DAG.getIntPtrConstant(0, true),
1118                                DAG.getIntPtrConstant(0, true), SDValue());
1119
1120      Tmp1 = LegalizeOp(Tmp1);
1121      Tmp2 = LegalizeOp(Tmp2);
1122      break;
1123    }
1124    case TargetLowering::Custom:
1125      Tmp3 = TLI.LowerOperation(Tmp1, DAG);
1126      if (Tmp3.getNode()) {
1127        Tmp1 = LegalizeOp(Tmp3);
1128        Tmp2 = LegalizeOp(Tmp3.getValue(1));
1129      }
1130      break;
1131    case TargetLowering::Legal:
1132      break;
1133    }
1134    // Since this op produce two values, make sure to remember that we
1135    // legalized both of them.
1136    AddLegalizedOperand(SDValue(Node, 0), Tmp1);
1137    AddLegalizedOperand(SDValue(Node, 1), Tmp2);
1138    return Op.getResNo() ? Tmp2 : Tmp1;
1139  }
1140  case ISD::BR_JT:
1141    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1142    // Ensure that libcalls are emitted before a branch.
1143    Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Tmp1, LastCALLSEQ_END);
1144    Tmp1 = LegalizeOp(Tmp1);
1145    LastCALLSEQ_END = DAG.getEntryNode();
1146
1147    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the jumptable node.
1148    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1149
1150    switch (TLI.getOperationAction(ISD::BR_JT, MVT::Other)) {
1151    default: assert(0 && "This action is not supported yet!");
1152    case TargetLowering::Legal: break;
1153    case TargetLowering::Custom:
1154      Tmp1 = TLI.LowerOperation(Result, DAG);
1155      if (Tmp1.getNode()) Result = Tmp1;
1156      break;
1157    case TargetLowering::Expand: {
1158      SDValue Chain = Result.getOperand(0);
1159      SDValue Table = Result.getOperand(1);
1160      SDValue Index = Result.getOperand(2);
1161
1162      MVT PTy = TLI.getPointerTy();
1163      MachineFunction &MF = DAG.getMachineFunction();
1164      unsigned EntrySize = MF.getJumpTableInfo()->getEntrySize();
1165      Index= DAG.getNode(ISD::MUL, dl, PTy,
1166                         Index, DAG.getConstant(EntrySize, PTy));
1167      SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
1168
1169      MVT MemVT = MVT::getIntegerVT(EntrySize * 8);
1170      SDValue LD = DAG.getExtLoad(ISD::SEXTLOAD, dl, PTy, Chain, Addr,
1171                                  PseudoSourceValue::getJumpTable(), 0, MemVT);
1172      Addr = LD;
1173      if (TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1174        // For PIC, the sequence is:
1175        // BRIND(load(Jumptable + index) + RelocBase)
1176        // RelocBase can be JumpTable, GOT or some sort of global base.
1177        Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr,
1178                           TLI.getPICJumpTableRelocBase(Table, DAG));
1179      }
1180      Result = DAG.getNode(ISD::BRIND, dl, MVT::Other, LD.getValue(1), Addr);
1181    }
1182    }
1183    break;
1184  case ISD::BR_CC:
1185    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1186    // Ensure that libcalls are emitted before a branch.
1187    Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Tmp1, LastCALLSEQ_END);
1188    Tmp1 = LegalizeOp(Tmp1);
1189    Tmp2 = Node->getOperand(2);              // LHS
1190    Tmp3 = Node->getOperand(3);              // RHS
1191    Tmp4 = Node->getOperand(1);              // CC
1192
1193    LegalizeSetCC(TLI.getSetCCResultType(Tmp2.getValueType()),
1194                  Tmp2, Tmp3, Tmp4, dl);
1195    LastCALLSEQ_END = DAG.getEntryNode();
1196
1197    // If we didn't get both a LHS and RHS back from LegalizeSetCC,
1198    // the LHS is a legal SETCC itself.  In this case, we need to compare
1199    // the result against zero to select between true and false values.
1200    if (Tmp3.getNode() == 0) {
1201      Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
1202      Tmp4 = DAG.getCondCode(ISD::SETNE);
1203    }
1204
1205    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp4, Tmp2, Tmp3,
1206                                    Node->getOperand(4));
1207
1208    switch (TLI.getOperationAction(ISD::BR_CC, Tmp3.getValueType())) {
1209    default: assert(0 && "Unexpected action for BR_CC!");
1210    case TargetLowering::Legal: break;
1211    case TargetLowering::Custom:
1212      Tmp4 = TLI.LowerOperation(Result, DAG);
1213      if (Tmp4.getNode()) Result = Tmp4;
1214      break;
1215    }
1216    break;
1217  case ISD::LOAD: {
1218    LoadSDNode *LD = cast<LoadSDNode>(Node);
1219    Tmp1 = LegalizeOp(LD->getChain());   // Legalize the chain.
1220    Tmp2 = LegalizeOp(LD->getBasePtr()); // Legalize the base pointer.
1221
1222    ISD::LoadExtType ExtType = LD->getExtensionType();
1223    if (ExtType == ISD::NON_EXTLOAD) {
1224      MVT VT = Node->getValueType(0);
1225      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
1226      Tmp3 = Result.getValue(0);
1227      Tmp4 = Result.getValue(1);
1228
1229      switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1230      default: assert(0 && "This action is not supported yet!");
1231      case TargetLowering::Legal:
1232        // If this is an unaligned load and the target doesn't support it,
1233        // expand it.
1234        if (!TLI.allowsUnalignedMemoryAccesses()) {
1235          unsigned ABIAlignment = TLI.getTargetData()->
1236            getABITypeAlignment(LD->getMemoryVT().getTypeForMVT());
1237          if (LD->getAlignment() < ABIAlignment){
1238            Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()), DAG,
1239                                         TLI);
1240            Tmp3 = Result.getOperand(0);
1241            Tmp4 = Result.getOperand(1);
1242            Tmp3 = LegalizeOp(Tmp3);
1243            Tmp4 = LegalizeOp(Tmp4);
1244          }
1245        }
1246        break;
1247      case TargetLowering::Custom:
1248        Tmp1 = TLI.LowerOperation(Tmp3, DAG);
1249        if (Tmp1.getNode()) {
1250          Tmp3 = LegalizeOp(Tmp1);
1251          Tmp4 = LegalizeOp(Tmp1.getValue(1));
1252        }
1253        break;
1254      case TargetLowering::Promote: {
1255        // Only promote a load of vector type to another.
1256        assert(VT.isVector() && "Cannot promote this load!");
1257        // Change base type to a different vector type.
1258        MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
1259
1260        Tmp1 = DAG.getLoad(NVT, dl, Tmp1, Tmp2, LD->getSrcValue(),
1261                           LD->getSrcValueOffset(),
1262                           LD->isVolatile(), LD->getAlignment());
1263        Tmp3 = LegalizeOp(DAG.getNode(ISD::BIT_CONVERT, dl, VT, Tmp1));
1264        Tmp4 = LegalizeOp(Tmp1.getValue(1));
1265        break;
1266      }
1267      }
1268      // Since loads produce two values, make sure to remember that we
1269      // legalized both of them.
1270      AddLegalizedOperand(SDValue(Node, 0), Tmp3);
1271      AddLegalizedOperand(SDValue(Node, 1), Tmp4);
1272      return Op.getResNo() ? Tmp4 : Tmp3;
1273    } else {
1274      MVT SrcVT = LD->getMemoryVT();
1275      unsigned SrcWidth = SrcVT.getSizeInBits();
1276      int SVOffset = LD->getSrcValueOffset();
1277      unsigned Alignment = LD->getAlignment();
1278      bool isVolatile = LD->isVolatile();
1279
1280      if (SrcWidth != SrcVT.getStoreSizeInBits() &&
1281          // Some targets pretend to have an i1 loading operation, and actually
1282          // load an i8.  This trick is correct for ZEXTLOAD because the top 7
1283          // bits are guaranteed to be zero; it helps the optimizers understand
1284          // that these bits are zero.  It is also useful for EXTLOAD, since it
1285          // tells the optimizers that those bits are undefined.  It would be
1286          // nice to have an effective generic way of getting these benefits...
1287          // Until such a way is found, don't insist on promoting i1 here.
1288          (SrcVT != MVT::i1 ||
1289           TLI.getLoadExtAction(ExtType, MVT::i1) == TargetLowering::Promote)) {
1290        // Promote to a byte-sized load if not loading an integral number of
1291        // bytes.  For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
1292        unsigned NewWidth = SrcVT.getStoreSizeInBits();
1293        MVT NVT = MVT::getIntegerVT(NewWidth);
1294        SDValue Ch;
1295
1296        // The extra bits are guaranteed to be zero, since we stored them that
1297        // way.  A zext load from NVT thus automatically gives zext from SrcVT.
1298
1299        ISD::LoadExtType NewExtType =
1300          ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
1301
1302        Result = DAG.getExtLoad(NewExtType, dl, Node->getValueType(0),
1303                                Tmp1, Tmp2, LD->getSrcValue(), SVOffset,
1304                                NVT, isVolatile, Alignment);
1305
1306        Ch = Result.getValue(1); // The chain.
1307
1308        if (ExtType == ISD::SEXTLOAD)
1309          // Having the top bits zero doesn't help when sign extending.
1310          Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
1311                               Result.getValueType(),
1312                               Result, DAG.getValueType(SrcVT));
1313        else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
1314          // All the top bits are guaranteed to be zero - inform the optimizers.
1315          Result = DAG.getNode(ISD::AssertZext, dl,
1316                               Result.getValueType(), Result,
1317                               DAG.getValueType(SrcVT));
1318
1319        Tmp1 = LegalizeOp(Result);
1320        Tmp2 = LegalizeOp(Ch);
1321      } else if (SrcWidth & (SrcWidth - 1)) {
1322        // If not loading a power-of-2 number of bits, expand as two loads.
1323        assert(SrcVT.isExtended() && !SrcVT.isVector() &&
1324               "Unsupported extload!");
1325        unsigned RoundWidth = 1 << Log2_32(SrcWidth);
1326        assert(RoundWidth < SrcWidth);
1327        unsigned ExtraWidth = SrcWidth - RoundWidth;
1328        assert(ExtraWidth < RoundWidth);
1329        assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
1330               "Load size not an integral number of bytes!");
1331        MVT RoundVT = MVT::getIntegerVT(RoundWidth);
1332        MVT ExtraVT = MVT::getIntegerVT(ExtraWidth);
1333        SDValue Lo, Hi, Ch;
1334        unsigned IncrementSize;
1335
1336        if (TLI.isLittleEndian()) {
1337          // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
1338          // Load the bottom RoundWidth bits.
1339          Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl,
1340                              Node->getValueType(0), Tmp1, Tmp2,
1341                              LD->getSrcValue(), SVOffset, RoundVT, isVolatile,
1342                              Alignment);
1343
1344          // Load the remaining ExtraWidth bits.
1345          IncrementSize = RoundWidth / 8;
1346          Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1347                             DAG.getIntPtrConstant(IncrementSize));
1348          Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Tmp1, Tmp2,
1349                              LD->getSrcValue(), SVOffset + IncrementSize,
1350                              ExtraVT, isVolatile,
1351                              MinAlign(Alignment, IncrementSize));
1352
1353          // Build a factor node to remember that this load is independent of the
1354          // other one.
1355          Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1356                           Hi.getValue(1));
1357
1358          // Move the top bits to the right place.
1359          Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1360                           DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
1361
1362          // Join the hi and lo parts.
1363          Result = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1364        } else {
1365          // Big endian - avoid unaligned loads.
1366          // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
1367          // Load the top RoundWidth bits.
1368          Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Tmp1, Tmp2,
1369                              LD->getSrcValue(), SVOffset, RoundVT, isVolatile,
1370                              Alignment);
1371
1372          // Load the remaining ExtraWidth bits.
1373          IncrementSize = RoundWidth / 8;
1374          Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1375                             DAG.getIntPtrConstant(IncrementSize));
1376          Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl,
1377                              Node->getValueType(0), Tmp1, Tmp2,
1378                              LD->getSrcValue(), SVOffset + IncrementSize,
1379                              ExtraVT, isVolatile,
1380                              MinAlign(Alignment, IncrementSize));
1381
1382          // Build a factor node to remember that this load is independent of the
1383          // other one.
1384          Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1385                           Hi.getValue(1));
1386
1387          // Move the top bits to the right place.
1388          Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1389                           DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
1390
1391          // Join the hi and lo parts.
1392          Result = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1393        }
1394
1395        Tmp1 = LegalizeOp(Result);
1396        Tmp2 = LegalizeOp(Ch);
1397      } else {
1398        switch (TLI.getLoadExtAction(ExtType, SrcVT)) {
1399        default: assert(0 && "This action is not supported yet!");
1400        case TargetLowering::Custom:
1401          isCustom = true;
1402          // FALLTHROUGH
1403        case TargetLowering::Legal:
1404          Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
1405          Tmp1 = Result.getValue(0);
1406          Tmp2 = Result.getValue(1);
1407
1408          if (isCustom) {
1409            Tmp3 = TLI.LowerOperation(Result, DAG);
1410            if (Tmp3.getNode()) {
1411              Tmp1 = LegalizeOp(Tmp3);
1412              Tmp2 = LegalizeOp(Tmp3.getValue(1));
1413            }
1414          } else {
1415            // If this is an unaligned load and the target doesn't support it,
1416            // expand it.
1417            if (!TLI.allowsUnalignedMemoryAccesses()) {
1418              unsigned ABIAlignment = TLI.getTargetData()->
1419                getABITypeAlignment(LD->getMemoryVT().getTypeForMVT());
1420              if (LD->getAlignment() < ABIAlignment){
1421                Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()), DAG,
1422                                             TLI);
1423                Tmp1 = Result.getOperand(0);
1424                Tmp2 = Result.getOperand(1);
1425                Tmp1 = LegalizeOp(Tmp1);
1426                Tmp2 = LegalizeOp(Tmp2);
1427              }
1428            }
1429          }
1430          break;
1431        case TargetLowering::Expand:
1432          // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
1433          if (SrcVT == MVT::f32 && Node->getValueType(0) == MVT::f64) {
1434            SDValue Load = DAG.getLoad(SrcVT, dl, Tmp1, Tmp2, LD->getSrcValue(),
1435                                         LD->getSrcValueOffset(),
1436                                         LD->isVolatile(), LD->getAlignment());
1437            Result = DAG.getNode(ISD::FP_EXTEND, dl,
1438                                 Node->getValueType(0), Load);
1439            Tmp1 = LegalizeOp(Result);  // Relegalize new nodes.
1440            Tmp2 = LegalizeOp(Load.getValue(1));
1441            break;
1442          }
1443          assert(ExtType != ISD::EXTLOAD &&"EXTLOAD should always be supported!");
1444          // Turn the unsupported load into an EXTLOAD followed by an explicit
1445          // zero/sign extend inreg.
1446          Result = DAG.getExtLoad(ISD::EXTLOAD, dl, Node->getValueType(0),
1447                                  Tmp1, Tmp2, LD->getSrcValue(),
1448                                  LD->getSrcValueOffset(), SrcVT,
1449                                  LD->isVolatile(), LD->getAlignment());
1450          SDValue ValRes;
1451          if (ExtType == ISD::SEXTLOAD)
1452            ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
1453                                 Result.getValueType(),
1454                                 Result, DAG.getValueType(SrcVT));
1455          else
1456            ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT);
1457          Tmp1 = LegalizeOp(ValRes);  // Relegalize new nodes.
1458          Tmp2 = LegalizeOp(Result.getValue(1));  // Relegalize new nodes.
1459          break;
1460        }
1461      }
1462
1463      // Since loads produce two values, make sure to remember that we legalized
1464      // both of them.
1465      AddLegalizedOperand(SDValue(Node, 0), Tmp1);
1466      AddLegalizedOperand(SDValue(Node, 1), Tmp2);
1467      return Op.getResNo() ? Tmp2 : Tmp1;
1468    }
1469  }
1470  case ISD::STORE: {
1471    StoreSDNode *ST = cast<StoreSDNode>(Node);
1472    Tmp1 = LegalizeOp(ST->getChain());    // Legalize the chain.
1473    Tmp2 = LegalizeOp(ST->getBasePtr());  // Legalize the pointer.
1474    int SVOffset = ST->getSrcValueOffset();
1475    unsigned Alignment = ST->getAlignment();
1476    bool isVolatile = ST->isVolatile();
1477
1478    if (!ST->isTruncatingStore()) {
1479      // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
1480      // FIXME: We shouldn't do this for TargetConstantFP's.
1481      // FIXME: move this to the DAG Combiner!  Note that we can't regress due
1482      // to phase ordering between legalized code and the dag combiner.  This
1483      // probably means that we need to integrate dag combiner and legalizer
1484      // together.
1485      // We generally can't do this one for long doubles.
1486      if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
1487        if (CFP->getValueType(0) == MVT::f32 &&
1488            getTypeAction(MVT::i32) == Legal) {
1489          Tmp3 = DAG.getConstant(CFP->getValueAPF().
1490                                          bitcastToAPInt().zextOrTrunc(32),
1491                                  MVT::i32);
1492          Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
1493                                SVOffset, isVolatile, Alignment);
1494          break;
1495        } else if (CFP->getValueType(0) == MVT::f64) {
1496          // If this target supports 64-bit registers, do a single 64-bit store.
1497          if (getTypeAction(MVT::i64) == Legal) {
1498            Tmp3 = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
1499                                     zextOrTrunc(64), MVT::i64);
1500            Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
1501                                  SVOffset, isVolatile, Alignment);
1502            break;
1503          } else if (getTypeAction(MVT::i32) == Legal && !ST->isVolatile()) {
1504            // Otherwise, if the target supports 32-bit registers, use 2 32-bit
1505            // stores.  If the target supports neither 32- nor 64-bits, this
1506            // xform is certainly not worth it.
1507            const APInt &IntVal =CFP->getValueAPF().bitcastToAPInt();
1508            SDValue Lo = DAG.getConstant(APInt(IntVal).trunc(32), MVT::i32);
1509            SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), MVT::i32);
1510            if (TLI.isBigEndian()) std::swap(Lo, Hi);
1511
1512            Lo = DAG.getStore(Tmp1, dl, Lo, Tmp2, ST->getSrcValue(),
1513                              SVOffset, isVolatile, Alignment);
1514            Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1515                               DAG.getIntPtrConstant(4));
1516            Hi = DAG.getStore(Tmp1, dl, Hi, Tmp2, ST->getSrcValue(), SVOffset+4,
1517                              isVolatile, MinAlign(Alignment, 4U));
1518
1519            Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
1520            break;
1521          }
1522        }
1523      }
1524
1525      {
1526        Tmp3 = LegalizeOp(ST->getValue());
1527        Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
1528                                        ST->getOffset());
1529
1530        MVT VT = Tmp3.getValueType();
1531        switch (TLI.getOperationAction(ISD::STORE, VT)) {
1532        default: assert(0 && "This action is not supported yet!");
1533        case TargetLowering::Legal:
1534          // If this is an unaligned store and the target doesn't support it,
1535          // expand it.
1536          if (!TLI.allowsUnalignedMemoryAccesses()) {
1537            unsigned ABIAlignment = TLI.getTargetData()->
1538              getABITypeAlignment(ST->getMemoryVT().getTypeForMVT());
1539            if (ST->getAlignment() < ABIAlignment)
1540              Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()), DAG,
1541                                            TLI);
1542          }
1543          break;
1544        case TargetLowering::Custom:
1545          Tmp1 = TLI.LowerOperation(Result, DAG);
1546          if (Tmp1.getNode()) Result = Tmp1;
1547          break;
1548        case TargetLowering::Promote:
1549          assert(VT.isVector() && "Unknown legal promote case!");
1550          Tmp3 = DAG.getNode(ISD::BIT_CONVERT, dl,
1551                             TLI.getTypeToPromoteTo(ISD::STORE, VT), Tmp3);
1552          Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2,
1553                                ST->getSrcValue(), SVOffset, isVolatile,
1554                                Alignment);
1555          break;
1556        }
1557        break;
1558      }
1559    } else {
1560      Tmp3 = LegalizeOp(ST->getValue());
1561
1562      MVT StVT = ST->getMemoryVT();
1563      unsigned StWidth = StVT.getSizeInBits();
1564
1565      if (StWidth != StVT.getStoreSizeInBits()) {
1566        // Promote to a byte-sized store with upper bits zero if not
1567        // storing an integral number of bytes.  For example, promote
1568        // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
1569        MVT NVT = MVT::getIntegerVT(StVT.getStoreSizeInBits());
1570        Tmp3 = DAG.getZeroExtendInReg(Tmp3, dl, StVT);
1571        Result = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
1572                                   SVOffset, NVT, isVolatile, Alignment);
1573      } else if (StWidth & (StWidth - 1)) {
1574        // If not storing a power-of-2 number of bits, expand as two stores.
1575        assert(StVT.isExtended() && !StVT.isVector() &&
1576               "Unsupported truncstore!");
1577        unsigned RoundWidth = 1 << Log2_32(StWidth);
1578        assert(RoundWidth < StWidth);
1579        unsigned ExtraWidth = StWidth - RoundWidth;
1580        assert(ExtraWidth < RoundWidth);
1581        assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
1582               "Store size not an integral number of bytes!");
1583        MVT RoundVT = MVT::getIntegerVT(RoundWidth);
1584        MVT ExtraVT = MVT::getIntegerVT(ExtraWidth);
1585        SDValue Lo, Hi;
1586        unsigned IncrementSize;
1587
1588        if (TLI.isLittleEndian()) {
1589          // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
1590          // Store the bottom RoundWidth bits.
1591          Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
1592                                 SVOffset, RoundVT,
1593                                 isVolatile, Alignment);
1594
1595          // Store the remaining ExtraWidth bits.
1596          IncrementSize = RoundWidth / 8;
1597          Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1598                             DAG.getIntPtrConstant(IncrementSize));
1599          Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
1600                           DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
1601          Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2, ST->getSrcValue(),
1602                                 SVOffset + IncrementSize, ExtraVT, isVolatile,
1603                                 MinAlign(Alignment, IncrementSize));
1604        } else {
1605          // Big endian - avoid unaligned stores.
1606          // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
1607          // Store the top RoundWidth bits.
1608          Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
1609                           DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
1610          Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2, ST->getSrcValue(),
1611                                 SVOffset, RoundVT, isVolatile, Alignment);
1612
1613          // Store the remaining ExtraWidth bits.
1614          IncrementSize = RoundWidth / 8;
1615          Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1616                             DAG.getIntPtrConstant(IncrementSize));
1617          Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
1618                                 SVOffset + IncrementSize, ExtraVT, isVolatile,
1619                                 MinAlign(Alignment, IncrementSize));
1620        }
1621
1622        // The order of the stores doesn't matter.
1623        Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
1624      } else {
1625        if (Tmp1 != ST->getChain() || Tmp3 != ST->getValue() ||
1626            Tmp2 != ST->getBasePtr())
1627          Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
1628                                          ST->getOffset());
1629
1630        switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) {
1631        default: assert(0 && "This action is not supported yet!");
1632        case TargetLowering::Legal:
1633          // If this is an unaligned store and the target doesn't support it,
1634          // expand it.
1635          if (!TLI.allowsUnalignedMemoryAccesses()) {
1636            unsigned ABIAlignment = TLI.getTargetData()->
1637              getABITypeAlignment(ST->getMemoryVT().getTypeForMVT());
1638            if (ST->getAlignment() < ABIAlignment)
1639              Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()), DAG,
1640                                            TLI);
1641          }
1642          break;
1643        case TargetLowering::Custom:
1644          Result = TLI.LowerOperation(Result, DAG);
1645          break;
1646        case Expand:
1647          // TRUNCSTORE:i16 i32 -> STORE i16
1648          assert(isTypeLegal(StVT) && "Do not know how to expand this store!");
1649          Tmp3 = DAG.getNode(ISD::TRUNCATE, dl, StVT, Tmp3);
1650          Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
1651                                SVOffset, isVolatile, Alignment);
1652          break;
1653        }
1654      }
1655    }
1656    break;
1657  }
1658  case ISD::SELECT_CC: {
1659    Tmp1 = Node->getOperand(0);               // LHS
1660    Tmp2 = Node->getOperand(1);               // RHS
1661    Tmp3 = LegalizeOp(Node->getOperand(2));   // True
1662    Tmp4 = LegalizeOp(Node->getOperand(3));   // False
1663    SDValue CC = Node->getOperand(4);
1664
1665    LegalizeSetCC(TLI.getSetCCResultType(Tmp1.getValueType()),
1666                  Tmp1, Tmp2, CC, dl);
1667
1668    // If we didn't get both a LHS and RHS back from LegalizeSetCC,
1669    // the LHS is a legal SETCC itself.  In this case, we need to compare
1670    // the result against zero to select between true and false values.
1671    if (Tmp2.getNode() == 0) {
1672      Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
1673      CC = DAG.getCondCode(ISD::SETNE);
1674    }
1675    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4, CC);
1676
1677    // Everything is legal, see if we should expand this op or something.
1678    switch (TLI.getOperationAction(ISD::SELECT_CC, Tmp3.getValueType())) {
1679    default: assert(0 && "This action is not supported yet!");
1680    case TargetLowering::Legal: break;
1681    case TargetLowering::Custom:
1682      Tmp1 = TLI.LowerOperation(Result, DAG);
1683      if (Tmp1.getNode()) Result = Tmp1;
1684      break;
1685    }
1686    break;
1687  }
1688  case ISD::SETCC:
1689    Tmp1 = Node->getOperand(0);
1690    Tmp2 = Node->getOperand(1);
1691    Tmp3 = Node->getOperand(2);
1692    LegalizeSetCC(Node->getValueType(0), Tmp1, Tmp2, Tmp3, dl);
1693
1694    // If we had to Expand the SetCC operands into a SELECT node, then it may
1695    // not always be possible to return a true LHS & RHS.  In this case, just
1696    // return the value we legalized, returned in the LHS
1697    if (Tmp2.getNode() == 0) {
1698      Result = Tmp1;
1699      break;
1700    }
1701
1702    switch (TLI.getOperationAction(ISD::SETCC, Tmp1.getValueType())) {
1703    default: assert(0 && "Cannot handle this action for SETCC yet!");
1704    case TargetLowering::Custom:
1705      isCustom = true;
1706      // FALLTHROUGH.
1707    case TargetLowering::Legal:
1708      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1709      if (isCustom) {
1710        Tmp4 = TLI.LowerOperation(Result, DAG);
1711        if (Tmp4.getNode()) Result = Tmp4;
1712      }
1713      break;
1714    case TargetLowering::Promote: {
1715      // First step, figure out the appropriate operation to use.
1716      // Allow SETCC to not be supported for all legal data types
1717      // Mostly this targets FP
1718      MVT NewInTy = Node->getOperand(0).getValueType();
1719      MVT OldVT = NewInTy; OldVT = OldVT;
1720
1721      // Scan for the appropriate larger type to use.
1722      while (1) {
1723        NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT()+1);
1724
1725        assert(NewInTy.isInteger() == OldVT.isInteger() &&
1726               "Fell off of the edge of the integer world");
1727        assert(NewInTy.isFloatingPoint() == OldVT.isFloatingPoint() &&
1728               "Fell off of the edge of the floating point world");
1729
1730        // If the target supports SETCC of this type, use it.
1731        if (TLI.isOperationLegalOrCustom(ISD::SETCC, NewInTy))
1732          break;
1733      }
1734      if (NewInTy.isInteger())
1735        assert(0 && "Cannot promote Legal Integer SETCC yet");
1736      else {
1737        Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NewInTy, Tmp1);
1738        Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NewInTy, Tmp2);
1739      }
1740      Tmp1 = LegalizeOp(Tmp1);
1741      Tmp2 = LegalizeOp(Tmp2);
1742      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1743      Result = LegalizeOp(Result);
1744      break;
1745    }
1746    case TargetLowering::Expand:
1747      // Expand a setcc node into a select_cc of the same condition, lhs, and
1748      // rhs that selects between const 1 (true) and const 0 (false).
1749      MVT VT = Node->getValueType(0);
1750      Result = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
1751                           DAG.getConstant(1, VT), DAG.getConstant(0, VT),
1752                           Tmp3);
1753      break;
1754    }
1755    break;
1756
1757    // Binary operators
1758  case ISD::FCOPYSIGN:  // FCOPYSIGN does not require LHS/RHS to match type!
1759    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
1760    Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
1761
1762    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1763
1764    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1765    default: assert(0 && "Operation not supported");
1766    case TargetLowering::Custom:
1767      Tmp1 = TLI.LowerOperation(Result, DAG);
1768      if (Tmp1.getNode()) Result = Tmp1;
1769      break;
1770    case TargetLowering::Legal: break;
1771    case TargetLowering::Expand: {
1772      assert((Tmp2.getValueType() == MVT::f32 ||
1773              Tmp2.getValueType() == MVT::f64) &&
1774              "Ugly special-cased code!");
1775      // Get the sign bit of the RHS.
1776      SDValue SignBit;
1777      MVT IVT = Tmp2.getValueType() == MVT::f64 ? MVT::i64 : MVT::i32;
1778      if (isTypeLegal(IVT)) {
1779        SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, IVT, Tmp2);
1780      } else {
1781        assert(isTypeLegal(TLI.getPointerTy()) &&
1782               (TLI.getPointerTy() == MVT::i32 ||
1783                TLI.getPointerTy() == MVT::i64) &&
1784               "Legal type for load?!");
1785        SDValue StackPtr = DAG.CreateStackTemporary(Tmp2.getValueType());
1786        SDValue StorePtr = StackPtr, LoadPtr = StackPtr;
1787        SDValue Ch =
1788            DAG.getStore(DAG.getEntryNode(), dl, Tmp2, StorePtr, NULL, 0);
1789        if (Tmp2.getValueType() == MVT::f64 && TLI.isLittleEndian())
1790          LoadPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(),
1791                                LoadPtr, DAG.getIntPtrConstant(4));
1792        SignBit = DAG.getExtLoad(ISD::SEXTLOAD, dl, TLI.getPointerTy(),
1793                                 Ch, LoadPtr, NULL, 0, MVT::i32);
1794      }
1795      SignBit =
1796          DAG.getSetCC(dl, TLI.getSetCCResultType(SignBit.getValueType()),
1797                       SignBit, DAG.getConstant(0, SignBit.getValueType()),
1798                       ISD::SETLT);
1799      // Get the absolute value of the result.
1800      SDValue AbsVal = DAG.getNode(ISD::FABS, dl, Tmp1.getValueType(), Tmp1);
1801      // Select between the nabs and abs value based on the sign bit of
1802      // the input.
1803      Result = DAG.getNode(ISD::SELECT, dl, AbsVal.getValueType(), SignBit,
1804                           DAG.getNode(ISD::FNEG, dl, AbsVal.getValueType(),
1805                                       AbsVal),
1806                           AbsVal);
1807      Result = LegalizeOp(Result);
1808      break;
1809    }
1810    }
1811    break;
1812  case ISD::SADDO:
1813  case ISD::SSUBO: {
1814    MVT VT = Node->getValueType(0);
1815    switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1816    default: assert(0 && "This action not supported for this op yet!");
1817    case TargetLowering::Custom:
1818      Result = TLI.LowerOperation(Op, DAG);
1819      if (Result.getNode()) break;
1820      // FALLTHROUGH
1821    case TargetLowering::Legal: {
1822      SDValue LHS = LegalizeOp(Node->getOperand(0));
1823      SDValue RHS = LegalizeOp(Node->getOperand(1));
1824
1825      SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
1826                                ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
1827                                LHS, RHS);
1828      MVT OType = Node->getValueType(1);
1829
1830      SDValue Zero = DAG.getConstant(0, LHS.getValueType());
1831
1832      //   LHSSign -> LHS >= 0
1833      //   RHSSign -> RHS >= 0
1834      //   SumSign -> Sum >= 0
1835      //
1836      //   Add:
1837      //   Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
1838      //   Sub:
1839      //   Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
1840      //
1841      SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
1842      SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
1843      SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
1844                                        Node->getOpcode() == ISD::SADDO ?
1845                                        ISD::SETEQ : ISD::SETNE);
1846
1847      SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
1848      SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
1849
1850      SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
1851
1852      MVT ValueVTs[] = { LHS.getValueType(), OType };
1853      SDValue Ops[] = { Sum, Cmp };
1854
1855      Result = DAG.getNode(ISD::MERGE_VALUES, dl,
1856                           DAG.getVTList(&ValueVTs[0], 2),
1857                           &Ops[0], 2);
1858      SDNode *RNode = Result.getNode();
1859      DAG.ReplaceAllUsesWith(Node, RNode);
1860      break;
1861    }
1862    }
1863
1864    break;
1865  }
1866  case ISD::UADDO:
1867  case ISD::USUBO: {
1868    MVT VT = Node->getValueType(0);
1869    switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1870    default: assert(0 && "This action not supported for this op yet!");
1871    case TargetLowering::Custom:
1872      Result = TLI.LowerOperation(Op, DAG);
1873      if (Result.getNode()) break;
1874      // FALLTHROUGH
1875    case TargetLowering::Legal: {
1876      SDValue LHS = LegalizeOp(Node->getOperand(0));
1877      SDValue RHS = LegalizeOp(Node->getOperand(1));
1878
1879      SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::UADDO ?
1880                                ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
1881                                LHS, RHS);
1882      MVT OType = Node->getValueType(1);
1883      SDValue Cmp = DAG.getSetCC(dl, OType, Sum, LHS,
1884                                 Node->getOpcode () == ISD::UADDO ?
1885                                 ISD::SETULT : ISD::SETUGT);
1886
1887      MVT ValueVTs[] = { LHS.getValueType(), OType };
1888      SDValue Ops[] = { Sum, Cmp };
1889
1890      Result = DAG.getNode(ISD::MERGE_VALUES, dl,
1891                           DAG.getVTList(&ValueVTs[0], 2),
1892                           &Ops[0], 2);
1893      SDNode *RNode = Result.getNode();
1894      DAG.ReplaceAllUsesWith(Node, RNode);
1895      break;
1896    }
1897    }
1898
1899    break;
1900  }
1901  }
1902
1903  assert(Result.getValueType() == Op.getValueType() &&
1904         "Bad legalization!");
1905
1906  // Make sure that the generated code is itself legal.
1907  if (Result != Op)
1908    Result = LegalizeOp(Result);
1909
1910  // Note that LegalizeOp may be reentered even from single-use nodes, which
1911  // means that we always must cache transformed nodes.
1912  AddLegalizedOperand(Op, Result);
1913  return Result;
1914}
1915
1916SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
1917  SDValue Vec = Op.getOperand(0);
1918  SDValue Idx = Op.getOperand(1);
1919  DebugLoc dl = Op.getDebugLoc();
1920  // Store the value to a temporary stack slot, then LOAD the returned part.
1921  SDValue StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
1922  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, NULL, 0);
1923
1924  // Add the offset to the index.
1925  unsigned EltSize =
1926      Vec.getValueType().getVectorElementType().getSizeInBits()/8;
1927  Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
1928                    DAG.getConstant(EltSize, Idx.getValueType()));
1929
1930  if (Idx.getValueType().bitsGT(TLI.getPointerTy()))
1931    Idx = DAG.getNode(ISD::TRUNCATE, dl, TLI.getPointerTy(), Idx);
1932  else
1933    Idx = DAG.getNode(ISD::ZERO_EXTEND, dl, TLI.getPointerTy(), Idx);
1934
1935  StackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx, StackPtr);
1936
1937  return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, NULL, 0);
1938}
1939
1940/// LegalizeSetCCOperands - Attempts to create a legal LHS and RHS for a SETCC
1941/// with condition CC on the current target.  This usually involves legalizing
1942/// or promoting the arguments.  In the case where LHS and RHS must be expanded,
1943/// there may be no choice but to create a new SetCC node to represent the
1944/// legalized value of setcc lhs, rhs.  In this case, the value is returned in
1945/// LHS, and the SDValue returned in RHS has a nil SDNode value.
1946void SelectionDAGLegalize::LegalizeSetCCOperands(SDValue &LHS,
1947                                                 SDValue &RHS,
1948                                                 SDValue &CC,
1949                                                 DebugLoc dl) {
1950  LHS = LegalizeOp(LHS);
1951  RHS = LegalizeOp(RHS);
1952}
1953
1954/// LegalizeSetCCCondCode - Legalize a SETCC with given LHS and RHS and
1955/// condition code CC on the current target. This routine assumes LHS and rHS
1956/// have already been legalized by LegalizeSetCCOperands. It expands SETCC with
1957/// illegal condition code into AND / OR of multiple SETCC values.
1958void SelectionDAGLegalize::LegalizeSetCCCondCode(MVT VT,
1959                                                 SDValue &LHS, SDValue &RHS,
1960                                                 SDValue &CC,
1961                                                 DebugLoc dl) {
1962  MVT OpVT = LHS.getValueType();
1963  ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
1964  switch (TLI.getCondCodeAction(CCCode, OpVT)) {
1965  default: assert(0 && "Unknown condition code action!");
1966  case TargetLowering::Legal:
1967    // Nothing to do.
1968    break;
1969  case TargetLowering::Expand: {
1970    ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
1971    unsigned Opc = 0;
1972    switch (CCCode) {
1973    default: assert(0 && "Don't know how to expand this condition!"); abort();
1974    case ISD::SETOEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1975    case ISD::SETOGT: CC1 = ISD::SETGT; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1976    case ISD::SETOGE: CC1 = ISD::SETGE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1977    case ISD::SETOLT: CC1 = ISD::SETLT; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1978    case ISD::SETOLE: CC1 = ISD::SETLE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1979    case ISD::SETONE: CC1 = ISD::SETNE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1980    case ISD::SETUEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1981    case ISD::SETUGT: CC1 = ISD::SETGT; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1982    case ISD::SETUGE: CC1 = ISD::SETGE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1983    case ISD::SETULT: CC1 = ISD::SETLT; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1984    case ISD::SETULE: CC1 = ISD::SETLE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1985    case ISD::SETUNE: CC1 = ISD::SETNE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1986    // FIXME: Implement more expansions.
1987    }
1988
1989    SDValue SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1);
1990    SDValue SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2);
1991    LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
1992    RHS = SDValue();
1993    CC  = SDValue();
1994    break;
1995  }
1996  }
1997}
1998
1999/// EmitStackConvert - Emit a store/load combination to the stack.  This stores
2000/// SrcOp to a stack slot of type SlotVT, truncating it if needed.  It then does
2001/// a load from the stack slot to DestVT, extending it if needed.
2002/// The resultant code need not be legal.
2003SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp,
2004                                               MVT SlotVT,
2005                                               MVT DestVT,
2006                                               DebugLoc dl) {
2007  // Create the stack frame object.
2008  unsigned SrcAlign =
2009    TLI.getTargetData()->getPrefTypeAlignment(SrcOp.getValueType().
2010                                              getTypeForMVT());
2011  SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign);
2012
2013  FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
2014  int SPFI = StackPtrFI->getIndex();
2015  const Value *SV = PseudoSourceValue::getFixedStack(SPFI);
2016
2017  unsigned SrcSize = SrcOp.getValueType().getSizeInBits();
2018  unsigned SlotSize = SlotVT.getSizeInBits();
2019  unsigned DestSize = DestVT.getSizeInBits();
2020  unsigned DestAlign =
2021    TLI.getTargetData()->getPrefTypeAlignment(DestVT.getTypeForMVT());
2022
2023  // Emit a store to the stack slot.  Use a truncstore if the input value is
2024  // later than DestVT.
2025  SDValue Store;
2026
2027  if (SrcSize > SlotSize)
2028    Store = DAG.getTruncStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
2029                              SV, 0, SlotVT, false, SrcAlign);
2030  else {
2031    assert(SrcSize == SlotSize && "Invalid store");
2032    Store = DAG.getStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
2033                         SV, 0, false, SrcAlign);
2034  }
2035
2036  // Result is a load from the stack slot.
2037  if (SlotSize == DestSize)
2038    return DAG.getLoad(DestVT, dl, Store, FIPtr, SV, 0, false, DestAlign);
2039
2040  assert(SlotSize < DestSize && "Unknown extension!");
2041  return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr, SV, 0, SlotVT,
2042                        false, DestAlign);
2043}
2044
2045SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
2046  DebugLoc dl = Node->getDebugLoc();
2047  // Create a vector sized/aligned stack slot, store the value to element #0,
2048  // then load the whole vector back out.
2049  SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
2050
2051  FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
2052  int SPFI = StackPtrFI->getIndex();
2053
2054  SDValue Ch = DAG.getTruncStore(DAG.getEntryNode(), dl, Node->getOperand(0),
2055                                 StackPtr,
2056                                 PseudoSourceValue::getFixedStack(SPFI), 0,
2057                                 Node->getValueType(0).getVectorElementType());
2058  return DAG.getLoad(Node->getValueType(0), dl, Ch, StackPtr,
2059                     PseudoSourceValue::getFixedStack(SPFI), 0);
2060}
2061
2062
2063/// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
2064/// support the operation, but do support the resultant vector type.
2065SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
2066  unsigned NumElems = Node->getNumOperands();
2067  SDValue SplatValue = Node->getOperand(0);
2068  DebugLoc dl = Node->getDebugLoc();
2069  MVT VT = Node->getValueType(0);
2070  MVT OpVT = SplatValue.getValueType();
2071  MVT EltVT = VT.getVectorElementType();
2072
2073  // If the only non-undef value is the low element, turn this into a
2074  // SCALAR_TO_VECTOR node.  If this is { X, X, X, X }, determine X.
2075  bool isOnlyLowElement = true;
2076
2077  // FIXME: it would be far nicer to change this into map<SDValue,uint64_t>
2078  // and use a bitmask instead of a list of elements.
2079  // FIXME: this doesn't treat <0, u, 0, u> for example, as a splat.
2080  std::map<SDValue, std::vector<unsigned> > Values;
2081  Values[SplatValue].push_back(0);
2082  bool isConstant = true;
2083  if (!isa<ConstantFPSDNode>(SplatValue) && !isa<ConstantSDNode>(SplatValue) &&
2084      SplatValue.getOpcode() != ISD::UNDEF)
2085    isConstant = false;
2086
2087  for (unsigned i = 1; i < NumElems; ++i) {
2088    SDValue V = Node->getOperand(i);
2089    Values[V].push_back(i);
2090    if (V.getOpcode() != ISD::UNDEF)
2091      isOnlyLowElement = false;
2092    if (SplatValue != V)
2093      SplatValue = SDValue(0, 0);
2094
2095    // If this isn't a constant element or an undef, we can't use a constant
2096    // pool load.
2097    if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V) &&
2098        V.getOpcode() != ISD::UNDEF)
2099      isConstant = false;
2100  }
2101
2102  if (isOnlyLowElement) {
2103    // If the low element is an undef too, then this whole things is an undef.
2104    if (Node->getOperand(0).getOpcode() == ISD::UNDEF)
2105      return DAG.getUNDEF(VT);
2106    // Otherwise, turn this into a scalar_to_vector node.
2107    return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
2108  }
2109
2110  // If all elements are constants, create a load from the constant pool.
2111  if (isConstant) {
2112    std::vector<Constant*> CV;
2113    for (unsigned i = 0, e = NumElems; i != e; ++i) {
2114      if (ConstantFPSDNode *V =
2115          dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
2116        CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
2117      } else if (ConstantSDNode *V =
2118                 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
2119        CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
2120      } else {
2121        assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
2122        const Type *OpNTy = OpVT.getTypeForMVT();
2123        CV.push_back(UndefValue::get(OpNTy));
2124      }
2125    }
2126    Constant *CP = ConstantVector::get(CV);
2127    SDValue CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
2128    unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
2129    return DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
2130                       PseudoSourceValue::getConstantPool(), 0,
2131                       false, Alignment);
2132  }
2133
2134  if (SplatValue.getNode()) {   // Splat of one value?
2135    // Build the shuffle constant vector: <0, 0, 0, 0>
2136    SmallVector<int, 8> ZeroVec(NumElems, 0);
2137
2138    // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
2139    if (TLI.isShuffleMaskLegal(ZeroVec, Node->getValueType(0))) {
2140      // Get the splatted value into the low element of a vector register.
2141      SDValue LowValVec =
2142        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, SplatValue);
2143
2144      // Return shuffle(LowValVec, undef, <0,0,0,0>)
2145      return DAG.getVectorShuffle(VT, dl, LowValVec, DAG.getUNDEF(VT),
2146                                  &ZeroVec[0]);
2147    }
2148  }
2149
2150  // If there are only two unique elements, we may be able to turn this into a
2151  // vector shuffle.
2152  if (Values.size() == 2) {
2153    // Get the two values in deterministic order.
2154    SDValue Val1 = Node->getOperand(1);
2155    SDValue Val2;
2156    std::map<SDValue, std::vector<unsigned> >::iterator MI = Values.begin();
2157    if (MI->first != Val1)
2158      Val2 = MI->first;
2159    else
2160      Val2 = (++MI)->first;
2161
2162    // If Val1 is an undef, make sure it ends up as Val2, to ensure that our
2163    // vector shuffle has the undef vector on the RHS.
2164    if (Val1.getOpcode() == ISD::UNDEF)
2165      std::swap(Val1, Val2);
2166
2167    // Build the shuffle constant vector: e.g. <0, 4, 0, 4>
2168    SmallVector<int, 8> ShuffleMask(NumElems, -1);
2169
2170    // Set elements of the shuffle mask for Val1.
2171    std::vector<unsigned> &Val1Elts = Values[Val1];
2172    for (unsigned i = 0, e = Val1Elts.size(); i != e; ++i)
2173      ShuffleMask[Val1Elts[i]] = 0;
2174
2175    // Set elements of the shuffle mask for Val2.
2176    std::vector<unsigned> &Val2Elts = Values[Val2];
2177    for (unsigned i = 0, e = Val2Elts.size(); i != e; ++i)
2178      if (Val2.getOpcode() != ISD::UNDEF)
2179        ShuffleMask[Val2Elts[i]] = NumElems;
2180
2181    // If the target supports SCALAR_TO_VECTOR and this shuffle mask, use it.
2182    if (TLI.isOperationLegalOrCustom(ISD::SCALAR_TO_VECTOR, VT) &&
2183        TLI.isShuffleMaskLegal(ShuffleMask, VT)) {
2184      Val1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Val1);
2185      Val2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Val2);
2186      return DAG.getVectorShuffle(VT, dl, Val1, Val2, &ShuffleMask[0]);
2187    }
2188  }
2189
2190  // Otherwise, we can't handle this case efficiently.  Allocate a sufficiently
2191  // aligned object on the stack, store each element into it, then load
2192  // the result as a vector.
2193  // Create the stack frame object.
2194  SDValue FIPtr = DAG.CreateStackTemporary(VT);
2195  int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
2196  const Value *SV = PseudoSourceValue::getFixedStack(FI);
2197
2198  // Emit a store of each element to the stack slot.
2199  SmallVector<SDValue, 8> Stores;
2200  unsigned TypeByteSize = OpVT.getSizeInBits() / 8;
2201  // Store (in the right endianness) the elements to memory.
2202  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
2203    // Ignore undef elements.
2204    if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
2205
2206    unsigned Offset = TypeByteSize*i;
2207
2208    SDValue Idx = DAG.getConstant(Offset, FIPtr.getValueType());
2209    Idx = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, Idx);
2210
2211    Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, Node->getOperand(i),
2212                                  Idx, SV, Offset));
2213  }
2214
2215  SDValue StoreChain;
2216  if (!Stores.empty())    // Not all undef elements?
2217    StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2218                             &Stores[0], Stores.size());
2219  else
2220    StoreChain = DAG.getEntryNode();
2221
2222  // Result is a load from the stack slot.
2223  return DAG.getLoad(VT, dl, StoreChain, FIPtr, SV, 0);
2224}
2225
2226// ExpandLibCall - Expand a node into a call to a libcall.  If the result value
2227// does not fit into a register, return the lo part and set the hi part to the
2228// by-reg argument.  If it does fit into a single register, return the result
2229// and leave the Hi part unset.
2230SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
2231                                            bool isSigned) {
2232  assert(!IsLegalizingCall && "Cannot overlap legalization of calls!");
2233  // The input chain to this libcall is the entry node of the function.
2234  // Legalizing the call will automatically add the previous call to the
2235  // dependence.
2236  SDValue InChain = DAG.getEntryNode();
2237
2238  TargetLowering::ArgListTy Args;
2239  TargetLowering::ArgListEntry Entry;
2240  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
2241    MVT ArgVT = Node->getOperand(i).getValueType();
2242    const Type *ArgTy = ArgVT.getTypeForMVT();
2243    Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy;
2244    Entry.isSExt = isSigned;
2245    Entry.isZExt = !isSigned;
2246    Args.push_back(Entry);
2247  }
2248  SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2249                                         TLI.getPointerTy());
2250
2251  // Splice the libcall in wherever FindInputOutputChains tells us to.
2252  const Type *RetTy = Node->getValueType(0).getTypeForMVT();
2253  std::pair<SDValue, SDValue> CallInfo =
2254    TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
2255                    CallingConv::C, false, Callee, Args, DAG,
2256                    Node->getDebugLoc());
2257
2258  // Legalize the call sequence, starting with the chain.  This will advance
2259  // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
2260  // was added by LowerCallTo (guaranteeing proper serialization of calls).
2261  LegalizeOp(CallInfo.second);
2262  return CallInfo.first;
2263}
2264
2265SDValue SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
2266                                              RTLIB::Libcall Call_F32,
2267                                              RTLIB::Libcall Call_F64,
2268                                              RTLIB::Libcall Call_F80,
2269                                              RTLIB::Libcall Call_PPCF128) {
2270  RTLIB::Libcall LC;
2271  switch (Node->getValueType(0).getSimpleVT()) {
2272  default: assert(0 && "Unexpected request for libcall!");
2273  case MVT::f32: LC = Call_F32; break;
2274  case MVT::f64: LC = Call_F64; break;
2275  case MVT::f80: LC = Call_F80; break;
2276  case MVT::ppcf128: LC = Call_PPCF128; break;
2277  }
2278  return ExpandLibCall(LC, Node, false);
2279}
2280
2281SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned,
2282                                               RTLIB::Libcall Call_I16,
2283                                               RTLIB::Libcall Call_I32,
2284                                               RTLIB::Libcall Call_I64,
2285                                               RTLIB::Libcall Call_I128) {
2286  RTLIB::Libcall LC;
2287  switch (Node->getValueType(0).getSimpleVT()) {
2288  default: assert(0 && "Unexpected request for libcall!");
2289  case MVT::i16: LC = Call_I16; break;
2290  case MVT::i32: LC = Call_I32; break;
2291  case MVT::i64: LC = Call_I64; break;
2292  case MVT::i128: LC = Call_I128; break;
2293  }
2294  return ExpandLibCall(LC, Node, isSigned);
2295}
2296
2297/// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
2298/// INT_TO_FP operation of the specified operand when the target requests that
2299/// we expand it.  At this point, we know that the result and operand types are
2300/// legal for the target.
2301SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
2302                                                   SDValue Op0,
2303                                                   MVT DestVT,
2304                                                   DebugLoc dl) {
2305  if (Op0.getValueType() == MVT::i32) {
2306    // simple 32-bit [signed|unsigned] integer to float/double expansion
2307
2308    // Get the stack frame index of a 8 byte buffer.
2309    SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
2310
2311    // word offset constant for Hi/Lo address computation
2312    SDValue WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
2313    // set up Hi and Lo (into buffer) address based on endian
2314    SDValue Hi = StackSlot;
2315    SDValue Lo = DAG.getNode(ISD::ADD, dl,
2316                             TLI.getPointerTy(), StackSlot, WordOff);
2317    if (TLI.isLittleEndian())
2318      std::swap(Hi, Lo);
2319
2320    // if signed map to unsigned space
2321    SDValue Op0Mapped;
2322    if (isSigned) {
2323      // constant used to invert sign bit (signed to unsigned mapping)
2324      SDValue SignBit = DAG.getConstant(0x80000000u, MVT::i32);
2325      Op0Mapped = DAG.getNode(ISD::XOR, dl, MVT::i32, Op0, SignBit);
2326    } else {
2327      Op0Mapped = Op0;
2328    }
2329    // store the lo of the constructed double - based on integer input
2330    SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl,
2331                                  Op0Mapped, Lo, NULL, 0);
2332    // initial hi portion of constructed double
2333    SDValue InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
2334    // store the hi of the constructed double - biased exponent
2335    SDValue Store2=DAG.getStore(Store1, dl, InitialHi, Hi, NULL, 0);
2336    // load the constructed double
2337    SDValue Load = DAG.getLoad(MVT::f64, dl, Store2, StackSlot, NULL, 0);
2338    // FP constant to bias correct the final result
2339    SDValue Bias = DAG.getConstantFP(isSigned ?
2340                                     BitsToDouble(0x4330000080000000ULL) :
2341                                     BitsToDouble(0x4330000000000000ULL),
2342                                     MVT::f64);
2343    // subtract the bias
2344    SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
2345    // final result
2346    SDValue Result;
2347    // handle final rounding
2348    if (DestVT == MVT::f64) {
2349      // do nothing
2350      Result = Sub;
2351    } else if (DestVT.bitsLT(MVT::f64)) {
2352      Result = DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
2353                           DAG.getIntPtrConstant(0));
2354    } else if (DestVT.bitsGT(MVT::f64)) {
2355      Result = DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
2356    }
2357    return Result;
2358  }
2359  assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
2360  SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2361
2362  SDValue SignSet = DAG.getSetCC(dl, TLI.getSetCCResultType(Op0.getValueType()),
2363                                 Op0, DAG.getConstant(0, Op0.getValueType()),
2364                                 ISD::SETLT);
2365  SDValue Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
2366  SDValue CstOffset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(),
2367                                    SignSet, Four, Zero);
2368
2369  // If the sign bit of the integer is set, the large number will be treated
2370  // as a negative number.  To counteract this, the dynamic code adds an
2371  // offset depending on the data type.
2372  uint64_t FF;
2373  switch (Op0.getValueType().getSimpleVT()) {
2374  default: assert(0 && "Unsupported integer type!");
2375  case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
2376  case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
2377  case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
2378  case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
2379  }
2380  if (TLI.isLittleEndian()) FF <<= 32;
2381  Constant *FudgeFactor = ConstantInt::get(Type::Int64Ty, FF);
2382
2383  SDValue CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
2384  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
2385  CPIdx = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), CPIdx, CstOffset);
2386  Alignment = std::min(Alignment, 4u);
2387  SDValue FudgeInReg;
2388  if (DestVT == MVT::f32)
2389    FudgeInReg = DAG.getLoad(MVT::f32, dl, DAG.getEntryNode(), CPIdx,
2390                             PseudoSourceValue::getConstantPool(), 0,
2391                             false, Alignment);
2392  else {
2393    FudgeInReg =
2394      LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT,
2395                                DAG.getEntryNode(), CPIdx,
2396                                PseudoSourceValue::getConstantPool(), 0,
2397                                MVT::f32, false, Alignment));
2398  }
2399
2400  return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
2401}
2402
2403/// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
2404/// *INT_TO_FP operation of the specified operand when the target requests that
2405/// we promote it.  At this point, we know that the result and operand types are
2406/// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
2407/// operation that takes a larger input.
2408SDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp,
2409                                                    MVT DestVT,
2410                                                    bool isSigned,
2411                                                    DebugLoc dl) {
2412  // First step, figure out the appropriate *INT_TO_FP operation to use.
2413  MVT NewInTy = LegalOp.getValueType();
2414
2415  unsigned OpToUse = 0;
2416
2417  // Scan for the appropriate larger type to use.
2418  while (1) {
2419    NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT()+1);
2420    assert(NewInTy.isInteger() && "Ran out of possibilities!");
2421
2422    // If the target supports SINT_TO_FP of this type, use it.
2423    switch (TLI.getOperationAction(ISD::SINT_TO_FP, NewInTy)) {
2424      default: break;
2425      case TargetLowering::Legal:
2426        if (!TLI.isTypeLegal(NewInTy))
2427          break;  // Can't use this datatype.
2428        // FALL THROUGH.
2429      case TargetLowering::Custom:
2430        OpToUse = ISD::SINT_TO_FP;
2431        break;
2432    }
2433    if (OpToUse) break;
2434    if (isSigned) continue;
2435
2436    // If the target supports UINT_TO_FP of this type, use it.
2437    switch (TLI.getOperationAction(ISD::UINT_TO_FP, NewInTy)) {
2438      default: break;
2439      case TargetLowering::Legal:
2440        if (!TLI.isTypeLegal(NewInTy))
2441          break;  // Can't use this datatype.
2442        // FALL THROUGH.
2443      case TargetLowering::Custom:
2444        OpToUse = ISD::UINT_TO_FP;
2445        break;
2446    }
2447    if (OpToUse) break;
2448
2449    // Otherwise, try a larger type.
2450  }
2451
2452  // Okay, we found the operation and type to use.  Zero extend our input to the
2453  // desired type then run the operation on it.
2454  return DAG.getNode(OpToUse, dl, DestVT,
2455                     DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
2456                                 dl, NewInTy, LegalOp));
2457}
2458
2459/// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
2460/// FP_TO_*INT operation of the specified operand when the target requests that
2461/// we promote it.  At this point, we know that the result and operand types are
2462/// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
2463/// operation that returns a larger result.
2464SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp,
2465                                                    MVT DestVT,
2466                                                    bool isSigned,
2467                                                    DebugLoc dl) {
2468  // First step, figure out the appropriate FP_TO*INT operation to use.
2469  MVT NewOutTy = DestVT;
2470
2471  unsigned OpToUse = 0;
2472
2473  // Scan for the appropriate larger type to use.
2474  while (1) {
2475    NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT()+1);
2476    assert(NewOutTy.isInteger() && "Ran out of possibilities!");
2477
2478    // If the target supports FP_TO_SINT returning this type, use it.
2479    switch (TLI.getOperationAction(ISD::FP_TO_SINT, NewOutTy)) {
2480    default: break;
2481    case TargetLowering::Legal:
2482      if (!TLI.isTypeLegal(NewOutTy))
2483        break;  // Can't use this datatype.
2484      // FALL THROUGH.
2485    case TargetLowering::Custom:
2486      OpToUse = ISD::FP_TO_SINT;
2487      break;
2488    }
2489    if (OpToUse) break;
2490
2491    // If the target supports FP_TO_UINT of this type, use it.
2492    switch (TLI.getOperationAction(ISD::FP_TO_UINT, NewOutTy)) {
2493    default: break;
2494    case TargetLowering::Legal:
2495      if (!TLI.isTypeLegal(NewOutTy))
2496        break;  // Can't use this datatype.
2497      // FALL THROUGH.
2498    case TargetLowering::Custom:
2499      OpToUse = ISD::FP_TO_UINT;
2500      break;
2501    }
2502    if (OpToUse) break;
2503
2504    // Otherwise, try a larger type.
2505  }
2506
2507
2508  // Okay, we found the operation and type to use.
2509  SDValue Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
2510
2511  // If the operation produces an invalid type, it must be custom lowered.  Use
2512  // the target lowering hooks to expand it.  Just keep the low part of the
2513  // expanded operation, we know that we're truncating anyway.
2514  if (getTypeAction(NewOutTy) == Expand) {
2515    SmallVector<SDValue, 2> Results;
2516    TLI.ReplaceNodeResults(Operation.getNode(), Results, DAG);
2517    assert(Results.size() == 1 && "Incorrect FP_TO_XINT lowering!");
2518    Operation = Results[0];
2519  }
2520
2521  // Truncate the result of the extended FP_TO_*INT operation to the desired
2522  // size.
2523  return DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
2524}
2525
2526/// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
2527///
2528SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op, DebugLoc dl) {
2529  MVT VT = Op.getValueType();
2530  MVT SHVT = TLI.getShiftAmountTy();
2531  SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
2532  switch (VT.getSimpleVT()) {
2533  default: assert(0 && "Unhandled Expand type in BSWAP!"); abort();
2534  case MVT::i16:
2535    Tmp2 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2536    Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2537    return DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
2538  case MVT::i32:
2539    Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2540    Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2541    Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2542    Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2543    Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
2544    Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, VT));
2545    Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2546    Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2547    return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2548  case MVT::i64:
2549    Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, SHVT));
2550    Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, SHVT));
2551    Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2552    Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2553    Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2554    Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2555    Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, SHVT));
2556    Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, SHVT));
2557    Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
2558    Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
2559    Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
2560    Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
2561    Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
2562    Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
2563    Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
2564    Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
2565    Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2566    Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2567    Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
2568    Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2569    return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
2570  }
2571}
2572
2573/// ExpandBitCount - Expand the specified bitcount instruction into operations.
2574///
2575SDValue SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDValue Op,
2576                                             DebugLoc dl) {
2577  switch (Opc) {
2578  default: assert(0 && "Cannot expand this yet!");
2579  case ISD::CTPOP: {
2580    static const uint64_t mask[6] = {
2581      0x5555555555555555ULL, 0x3333333333333333ULL,
2582      0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
2583      0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
2584    };
2585    MVT VT = Op.getValueType();
2586    MVT ShVT = TLI.getShiftAmountTy();
2587    unsigned len = VT.getSizeInBits();
2588    for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
2589      //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
2590      unsigned EltSize = VT.isVector() ?
2591        VT.getVectorElementType().getSizeInBits() : len;
2592      SDValue Tmp2 = DAG.getConstant(APInt(EltSize, mask[i]), VT);
2593      SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
2594      Op = DAG.getNode(ISD::ADD, dl, VT,
2595                       DAG.getNode(ISD::AND, dl, VT, Op, Tmp2),
2596                       DAG.getNode(ISD::AND, dl, VT,
2597                                   DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3),
2598                                   Tmp2));
2599    }
2600    return Op;
2601  }
2602  case ISD::CTLZ: {
2603    // for now, we do this:
2604    // x = x | (x >> 1);
2605    // x = x | (x >> 2);
2606    // ...
2607    // x = x | (x >>16);
2608    // x = x | (x >>32); // for 64-bit input
2609    // return popcount(~x);
2610    //
2611    // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
2612    MVT VT = Op.getValueType();
2613    MVT ShVT = TLI.getShiftAmountTy();
2614    unsigned len = VT.getSizeInBits();
2615    for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
2616      SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
2617      Op = DAG.getNode(ISD::OR, dl, VT, Op,
2618                       DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3));
2619    }
2620    Op = DAG.getNOT(dl, Op, VT);
2621    return DAG.getNode(ISD::CTPOP, dl, VT, Op);
2622  }
2623  case ISD::CTTZ: {
2624    // for now, we use: { return popcount(~x & (x - 1)); }
2625    // unless the target has ctlz but not ctpop, in which case we use:
2626    // { return 32 - nlz(~x & (x-1)); }
2627    // see also http://www.hackersdelight.org/HDcode/ntz.cc
2628    MVT VT = Op.getValueType();
2629    SDValue Tmp3 = DAG.getNode(ISD::AND, dl, VT,
2630                               DAG.getNOT(dl, Op, VT),
2631                               DAG.getNode(ISD::SUB, dl, VT, Op,
2632                                           DAG.getConstant(1, VT)));
2633    // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
2634    if (!TLI.isOperationLegalOrCustom(ISD::CTPOP, VT) &&
2635        TLI.isOperationLegalOrCustom(ISD::CTLZ, VT))
2636      return DAG.getNode(ISD::SUB, dl, VT,
2637                         DAG.getConstant(VT.getSizeInBits(), VT),
2638                         DAG.getNode(ISD::CTLZ, dl, VT, Tmp3));
2639    return DAG.getNode(ISD::CTPOP, dl, VT, Tmp3);
2640  }
2641  }
2642}
2643
2644void SelectionDAGLegalize::ExpandNode(SDNode *Node,
2645                                      SmallVectorImpl<SDValue> &Results) {
2646  DebugLoc dl = Node->getDebugLoc();
2647  SDValue Tmp1, Tmp2, Tmp3;
2648  switch (Node->getOpcode()) {
2649  case ISD::CTPOP:
2650  case ISD::CTLZ:
2651  case ISD::CTTZ:
2652    Tmp1 = ExpandBitCount(Node->getOpcode(), Node->getOperand(0), dl);
2653    Results.push_back(Tmp1);
2654    break;
2655  case ISD::BSWAP:
2656    Results.push_back(ExpandBSWAP(Node->getOperand(0), dl));
2657    break;
2658  case ISD::FRAMEADDR:
2659  case ISD::RETURNADDR:
2660  case ISD::FRAME_TO_ARGS_OFFSET:
2661    Results.push_back(DAG.getConstant(0, Node->getValueType(0)));
2662    break;
2663  case ISD::FLT_ROUNDS_:
2664    Results.push_back(DAG.getConstant(1, Node->getValueType(0)));
2665    break;
2666  case ISD::EH_RETURN:
2667  case ISD::DECLARE:
2668  case ISD::DBG_LABEL:
2669  case ISD::EH_LABEL:
2670  case ISD::PREFETCH:
2671  case ISD::MEMBARRIER:
2672  case ISD::VAEND:
2673    Results.push_back(Node->getOperand(0));
2674    break;
2675  case ISD::MERGE_VALUES:
2676    for (unsigned i = 0; i < Node->getNumValues(); i++)
2677      Results.push_back(Node->getOperand(i));
2678    break;
2679  case ISD::UNDEF: {
2680    MVT VT = Node->getValueType(0);
2681    if (VT.isInteger())
2682      Results.push_back(DAG.getConstant(0, VT));
2683    else if (VT.isFloatingPoint())
2684      Results.push_back(DAG.getConstantFP(0, VT));
2685    else
2686      assert(0 && "Unknown value type!");
2687    break;
2688  }
2689  case ISD::TRAP: {
2690    // If this operation is not supported, lower it to 'abort()' call
2691    TargetLowering::ArgListTy Args;
2692    std::pair<SDValue, SDValue> CallResult =
2693      TLI.LowerCallTo(Node->getOperand(0), Type::VoidTy,
2694                      false, false, false, false, CallingConv::C, false,
2695                      DAG.getExternalSymbol("abort", TLI.getPointerTy()),
2696                      Args, DAG, dl);
2697    Results.push_back(CallResult.second);
2698    break;
2699  }
2700  case ISD::FP_ROUND:
2701  case ISD::BIT_CONVERT:
2702    Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
2703                            Node->getValueType(0), dl);
2704    Results.push_back(Tmp1);
2705    break;
2706  case ISD::FP_EXTEND:
2707    Tmp1 = EmitStackConvert(Node->getOperand(0),
2708                            Node->getOperand(0).getValueType(),
2709                            Node->getValueType(0), dl);
2710    Results.push_back(Tmp1);
2711    break;
2712  case ISD::SIGN_EXTEND_INREG: {
2713    // NOTE: we could fall back on load/store here too for targets without
2714    // SAR.  However, it is doubtful that any exist.
2715    MVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2716    unsigned BitsDiff = Node->getValueType(0).getSizeInBits() -
2717                        ExtraVT.getSizeInBits();
2718    SDValue ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
2719    Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0),
2720                       Node->getOperand(0), ShiftCst);
2721    Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst);
2722    Results.push_back(Tmp1);
2723    break;
2724  }
2725  case ISD::FP_ROUND_INREG: {
2726    // The only way we can lower this is to turn it into a TRUNCSTORE,
2727    // EXTLOAD pair, targetting a temporary location (a stack slot).
2728
2729    // NOTE: there is a choice here between constantly creating new stack
2730    // slots and always reusing the same one.  We currently always create
2731    // new ones, as reuse may inhibit scheduling.
2732    MVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2733    Tmp1 = EmitStackConvert(Node->getOperand(0), ExtraVT,
2734                            Node->getValueType(0), dl);
2735    Results.push_back(Tmp1);
2736    break;
2737  }
2738  case ISD::SINT_TO_FP:
2739  case ISD::UINT_TO_FP:
2740    Tmp1 = ExpandLegalINT_TO_FP(Node->getOpcode() == ISD::SINT_TO_FP,
2741                                Node->getOperand(0), Node->getValueType(0), dl);
2742    Results.push_back(Tmp1);
2743    break;
2744  case ISD::FP_TO_UINT: {
2745    SDValue True, False;
2746    MVT VT =  Node->getOperand(0).getValueType();
2747    MVT NVT = Node->getValueType(0);
2748    const uint64_t zero[] = {0, 0};
2749    APFloat apf = APFloat(APInt(VT.getSizeInBits(), 2, zero));
2750    APInt x = APInt::getSignBit(NVT.getSizeInBits());
2751    (void)apf.convertFromAPInt(x, false, APFloat::rmNearestTiesToEven);
2752    Tmp1 = DAG.getConstantFP(apf, VT);
2753    Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(VT),
2754                        Node->getOperand(0),
2755                        Tmp1, ISD::SETLT);
2756    True = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, Node->getOperand(0));
2757    False = DAG.getNode(ISD::FP_TO_SINT, dl, NVT,
2758                        DAG.getNode(ISD::FSUB, dl, VT,
2759                                    Node->getOperand(0), Tmp1));
2760    False = DAG.getNode(ISD::XOR, dl, NVT, False,
2761                        DAG.getConstant(x, NVT));
2762    Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2, True, False);
2763    Results.push_back(Tmp1);
2764    break;
2765  }
2766  case ISD::VAARG: {
2767    const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2768    MVT VT = Node->getValueType(0);
2769    Tmp1 = Node->getOperand(0);
2770    Tmp2 = Node->getOperand(1);
2771    SDValue VAList = DAG.getLoad(TLI.getPointerTy(), dl, Tmp1, Tmp2, V, 0);
2772    // Increment the pointer, VAList, to the next vaarg
2773    Tmp3 = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), VAList,
2774                       DAG.getConstant(TLI.getTargetData()->
2775                                       getTypeAllocSize(VT.getTypeForMVT()),
2776                                       TLI.getPointerTy()));
2777    // Store the incremented VAList to the legalized pointer
2778    Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Tmp2, V, 0);
2779    // Load the actual argument out of the pointer VAList
2780    Results.push_back(DAG.getLoad(VT, dl, Tmp3, VAList, NULL, 0));
2781    Results.push_back(Results[0].getValue(1));
2782    break;
2783  }
2784  case ISD::VACOPY: {
2785    // This defaults to loading a pointer from the input and storing it to the
2786    // output, returning the chain.
2787    const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2788    const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2789    Tmp1 = DAG.getLoad(TLI.getPointerTy(), dl, Node->getOperand(0),
2790                       Node->getOperand(2), VS, 0);
2791    Tmp1 = DAG.getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), VD, 0);
2792    Results.push_back(Tmp1);
2793    break;
2794  }
2795  case ISD::EXTRACT_VECTOR_ELT:
2796    if (Node->getOperand(0).getValueType().getVectorNumElements() == 1)
2797      // This must be an access of the only element.  Return it.
2798      Tmp1 = DAG.getNode(ISD::BIT_CONVERT, dl, Node->getValueType(0),
2799                         Node->getOperand(0));
2800    else
2801      Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0));
2802    Results.push_back(Tmp1);
2803    break;
2804  case ISD::EXTRACT_SUBVECTOR:
2805    Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0)));
2806    break;
2807  case ISD::CONCAT_VECTORS: {
2808    // Use extract/insert/build vector for now. We might try to be
2809    // more clever later.
2810    SmallVector<SDValue, 8> Ops;
2811    unsigned NumOperands = Node->getNumOperands();
2812    for (unsigned i=0; i < NumOperands; ++i) {
2813      SDValue SubOp = Node->getOperand(i);
2814      MVT VVT = SubOp.getNode()->getValueType(0);
2815      MVT EltVT = VVT.getVectorElementType();
2816      unsigned NumSubElem = VVT.getVectorNumElements();
2817      for (unsigned j=0; j < NumSubElem; ++j) {
2818        Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, SubOp,
2819                                  DAG.getIntPtrConstant(j)));
2820      }
2821    }
2822    Tmp1 = DAG.getNode(ISD::BUILD_VECTOR, dl, Node->getValueType(0),
2823                       &Ops[0], Ops.size());
2824    Results.push_back(Tmp1);
2825    break;
2826  }
2827  case ISD::SCALAR_TO_VECTOR:
2828    Results.push_back(ExpandSCALAR_TO_VECTOR(Node));
2829    break;
2830  case ISD::INSERT_VECTOR_ELT:
2831    Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0),
2832                                              Node->getOperand(1),
2833                                              Node->getOperand(2), dl));
2834    break;
2835  case ISD::VECTOR_SHUFFLE: {
2836    SmallVector<int, 8> Mask;
2837    cast<ShuffleVectorSDNode>(Node)->getMask(Mask);
2838
2839    MVT VT = Node->getValueType(0);
2840    MVT EltVT = VT.getVectorElementType();
2841    unsigned NumElems = VT.getVectorNumElements();
2842    SmallVector<SDValue, 8> Ops;
2843    for (unsigned i = 0; i != NumElems; ++i) {
2844      if (Mask[i] < 0) {
2845        Ops.push_back(DAG.getUNDEF(EltVT));
2846        continue;
2847      }
2848      unsigned Idx = Mask[i];
2849      if (Idx < NumElems)
2850        Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
2851                                  Node->getOperand(0),
2852                                  DAG.getIntPtrConstant(Idx)));
2853      else
2854        Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
2855                                  Node->getOperand(1),
2856                                  DAG.getIntPtrConstant(Idx - NumElems)));
2857    }
2858    Tmp1 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], Ops.size());
2859    Results.push_back(Tmp1);
2860    break;
2861  }
2862  case ISD::EXTRACT_ELEMENT: {
2863    MVT OpTy = Node->getOperand(0).getValueType();
2864    if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
2865      // 1 -> Hi
2866      Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0),
2867                         DAG.getConstant(OpTy.getSizeInBits()/2,
2868                                         TLI.getShiftAmountTy()));
2869      Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
2870    } else {
2871      // 0 -> Lo
2872      Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
2873                         Node->getOperand(0));
2874    }
2875    Results.push_back(Tmp1);
2876    break;
2877  }
2878  case ISD::STACKSAVE:
2879    // Expand to CopyFromReg if the target set
2880    // StackPointerRegisterToSaveRestore.
2881    if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2882      Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP,
2883                                           Node->getValueType(0)));
2884      Results.push_back(Results[0].getValue(1));
2885    } else {
2886      Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
2887      Results.push_back(Node->getOperand(0));
2888    }
2889    break;
2890  case ISD::STACKRESTORE:
2891    // Expand to CopyToReg if the target set
2892    // StackPointerRegisterToSaveRestore.
2893    if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2894      Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP,
2895                                         Node->getOperand(1)));
2896    } else {
2897      Results.push_back(Node->getOperand(0));
2898    }
2899    break;
2900  case ISD::FNEG:
2901    // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
2902    Tmp1 = DAG.getConstantFP(-0.0, Node->getValueType(0));
2903    Tmp1 = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp1,
2904                       Node->getOperand(0));
2905    Results.push_back(Tmp1);
2906    break;
2907  case ISD::FABS: {
2908    // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
2909    MVT VT = Node->getValueType(0);
2910    Tmp1 = Node->getOperand(0);
2911    Tmp2 = DAG.getConstantFP(0.0, VT);
2912    Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(Tmp1.getValueType()),
2913                        Tmp1, Tmp2, ISD::SETUGT);
2914    Tmp3 = DAG.getNode(ISD::FNEG, dl, VT, Tmp1);
2915    Tmp1 = DAG.getNode(ISD::SELECT, dl, VT, Tmp2, Tmp1, Tmp3);
2916    Results.push_back(Tmp1);
2917    break;
2918  }
2919  case ISD::FSQRT:
2920    Results.push_back(ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
2921                                      RTLIB::SQRT_F80, RTLIB::SQRT_PPCF128));
2922    break;
2923  case ISD::FSIN:
2924    Results.push_back(ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64,
2925                                      RTLIB::SIN_F80, RTLIB::SIN_PPCF128));
2926    break;
2927  case ISD::FCOS:
2928    Results.push_back(ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64,
2929                                      RTLIB::COS_F80, RTLIB::COS_PPCF128));
2930    break;
2931  case ISD::FLOG:
2932    Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64,
2933                                      RTLIB::LOG_F80, RTLIB::LOG_PPCF128));
2934    break;
2935  case ISD::FLOG2:
2936    Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
2937                                      RTLIB::LOG2_F80, RTLIB::LOG2_PPCF128));
2938    break;
2939  case ISD::FLOG10:
2940    Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
2941                                      RTLIB::LOG10_F80, RTLIB::LOG10_PPCF128));
2942    break;
2943  case ISD::FEXP:
2944    Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64,
2945                                      RTLIB::EXP_F80, RTLIB::EXP_PPCF128));
2946    break;
2947  case ISD::FEXP2:
2948    Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
2949                                      RTLIB::EXP2_F80, RTLIB::EXP2_PPCF128));
2950    break;
2951  case ISD::FTRUNC:
2952    Results.push_back(ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
2953                                      RTLIB::TRUNC_F80, RTLIB::TRUNC_PPCF128));
2954    break;
2955  case ISD::FFLOOR:
2956    Results.push_back(ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
2957                                      RTLIB::FLOOR_F80, RTLIB::FLOOR_PPCF128));
2958    break;
2959  case ISD::FCEIL:
2960    Results.push_back(ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
2961                                      RTLIB::CEIL_F80, RTLIB::CEIL_PPCF128));
2962    break;
2963  case ISD::FRINT:
2964    Results.push_back(ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64,
2965                                      RTLIB::RINT_F80, RTLIB::RINT_PPCF128));
2966    break;
2967  case ISD::FNEARBYINT:
2968    Results.push_back(ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32,
2969                                      RTLIB::NEARBYINT_F64,
2970                                      RTLIB::NEARBYINT_F80,
2971                                      RTLIB::NEARBYINT_PPCF128));
2972    break;
2973  case ISD::FPOWI:
2974    Results.push_back(ExpandFPLibCall(Node, RTLIB::POWI_F32, RTLIB::POWI_F64,
2975                                      RTLIB::POWI_F80, RTLIB::POWI_PPCF128));
2976    break;
2977  case ISD::FPOW:
2978    Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64,
2979                                      RTLIB::POW_F80, RTLIB::POW_PPCF128));
2980    break;
2981  case ISD::FDIV:
2982    Results.push_back(ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64,
2983                                      RTLIB::DIV_F80, RTLIB::DIV_PPCF128));
2984    break;
2985  case ISD::FREM:
2986    Results.push_back(ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64,
2987                                      RTLIB::REM_F80, RTLIB::REM_PPCF128));
2988    break;
2989  case ISD::ConstantFP: {
2990    ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
2991    // Check to see if this FP immediate is already legal.
2992    bool isLegal = false;
2993    for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
2994            E = TLI.legal_fpimm_end(); I != E; ++I) {
2995      if (CFP->isExactlyValue(*I)) {
2996        isLegal = true;
2997        break;
2998      }
2999    }
3000    // If this is a legal constant, turn it into a TargetConstantFP node.
3001    if (isLegal)
3002      Results.push_back(SDValue(Node, 0));
3003    else
3004      Results.push_back(ExpandConstantFP(CFP, true, DAG, TLI));
3005    break;
3006  }
3007  case ISD::EHSELECTION: {
3008    unsigned Reg = TLI.getExceptionSelectorRegister();
3009    assert(Reg && "Can't expand to unknown register!");
3010    Results.push_back(DAG.getCopyFromReg(Node->getOperand(1), dl, Reg,
3011                                         Node->getValueType(0)));
3012    Results.push_back(Results[0].getValue(1));
3013    break;
3014  }
3015  case ISD::EXCEPTIONADDR: {
3016    unsigned Reg = TLI.getExceptionAddressRegister();
3017    assert(Reg && "Can't expand to unknown register!");
3018    Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, Reg,
3019                                         Node->getValueType(0)));
3020    Results.push_back(Results[0].getValue(1));
3021    break;
3022  }
3023  case ISD::SUB: {
3024    MVT VT = Node->getValueType(0);
3025    assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
3026           TLI.isOperationLegalOrCustom(ISD::XOR, VT) &&
3027           "Don't know how to expand this subtraction!");
3028    Tmp1 = DAG.getNode(ISD::XOR, dl, VT, Node->getOperand(1),
3029               DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT));
3030    Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp2, DAG.getConstant(1, VT));
3031    Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1));
3032    break;
3033  }
3034  case ISD::UREM:
3035  case ISD::SREM: {
3036    MVT VT = Node->getValueType(0);
3037    SDVTList VTs = DAG.getVTList(VT, VT);
3038    bool isSigned = Node->getOpcode() == ISD::SREM;
3039    unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
3040    unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3041    Tmp2 = Node->getOperand(0);
3042    Tmp3 = Node->getOperand(1);
3043    if (TLI.getOperationAction(DivOpc, VT) == TargetLowering::Legal) {
3044      // X % Y -> X-X/Y*Y
3045      Tmp1 = DAG.getNode(DivOpc, dl, VT, Tmp2, Tmp3);
3046      Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Tmp3);
3047      Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Tmp2, Tmp1);
3048    } else if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) {
3049      Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Tmp2, Tmp3).getValue(1);
3050    } else if (isSigned) {
3051      Tmp1 = ExpandIntLibCall(Node, true, RTLIB::SREM_I16, RTLIB::SREM_I32,
3052                              RTLIB::SREM_I64, RTLIB::SREM_I128);
3053    } else {
3054      Tmp1 = ExpandIntLibCall(Node, false, RTLIB::UREM_I16, RTLIB::UREM_I32,
3055                              RTLIB::UREM_I64, RTLIB::UREM_I128);
3056    }
3057    Results.push_back(Tmp1);
3058    break;
3059  }
3060  case ISD::UDIV:
3061  case ISD::SDIV: {
3062    bool isSigned = Node->getOpcode() == ISD::SDIV;
3063    unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3064    MVT VT = Node->getValueType(0);
3065    SDVTList VTs = DAG.getVTList(VT, VT);
3066    if (TLI.isOperationLegalOrCustom(DivRemOpc, VT))
3067      Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0),
3068                         Node->getOperand(1));
3069    else if (isSigned)
3070      Tmp1 = ExpandIntLibCall(Node, true, RTLIB::SDIV_I16, RTLIB::SDIV_I32,
3071                              RTLIB::SDIV_I64, RTLIB::SDIV_I128);
3072    else
3073      Tmp1 = ExpandIntLibCall(Node, false, RTLIB::UDIV_I16, RTLIB::UDIV_I32,
3074                              RTLIB::UDIV_I64, RTLIB::UDIV_I128);
3075    Results.push_back(Tmp1);
3076    break;
3077  }
3078  case ISD::MULHU:
3079  case ISD::MULHS: {
3080    unsigned ExpandOpcode = Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI :
3081                                                              ISD::SMUL_LOHI;
3082    MVT VT = Node->getValueType(0);
3083    SDVTList VTs = DAG.getVTList(VT, VT);
3084    assert(TLI.isOperationLegalOrCustom(ExpandOpcode, VT) &&
3085           "If this wasn't legal, it shouldn't have been created!");
3086    Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0),
3087                       Node->getOperand(1));
3088    Results.push_back(Tmp1.getValue(1));
3089    break;
3090  }
3091  case ISD::MUL: {
3092    MVT VT = Node->getValueType(0);
3093    SDVTList VTs = DAG.getVTList(VT, VT);
3094    // See if multiply or divide can be lowered using two-result operations.
3095    // We just need the low half of the multiply; try both the signed
3096    // and unsigned forms. If the target supports both SMUL_LOHI and
3097    // UMUL_LOHI, form a preference by checking which forms of plain
3098    // MULH it supports.
3099    bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
3100    bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
3101    bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
3102    bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
3103    unsigned OpToUse = 0;
3104    if (HasSMUL_LOHI && !HasMULHS) {
3105      OpToUse = ISD::SMUL_LOHI;
3106    } else if (HasUMUL_LOHI && !HasMULHU) {
3107      OpToUse = ISD::UMUL_LOHI;
3108    } else if (HasSMUL_LOHI) {
3109      OpToUse = ISD::SMUL_LOHI;
3110    } else if (HasUMUL_LOHI) {
3111      OpToUse = ISD::UMUL_LOHI;
3112    }
3113    if (OpToUse) {
3114      Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0),
3115                                    Node->getOperand(1)));
3116      break;
3117    }
3118    Tmp1 = ExpandIntLibCall(Node, false, RTLIB::MUL_I16, RTLIB::MUL_I32,
3119                            RTLIB::MUL_I64, RTLIB::MUL_I128);
3120    Results.push_back(Tmp1);
3121    break;
3122  }
3123  case ISD::BUILD_PAIR: {
3124    MVT PairTy = Node->getValueType(0);
3125    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0));
3126    Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1));
3127    Tmp2 = DAG.getNode(ISD::SHL, dl, PairTy, Tmp2,
3128                       DAG.getConstant(PairTy.getSizeInBits()/2,
3129                                       TLI.getShiftAmountTy()));
3130    Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2));
3131    break;
3132  }
3133  case ISD::SELECT:
3134    Tmp1 = Node->getOperand(0);
3135    Tmp2 = Node->getOperand(1);
3136    Tmp3 = Node->getOperand(2);
3137    if (Tmp1.getOpcode() == ISD::SETCC) {
3138      Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1),
3139                             Tmp2, Tmp3,
3140                             cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
3141    } else {
3142      Tmp1 = DAG.getSelectCC(dl, Tmp1,
3143                             DAG.getConstant(0, Tmp1.getValueType()),
3144                             Tmp2, Tmp3, ISD::SETNE);
3145    }
3146    Results.push_back(Tmp1);
3147    break;
3148  case ISD::BRCOND:
3149    // Expand brcond's setcc into its constituent parts and create a BR_CC
3150    // Node.
3151    Tmp1 = Node->getOperand(0);
3152    Tmp2 = Node->getOperand(1);
3153    if (Tmp2.getOpcode() == ISD::SETCC) {
3154      Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other,
3155                         Tmp1, Tmp2.getOperand(2),
3156                         Tmp2.getOperand(0), Tmp2.getOperand(1),
3157                         Node->getOperand(2));
3158    } else {
3159      Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
3160                         DAG.getCondCode(ISD::SETNE), Tmp2,
3161                         DAG.getConstant(0, Tmp2.getValueType()),
3162                         Node->getOperand(2));
3163    }
3164    Results.push_back(Tmp1);
3165    break;
3166  case ISD::GLOBAL_OFFSET_TABLE:
3167  case ISD::GlobalAddress:
3168  case ISD::GlobalTLSAddress:
3169  case ISD::ExternalSymbol:
3170  case ISD::ConstantPool:
3171  case ISD::JumpTable:
3172  case ISD::INTRINSIC_W_CHAIN:
3173  case ISD::INTRINSIC_WO_CHAIN:
3174  case ISD::INTRINSIC_VOID:
3175    // FIXME: Custom lowering for these operations shouldn't return null!
3176    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
3177      Results.push_back(SDValue(Node, i));
3178    break;
3179  }
3180}
3181void SelectionDAGLegalize::PromoteNode(SDNode *Node,
3182                                       SmallVectorImpl<SDValue> &Results) {
3183  MVT OVT = Node->getValueType(0);
3184  if (Node->getOpcode() == ISD::UINT_TO_FP ||
3185      Node->getOpcode() == ISD::SINT_TO_FP) {
3186    OVT = Node->getOperand(0).getValueType();
3187  }
3188  MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3189  DebugLoc dl = Node->getDebugLoc();
3190  SDValue Tmp1, Tmp2, Tmp3;
3191  switch (Node->getOpcode()) {
3192  case ISD::CTTZ:
3193  case ISD::CTLZ:
3194  case ISD::CTPOP:
3195    // Zero extend the argument.
3196    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
3197    // Perform the larger operation.
3198    Tmp1 = DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0), Tmp1);
3199    if (Node->getOpcode() == ISD::CTTZ) {
3200      //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
3201      Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(Tmp1.getValueType()),
3202                          Tmp1, DAG.getConstant(NVT.getSizeInBits(), NVT),
3203                          ISD::SETEQ);
3204      Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2,
3205                          DAG.getConstant(OVT.getSizeInBits(), NVT), Tmp1);
3206    } else if (Node->getOpcode() == ISD::CTLZ) {
3207      // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
3208      Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
3209                          DAG.getConstant(NVT.getSizeInBits() -
3210                                          OVT.getSizeInBits(), NVT));
3211    }
3212    Results.push_back(Tmp1);
3213    break;
3214  case ISD::BSWAP: {
3215    unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
3216    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Tmp1);
3217    Tmp1 = DAG.getNode(ISD::BSWAP, dl, NVT, Tmp1);
3218    Tmp1 = DAG.getNode(ISD::SRL, dl, NVT, Tmp1,
3219                          DAG.getConstant(DiffBits, TLI.getShiftAmountTy()));
3220    Results.push_back(Tmp1);
3221    break;
3222  }
3223  case ISD::FP_TO_UINT:
3224  case ISD::FP_TO_SINT:
3225    Tmp1 = PromoteLegalFP_TO_INT(Node->getOperand(0), Node->getValueType(0),
3226                                 Node->getOpcode() == ISD::FP_TO_SINT, dl);
3227    Results.push_back(Tmp1);
3228    break;
3229  case ISD::UINT_TO_FP:
3230  case ISD::SINT_TO_FP:
3231    Tmp1 = PromoteLegalINT_TO_FP(Node->getOperand(0), Node->getValueType(0),
3232                                 Node->getOpcode() == ISD::SINT_TO_FP, dl);
3233    Results.push_back(Tmp1);
3234    break;
3235  case ISD::AND:
3236  case ISD::OR:
3237  case ISD::XOR:
3238    assert(OVT.isVector() && "Don't know how to promote scalar logic ops");
3239    // Bit convert each of the values to the new type.
3240    Tmp1 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Node->getOperand(0));
3241    Tmp2 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Node->getOperand(1));
3242    Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
3243    // Bit convert the result back the original type.
3244    Results.push_back(DAG.getNode(ISD::BIT_CONVERT, dl, OVT, Tmp1));
3245    break;
3246  case ISD::SELECT:
3247    unsigned ExtOp, TruncOp;
3248    if (Tmp2.getValueType().isVector()) {
3249      ExtOp   = ISD::BIT_CONVERT;
3250      TruncOp = ISD::BIT_CONVERT;
3251    } else if (Tmp2.getValueType().isInteger()) {
3252      ExtOp   = ISD::ANY_EXTEND;
3253      TruncOp = ISD::TRUNCATE;
3254    } else {
3255      ExtOp   = ISD::FP_EXTEND;
3256      TruncOp = ISD::FP_ROUND;
3257    }
3258    Tmp1 = Node->getOperand(0);
3259    // Promote each of the values to the new type.
3260    Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3261    Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
3262    // Perform the larger operation, then round down.
3263    Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp1, Tmp2, Tmp3);
3264    if (TruncOp != ISD::FP_ROUND)
3265      Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1);
3266    else
3267      Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1,
3268                         DAG.getIntPtrConstant(0));
3269    Results.push_back(Tmp1);
3270    break;
3271  case ISD::VECTOR_SHUFFLE: {
3272    SmallVector<int, 8> Mask;
3273    cast<ShuffleVectorSDNode>(Node)->getMask(Mask);
3274
3275    // Cast the two input vectors.
3276    Tmp1 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Node->getOperand(0));
3277    Tmp2 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Node->getOperand(1));
3278
3279    // Convert the shuffle mask to the right # elements.
3280    Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
3281    Tmp1 = DAG.getNode(ISD::BIT_CONVERT, dl, OVT, Tmp1);
3282    Results.push_back(Tmp1);
3283    break;
3284  }
3285  }
3286}
3287
3288// SelectionDAG::Legalize - This is the entry point for the file.
3289//
3290void SelectionDAG::Legalize(bool TypesNeedLegalizing,
3291                            CodeGenOpt::Level OptLevel) {
3292  /// run - This is the main entry point to this class.
3293  ///
3294  SelectionDAGLegalize(*this, OptLevel).LegalizeDAG();
3295}
3296
3297