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