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