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