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