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