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