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 ExtRes = Res;
2841     SDValue LHS = Res;
2842     SDValue RHS = Node->getOperand(1);
2843 
2844     EVT AtomicType = cast<AtomicSDNode>(Node)->getMemoryVT();
2845     EVT OuterType = Node->getValueType(0);
2846     switch (TLI.getExtendForAtomicOps()) {
2847     case ISD::SIGN_EXTEND:
2848       LHS = DAG.getNode(ISD::AssertSext, dl, OuterType, Res,
2849                         DAG.getValueType(AtomicType));
2850       RHS = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, OuterType,
2851                         Node->getOperand(2), DAG.getValueType(AtomicType));
2852       ExtRes = LHS;
2853       break;
2854     case ISD::ZERO_EXTEND:
2855       LHS = DAG.getNode(ISD::AssertZext, dl, OuterType, Res,
2856                         DAG.getValueType(AtomicType));
2857       RHS = DAG.getNode(ISD::ZERO_EXTEND, dl, OuterType, Node->getOperand(2));
2858       ExtRes = LHS;
2859       break;
2860     case ISD::ANY_EXTEND:
2861       LHS = DAG.getZeroExtendInReg(Res, dl, AtomicType);
2862       RHS = DAG.getNode(ISD::ZERO_EXTEND, dl, OuterType, Node->getOperand(2));
2863       break;
2864     default:
2865       llvm_unreachable("Invalid atomic op extension");
2866     }
2867 
2868     SDValue Success =
2869         DAG.getSetCC(dl, Node->getValueType(1), LHS, RHS, ISD::SETEQ);
2870 
2871     Results.push_back(ExtRes.getValue(0));
2872     Results.push_back(Success);
2873     Results.push_back(Res.getValue(1));
2874     break;
2875   }
2876   case ISD::DYNAMIC_STACKALLOC:
2877     ExpandDYNAMIC_STACKALLOC(Node, Results);
2878     break;
2879   case ISD::MERGE_VALUES:
2880     for (unsigned i = 0; i < Node->getNumValues(); i++)
2881       Results.push_back(Node->getOperand(i));
2882     break;
2883   case ISD::UNDEF: {
2884     EVT VT = Node->getValueType(0);
2885     if (VT.isInteger())
2886       Results.push_back(DAG.getConstant(0, dl, VT));
2887     else {
2888       assert(VT.isFloatingPoint() && "Unknown value type!");
2889       Results.push_back(DAG.getConstantFP(0, dl, VT));
2890     }
2891     break;
2892   }
2893   case ISD::FP_ROUND:
2894   case ISD::BITCAST:
2895     Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
2896                             Node->getValueType(0), dl);
2897     Results.push_back(Tmp1);
2898     break;
2899   case ISD::FP_EXTEND:
2900     Tmp1 = EmitStackConvert(Node->getOperand(0),
2901                             Node->getOperand(0).getValueType(),
2902                             Node->getValueType(0), dl);
2903     Results.push_back(Tmp1);
2904     break;
2905   case ISD::SIGN_EXTEND_INREG: {
2906     // NOTE: we could fall back on load/store here too for targets without
2907     // SAR.  However, it is doubtful that any exist.
2908     EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2909     EVT VT = Node->getValueType(0);
2910     EVT ShiftAmountTy = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
2911     if (VT.isVector())
2912       ShiftAmountTy = VT;
2913     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
2914                         ExtraVT.getScalarType().getSizeInBits();
2915     SDValue ShiftCst = DAG.getConstant(BitsDiff, dl, ShiftAmountTy);
2916     Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0),
2917                        Node->getOperand(0), ShiftCst);
2918     Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst);
2919     Results.push_back(Tmp1);
2920     break;
2921   }
2922   case ISD::FP_ROUND_INREG: {
2923     // The only way we can lower this is to turn it into a TRUNCSTORE,
2924     // EXTLOAD pair, targeting a temporary location (a stack slot).
2925 
2926     // NOTE: there is a choice here between constantly creating new stack
2927     // slots and always reusing the same one.  We currently always create
2928     // new ones, as reuse may inhibit scheduling.
2929     EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2930     Tmp1 = EmitStackConvert(Node->getOperand(0), ExtraVT,
2931                             Node->getValueType(0), dl);
2932     Results.push_back(Tmp1);
2933     break;
2934   }
2935   case ISD::SINT_TO_FP:
2936   case ISD::UINT_TO_FP:
2937     Tmp1 = ExpandLegalINT_TO_FP(Node->getOpcode() == ISD::SINT_TO_FP,
2938                                 Node->getOperand(0), Node->getValueType(0), dl);
2939     Results.push_back(Tmp1);
2940     break;
2941   case ISD::FP_TO_SINT:
2942     if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG))
2943       Results.push_back(Tmp1);
2944     break;
2945   case ISD::FP_TO_UINT: {
2946     SDValue True, False;
2947     EVT VT =  Node->getOperand(0).getValueType();
2948     EVT NVT = Node->getValueType(0);
2949     APFloat apf(DAG.EVTToAPFloatSemantics(VT),
2950                 APInt::getNullValue(VT.getSizeInBits()));
2951     APInt x = APInt::getSignBit(NVT.getSizeInBits());
2952     (void)apf.convertFromAPInt(x, false, APFloat::rmNearestTiesToEven);
2953     Tmp1 = DAG.getConstantFP(apf, dl, VT);
2954     Tmp2 = DAG.getSetCC(dl, getSetCCResultType(VT),
2955                         Node->getOperand(0),
2956                         Tmp1, ISD::SETLT);
2957     True = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, Node->getOperand(0));
2958     // TODO: Should any fast-math-flags be set for the FSUB?
2959     False = DAG.getNode(ISD::FP_TO_SINT, dl, NVT,
2960                         DAG.getNode(ISD::FSUB, dl, VT,
2961                                     Node->getOperand(0), Tmp1));
2962     False = DAG.getNode(ISD::XOR, dl, NVT, False,
2963                         DAG.getConstant(x, dl, NVT));
2964     Tmp1 = DAG.getSelect(dl, NVT, Tmp2, True, False);
2965     Results.push_back(Tmp1);
2966     break;
2967   }
2968   case ISD::VAARG:
2969     Results.push_back(DAG.expandVAArg(Node));
2970     Results.push_back(Results[0].getValue(1));
2971     break;
2972   case ISD::VACOPY:
2973     Results.push_back(DAG.expandVACopy(Node));
2974     break;
2975   case ISD::EXTRACT_VECTOR_ELT:
2976     if (Node->getOperand(0).getValueType().getVectorNumElements() == 1)
2977       // This must be an access of the only element.  Return it.
2978       Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0),
2979                          Node->getOperand(0));
2980     else
2981       Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0));
2982     Results.push_back(Tmp1);
2983     break;
2984   case ISD::EXTRACT_SUBVECTOR:
2985     Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0)));
2986     break;
2987   case ISD::INSERT_SUBVECTOR:
2988     Results.push_back(ExpandInsertToVectorThroughStack(SDValue(Node, 0)));
2989     break;
2990   case ISD::CONCAT_VECTORS: {
2991     Results.push_back(ExpandVectorBuildThroughStack(Node));
2992     break;
2993   }
2994   case ISD::SCALAR_TO_VECTOR:
2995     Results.push_back(ExpandSCALAR_TO_VECTOR(Node));
2996     break;
2997   case ISD::INSERT_VECTOR_ELT:
2998     Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0),
2999                                               Node->getOperand(1),
3000                                               Node->getOperand(2), dl));
3001     break;
3002   case ISD::VECTOR_SHUFFLE: {
3003     SmallVector<int, 32> NewMask;
3004     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
3005 
3006     EVT VT = Node->getValueType(0);
3007     EVT EltVT = VT.getVectorElementType();
3008     SDValue Op0 = Node->getOperand(0);
3009     SDValue Op1 = Node->getOperand(1);
3010     if (!TLI.isTypeLegal(EltVT)) {
3011 
3012       EVT NewEltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT);
3013 
3014       // BUILD_VECTOR operands are allowed to be wider than the element type.
3015       // But if NewEltVT is smaller that EltVT the BUILD_VECTOR does not accept
3016       // it.
3017       if (NewEltVT.bitsLT(EltVT)) {
3018 
3019         // Convert shuffle node.
3020         // If original node was v4i64 and the new EltVT is i32,
3021         // cast operands to v8i32 and re-build the mask.
3022 
3023         // Calculate new VT, the size of the new VT should be equal to original.
3024         EVT NewVT =
3025             EVT::getVectorVT(*DAG.getContext(), NewEltVT,
3026                              VT.getSizeInBits() / NewEltVT.getSizeInBits());
3027         assert(NewVT.bitsEq(VT));
3028 
3029         // cast operands to new VT
3030         Op0 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op0);
3031         Op1 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op1);
3032 
3033         // Convert the shuffle mask
3034         unsigned int factor =
3035                          NewVT.getVectorNumElements()/VT.getVectorNumElements();
3036 
3037         // EltVT gets smaller
3038         assert(factor > 0);
3039 
3040         for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
3041           if (Mask[i] < 0) {
3042             for (unsigned fi = 0; fi < factor; ++fi)
3043               NewMask.push_back(Mask[i]);
3044           }
3045           else {
3046             for (unsigned fi = 0; fi < factor; ++fi)
3047               NewMask.push_back(Mask[i]*factor+fi);
3048           }
3049         }
3050         Mask = NewMask;
3051         VT = NewVT;
3052       }
3053       EltVT = NewEltVT;
3054     }
3055     unsigned NumElems = VT.getVectorNumElements();
3056     SmallVector<SDValue, 16> Ops;
3057     for (unsigned i = 0; i != NumElems; ++i) {
3058       if (Mask[i] < 0) {
3059         Ops.push_back(DAG.getUNDEF(EltVT));
3060         continue;
3061       }
3062       unsigned Idx = Mask[i];
3063       if (Idx < NumElems)
3064         Ops.push_back(DAG.getNode(
3065             ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
3066             DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))));
3067       else
3068         Ops.push_back(DAG.getNode(
3069             ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op1,
3070             DAG.getConstant(Idx - NumElems, dl,
3071                             TLI.getVectorIdxTy(DAG.getDataLayout()))));
3072     }
3073 
3074     Tmp1 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
3075     // We may have changed the BUILD_VECTOR type. Cast it back to the Node type.
3076     Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), Tmp1);
3077     Results.push_back(Tmp1);
3078     break;
3079   }
3080   case ISD::EXTRACT_ELEMENT: {
3081     EVT OpTy = Node->getOperand(0).getValueType();
3082     if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
3083       // 1 -> Hi
3084       Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0),
3085                          DAG.getConstant(OpTy.getSizeInBits() / 2, dl,
3086                                          TLI.getShiftAmountTy(
3087                                              Node->getOperand(0).getValueType(),
3088                                              DAG.getDataLayout())));
3089       Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
3090     } else {
3091       // 0 -> Lo
3092       Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
3093                          Node->getOperand(0));
3094     }
3095     Results.push_back(Tmp1);
3096     break;
3097   }
3098   case ISD::STACKSAVE:
3099     // Expand to CopyFromReg if the target set
3100     // StackPointerRegisterToSaveRestore.
3101     if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
3102       Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP,
3103                                            Node->getValueType(0)));
3104       Results.push_back(Results[0].getValue(1));
3105     } else {
3106       Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
3107       Results.push_back(Node->getOperand(0));
3108     }
3109     break;
3110   case ISD::STACKRESTORE:
3111     // Expand to CopyToReg if the target set
3112     // StackPointerRegisterToSaveRestore.
3113     if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
3114       Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP,
3115                                          Node->getOperand(1)));
3116     } else {
3117       Results.push_back(Node->getOperand(0));
3118     }
3119     break;
3120   case ISD::GET_DYNAMIC_AREA_OFFSET:
3121     Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0)));
3122     Results.push_back(Results[0].getValue(0));
3123     break;
3124   case ISD::FCOPYSIGN:
3125     Results.push_back(ExpandFCOPYSIGN(Node));
3126     break;
3127   case ISD::FNEG:
3128     // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
3129     Tmp1 = DAG.getConstantFP(-0.0, dl, Node->getValueType(0));
3130     // TODO: If FNEG has fast-math-flags, propagate them to the FSUB.
3131     Tmp1 = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp1,
3132                        Node->getOperand(0));
3133     Results.push_back(Tmp1);
3134     break;
3135   case ISD::FABS:
3136     Results.push_back(ExpandFABS(Node));
3137     break;
3138   case ISD::SMIN:
3139   case ISD::SMAX:
3140   case ISD::UMIN:
3141   case ISD::UMAX: {
3142     // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
3143     ISD::CondCode Pred;
3144     switch (Node->getOpcode()) {
3145     default: llvm_unreachable("How did we get here?");
3146     case ISD::SMAX: Pred = ISD::SETGT; break;
3147     case ISD::SMIN: Pred = ISD::SETLT; break;
3148     case ISD::UMAX: Pred = ISD::SETUGT; break;
3149     case ISD::UMIN: Pred = ISD::SETULT; break;
3150     }
3151     Tmp1 = Node->getOperand(0);
3152     Tmp2 = Node->getOperand(1);
3153     Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp1, Tmp2, Pred);
3154     Results.push_back(Tmp1);
3155     break;
3156   }
3157 
3158   case ISD::FSIN:
3159   case ISD::FCOS: {
3160     EVT VT = Node->getValueType(0);
3161     // Turn fsin / fcos into ISD::FSINCOS node if there are a pair of fsin /
3162     // fcos which share the same operand and both are used.
3163     if ((TLI.isOperationLegalOrCustom(ISD::FSINCOS, VT) ||
3164          canCombineSinCosLibcall(Node, TLI, TM))
3165         && useSinCos(Node)) {
3166       SDVTList VTs = DAG.getVTList(VT, VT);
3167       Tmp1 = DAG.getNode(ISD::FSINCOS, dl, VTs, Node->getOperand(0));
3168       if (Node->getOpcode() == ISD::FCOS)
3169         Tmp1 = Tmp1.getValue(1);
3170       Results.push_back(Tmp1);
3171     }
3172     break;
3173   }
3174   case ISD::FMAD:
3175     llvm_unreachable("Illegal fmad should never be formed");
3176 
3177   case ISD::FP16_TO_FP:
3178     if (Node->getValueType(0) != MVT::f32) {
3179       // We can extend to types bigger than f32 in two steps without changing
3180       // the result. Since "f16 -> f32" is much more commonly available, give
3181       // CodeGen the option of emitting that before resorting to a libcall.
3182       SDValue Res =
3183           DAG.getNode(ISD::FP16_TO_FP, dl, MVT::f32, Node->getOperand(0));
3184       Results.push_back(
3185           DAG.getNode(ISD::FP_EXTEND, dl, Node->getValueType(0), Res));
3186     }
3187     break;
3188   case ISD::FP_TO_FP16:
3189     if (!TLI.useSoftFloat() && TM.Options.UnsafeFPMath) {
3190       SDValue Op = Node->getOperand(0);
3191       MVT SVT = Op.getSimpleValueType();
3192       if ((SVT == MVT::f64 || SVT == MVT::f80) &&
3193           TLI.isOperationLegalOrCustom(ISD::FP_TO_FP16, MVT::f32)) {
3194         // Under fastmath, we can expand this node into a fround followed by
3195         // a float-half conversion.
3196         SDValue FloatVal = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Op,
3197                                        DAG.getIntPtrConstant(0, dl));
3198         Results.push_back(
3199             DAG.getNode(ISD::FP_TO_FP16, dl, Node->getValueType(0), FloatVal));
3200       }
3201     }
3202     break;
3203   case ISD::ConstantFP: {
3204     ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
3205     // Check to see if this FP immediate is already legal.
3206     // If this is a legal constant, turn it into a TargetConstantFP node.
3207     if (!TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0)))
3208       Results.push_back(ExpandConstantFP(CFP, true));
3209     break;
3210   }
3211   case ISD::Constant: {
3212     ConstantSDNode *CP = cast<ConstantSDNode>(Node);
3213     Results.push_back(ExpandConstant(CP));
3214     break;
3215   }
3216   case ISD::FSUB: {
3217     EVT VT = Node->getValueType(0);
3218     if (TLI.isOperationLegalOrCustom(ISD::FADD, VT) &&
3219         TLI.isOperationLegalOrCustom(ISD::FNEG, VT)) {
3220       const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(Node)->Flags;
3221       Tmp1 = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(1));
3222       Tmp1 = DAG.getNode(ISD::FADD, dl, VT, Node->getOperand(0), Tmp1, Flags);
3223       Results.push_back(Tmp1);
3224     }
3225     break;
3226   }
3227   case ISD::SUB: {
3228     EVT VT = Node->getValueType(0);
3229     assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
3230            TLI.isOperationLegalOrCustom(ISD::XOR, VT) &&
3231            "Don't know how to expand this subtraction!");
3232     Tmp1 = DAG.getNode(ISD::XOR, dl, VT, Node->getOperand(1),
3233                DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
3234                                VT));
3235     Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp1, DAG.getConstant(1, dl, VT));
3236     Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1));
3237     break;
3238   }
3239   case ISD::UREM:
3240   case ISD::SREM: {
3241     EVT VT = Node->getValueType(0);
3242     bool isSigned = Node->getOpcode() == ISD::SREM;
3243     unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
3244     unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3245     Tmp2 = Node->getOperand(0);
3246     Tmp3 = Node->getOperand(1);
3247     if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) {
3248       SDVTList VTs = DAG.getVTList(VT, VT);
3249       Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Tmp2, Tmp3).getValue(1);
3250       Results.push_back(Tmp1);
3251     } else if (TLI.isOperationLegalOrCustom(DivOpc, VT)) {
3252       // X % Y -> X-X/Y*Y
3253       Tmp1 = DAG.getNode(DivOpc, dl, VT, Tmp2, Tmp3);
3254       Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Tmp3);
3255       Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Tmp2, Tmp1);
3256       Results.push_back(Tmp1);
3257     }
3258     break;
3259   }
3260   case ISD::UDIV:
3261   case ISD::SDIV: {
3262     bool isSigned = Node->getOpcode() == ISD::SDIV;
3263     unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3264     EVT VT = Node->getValueType(0);
3265     if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) {
3266       SDVTList VTs = DAG.getVTList(VT, VT);
3267       Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0),
3268                          Node->getOperand(1));
3269       Results.push_back(Tmp1);
3270     }
3271     break;
3272   }
3273   case ISD::MULHU:
3274   case ISD::MULHS: {
3275     unsigned ExpandOpcode = Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI :
3276                                                               ISD::SMUL_LOHI;
3277     EVT VT = Node->getValueType(0);
3278     SDVTList VTs = DAG.getVTList(VT, VT);
3279     assert(TLI.isOperationLegalOrCustom(ExpandOpcode, VT) &&
3280            "If this wasn't legal, it shouldn't have been created!");
3281     Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0),
3282                        Node->getOperand(1));
3283     Results.push_back(Tmp1.getValue(1));
3284     break;
3285   }
3286   case ISD::MUL: {
3287     EVT VT = Node->getValueType(0);
3288     SDVTList VTs = DAG.getVTList(VT, VT);
3289     // See if multiply or divide can be lowered using two-result operations.
3290     // We just need the low half of the multiply; try both the signed
3291     // and unsigned forms. If the target supports both SMUL_LOHI and
3292     // UMUL_LOHI, form a preference by checking which forms of plain
3293     // MULH it supports.
3294     bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
3295     bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
3296     bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
3297     bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
3298     unsigned OpToUse = 0;
3299     if (HasSMUL_LOHI && !HasMULHS) {
3300       OpToUse = ISD::SMUL_LOHI;
3301     } else if (HasUMUL_LOHI && !HasMULHU) {
3302       OpToUse = ISD::UMUL_LOHI;
3303     } else if (HasSMUL_LOHI) {
3304       OpToUse = ISD::SMUL_LOHI;
3305     } else if (HasUMUL_LOHI) {
3306       OpToUse = ISD::UMUL_LOHI;
3307     }
3308     if (OpToUse) {
3309       Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0),
3310                                     Node->getOperand(1)));
3311       break;
3312     }
3313 
3314     SDValue Lo, Hi;
3315     EVT HalfType = VT.getHalfSizedIntegerVT(*DAG.getContext());
3316     if (TLI.isOperationLegalOrCustom(ISD::ZERO_EXTEND, VT) &&
3317         TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND, VT) &&
3318         TLI.isOperationLegalOrCustom(ISD::SHL, VT) &&
3319         TLI.isOperationLegalOrCustom(ISD::OR, VT) &&
3320         TLI.expandMUL(Node, Lo, Hi, HalfType, DAG)) {
3321       Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
3322       Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Hi);
3323       SDValue Shift =
3324           DAG.getConstant(HalfType.getSizeInBits(), dl,
3325                           TLI.getShiftAmountTy(HalfType, DAG.getDataLayout()));
3326       Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
3327       Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi));
3328     }
3329     break;
3330   }
3331   case ISD::SADDO:
3332   case ISD::SSUBO: {
3333     SDValue LHS = Node->getOperand(0);
3334     SDValue RHS = Node->getOperand(1);
3335     SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
3336                               ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3337                               LHS, RHS);
3338     Results.push_back(Sum);
3339     EVT ResultType = Node->getValueType(1);
3340     EVT OType = getSetCCResultType(Node->getValueType(0));
3341 
3342     SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
3343 
3344     //   LHSSign -> LHS >= 0
3345     //   RHSSign -> RHS >= 0
3346     //   SumSign -> Sum >= 0
3347     //
3348     //   Add:
3349     //   Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
3350     //   Sub:
3351     //   Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
3352     //
3353     SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
3354     SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
3355     SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
3356                                       Node->getOpcode() == ISD::SADDO ?
3357                                       ISD::SETEQ : ISD::SETNE);
3358 
3359     SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
3360     SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
3361 
3362     SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
3363     Results.push_back(DAG.getBoolExtOrTrunc(Cmp, dl, ResultType, ResultType));
3364     break;
3365   }
3366   case ISD::UADDO:
3367   case ISD::USUBO: {
3368     SDValue LHS = Node->getOperand(0);
3369     SDValue RHS = Node->getOperand(1);
3370     SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::UADDO ?
3371                               ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3372                               LHS, RHS);
3373     Results.push_back(Sum);
3374 
3375     EVT ResultType = Node->getValueType(1);
3376     EVT SetCCType = getSetCCResultType(Node->getValueType(0));
3377     ISD::CondCode CC
3378       = Node->getOpcode() == ISD::UADDO ? ISD::SETULT : ISD::SETUGT;
3379     SDValue SetCC = DAG.getSetCC(dl, SetCCType, Sum, LHS, CC);
3380 
3381     Results.push_back(DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType));
3382     break;
3383   }
3384   case ISD::UMULO:
3385   case ISD::SMULO: {
3386     EVT VT = Node->getValueType(0);
3387     EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits() * 2);
3388     SDValue LHS = Node->getOperand(0);
3389     SDValue RHS = Node->getOperand(1);
3390     SDValue BottomHalf;
3391     SDValue TopHalf;
3392     static const unsigned Ops[2][3] =
3393         { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
3394           { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
3395     bool isSigned = Node->getOpcode() == ISD::SMULO;
3396     if (TLI.isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
3397       BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
3398       TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
3399     } else if (TLI.isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
3400       BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
3401                                RHS);
3402       TopHalf = BottomHalf.getValue(1);
3403     } else if (TLI.isTypeLegal(WideVT)) {
3404       LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
3405       RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
3406       Tmp1 = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
3407       BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
3408                                DAG.getIntPtrConstant(0, dl));
3409       TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
3410                             DAG.getIntPtrConstant(1, dl));
3411     } else {
3412       // We can fall back to a libcall with an illegal type for the MUL if we
3413       // have a libcall big enough.
3414       // Also, we can fall back to a division in some cases, but that's a big
3415       // performance hit in the general case.
3416       RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3417       if (WideVT == MVT::i16)
3418         LC = RTLIB::MUL_I16;
3419       else if (WideVT == MVT::i32)
3420         LC = RTLIB::MUL_I32;
3421       else if (WideVT == MVT::i64)
3422         LC = RTLIB::MUL_I64;
3423       else if (WideVT == MVT::i128)
3424         LC = RTLIB::MUL_I128;
3425       assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!");
3426 
3427       // The high part is obtained by SRA'ing all but one of the bits of low
3428       // part.
3429       unsigned LoSize = VT.getSizeInBits();
3430       SDValue HiLHS =
3431           DAG.getNode(ISD::SRA, dl, VT, RHS,
3432                       DAG.getConstant(LoSize - 1, dl,
3433                                       TLI.getPointerTy(DAG.getDataLayout())));
3434       SDValue HiRHS =
3435           DAG.getNode(ISD::SRA, dl, VT, LHS,
3436                       DAG.getConstant(LoSize - 1, dl,
3437                                       TLI.getPointerTy(DAG.getDataLayout())));
3438 
3439       // Here we're passing the 2 arguments explicitly as 4 arguments that are
3440       // pre-lowered to the correct types. This all depends upon WideVT not
3441       // being a legal type for the architecture and thus has to be split to
3442       // two arguments.
3443       SDValue Args[] = { LHS, HiLHS, RHS, HiRHS };
3444       SDValue Ret = ExpandLibCall(LC, WideVT, Args, 4, isSigned, dl);
3445       BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Ret,
3446                                DAG.getIntPtrConstant(0, dl));
3447       TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Ret,
3448                             DAG.getIntPtrConstant(1, dl));
3449       // Ret is a node with an illegal type. Because such things are not
3450       // generally permitted during this phase of legalization, make sure the
3451       // node has no more uses. The above EXTRACT_ELEMENT nodes should have been
3452       // folded.
3453       assert(Ret->use_empty() &&
3454              "Unexpected uses of illegally type from expanded lib call.");
3455     }
3456 
3457     if (isSigned) {
3458       Tmp1 = DAG.getConstant(
3459           VT.getSizeInBits() - 1, dl,
3460           TLI.getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout()));
3461       Tmp1 = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, Tmp1);
3462       TopHalf = DAG.getSetCC(dl, getSetCCResultType(VT), TopHalf, Tmp1,
3463                              ISD::SETNE);
3464     } else {
3465       TopHalf = DAG.getSetCC(dl, getSetCCResultType(VT), TopHalf,
3466                              DAG.getConstant(0, dl, VT), ISD::SETNE);
3467     }
3468     Results.push_back(BottomHalf);
3469     Results.push_back(TopHalf);
3470     break;
3471   }
3472   case ISD::BUILD_PAIR: {
3473     EVT PairTy = Node->getValueType(0);
3474     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0));
3475     Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1));
3476     Tmp2 = DAG.getNode(
3477         ISD::SHL, dl, PairTy, Tmp2,
3478         DAG.getConstant(PairTy.getSizeInBits() / 2, dl,
3479                         TLI.getShiftAmountTy(PairTy, DAG.getDataLayout())));
3480     Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2));
3481     break;
3482   }
3483   case ISD::SELECT:
3484     Tmp1 = Node->getOperand(0);
3485     Tmp2 = Node->getOperand(1);
3486     Tmp3 = Node->getOperand(2);
3487     if (Tmp1.getOpcode() == ISD::SETCC) {
3488       Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1),
3489                              Tmp2, Tmp3,
3490                              cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
3491     } else {
3492       Tmp1 = DAG.getSelectCC(dl, Tmp1,
3493                              DAG.getConstant(0, dl, Tmp1.getValueType()),
3494                              Tmp2, Tmp3, ISD::SETNE);
3495     }
3496     Results.push_back(Tmp1);
3497     break;
3498   case ISD::BR_JT: {
3499     SDValue Chain = Node->getOperand(0);
3500     SDValue Table = Node->getOperand(1);
3501     SDValue Index = Node->getOperand(2);
3502 
3503     EVT PTy = TLI.getPointerTy(DAG.getDataLayout());
3504 
3505     const DataLayout &TD = DAG.getDataLayout();
3506     unsigned EntrySize =
3507       DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
3508 
3509     Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(), Index,
3510                         DAG.getConstant(EntrySize, dl, Index.getValueType()));
3511     SDValue Addr = DAG.getNode(ISD::ADD, dl, Index.getValueType(),
3512                                Index, Table);
3513 
3514     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
3515     SDValue LD = DAG.getExtLoad(
3516         ISD::SEXTLOAD, dl, PTy, Chain, Addr,
3517         MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), MemVT,
3518         false, false, false, 0);
3519     Addr = LD;
3520     if (TM.getRelocationModel() == Reloc::PIC_) {
3521       // For PIC, the sequence is:
3522       // BRIND(load(Jumptable + index) + RelocBase)
3523       // RelocBase can be JumpTable, GOT or some sort of global base.
3524       Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr,
3525                           TLI.getPICJumpTableRelocBase(Table, DAG));
3526     }
3527     Tmp1 = DAG.getNode(ISD::BRIND, dl, MVT::Other, LD.getValue(1), Addr);
3528     Results.push_back(Tmp1);
3529     break;
3530   }
3531   case ISD::BRCOND:
3532     // Expand brcond's setcc into its constituent parts and create a BR_CC
3533     // Node.
3534     Tmp1 = Node->getOperand(0);
3535     Tmp2 = Node->getOperand(1);
3536     if (Tmp2.getOpcode() == ISD::SETCC) {
3537       Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other,
3538                          Tmp1, Tmp2.getOperand(2),
3539                          Tmp2.getOperand(0), Tmp2.getOperand(1),
3540                          Node->getOperand(2));
3541     } else {
3542       // We test only the i1 bit.  Skip the AND if UNDEF.
3543       Tmp3 = (Tmp2.isUndef()) ? Tmp2 :
3544         DAG.getNode(ISD::AND, dl, Tmp2.getValueType(), Tmp2,
3545                     DAG.getConstant(1, dl, Tmp2.getValueType()));
3546       Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
3547                          DAG.getCondCode(ISD::SETNE), Tmp3,
3548                          DAG.getConstant(0, dl, Tmp3.getValueType()),
3549                          Node->getOperand(2));
3550     }
3551     Results.push_back(Tmp1);
3552     break;
3553   case ISD::SETCC: {
3554     Tmp1 = Node->getOperand(0);
3555     Tmp2 = Node->getOperand(1);
3556     Tmp3 = Node->getOperand(2);
3557     bool Legalized = LegalizeSetCCCondCode(Node->getValueType(0), Tmp1, Tmp2,
3558                                            Tmp3, NeedInvert, dl);
3559 
3560     if (Legalized) {
3561       // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
3562       // condition code, create a new SETCC node.
3563       if (Tmp3.getNode())
3564         Tmp1 = DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
3565                            Tmp1, Tmp2, Tmp3);
3566 
3567       // If we expanded the SETCC by inverting the condition code, then wrap
3568       // the existing SETCC in a NOT to restore the intended condition.
3569       if (NeedInvert)
3570         Tmp1 = DAG.getLogicalNOT(dl, Tmp1, Tmp1->getValueType(0));
3571 
3572       Results.push_back(Tmp1);
3573       break;
3574     }
3575 
3576     // Otherwise, SETCC for the given comparison type must be completely
3577     // illegal; expand it into a SELECT_CC.
3578     EVT VT = Node->getValueType(0);
3579     int TrueValue;
3580     switch (TLI.getBooleanContents(Tmp1->getValueType(0))) {
3581     case TargetLowering::ZeroOrOneBooleanContent:
3582     case TargetLowering::UndefinedBooleanContent:
3583       TrueValue = 1;
3584       break;
3585     case TargetLowering::ZeroOrNegativeOneBooleanContent:
3586       TrueValue = -1;
3587       break;
3588     }
3589     Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
3590                        DAG.getConstant(TrueValue, dl, VT),
3591                        DAG.getConstant(0, dl, VT),
3592                        Tmp3);
3593     Results.push_back(Tmp1);
3594     break;
3595   }
3596   case ISD::SELECT_CC: {
3597     Tmp1 = Node->getOperand(0);   // LHS
3598     Tmp2 = Node->getOperand(1);   // RHS
3599     Tmp3 = Node->getOperand(2);   // True
3600     Tmp4 = Node->getOperand(3);   // False
3601     EVT VT = Node->getValueType(0);
3602     SDValue CC = Node->getOperand(4);
3603     ISD::CondCode CCOp = cast<CondCodeSDNode>(CC)->get();
3604 
3605     if (TLI.isCondCodeLegal(CCOp, Tmp1.getSimpleValueType())) {
3606       // If the condition code is legal, then we need to expand this
3607       // node using SETCC and SELECT.
3608       EVT CmpVT = Tmp1.getValueType();
3609       assert(!TLI.isOperationExpand(ISD::SELECT, VT) &&
3610              "Cannot expand ISD::SELECT_CC when ISD::SELECT also needs to be "
3611              "expanded.");
3612       EVT CCVT =
3613           TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT);
3614       SDValue Cond = DAG.getNode(ISD::SETCC, dl, CCVT, Tmp1, Tmp2, CC);
3615       Results.push_back(DAG.getSelect(dl, VT, Cond, Tmp3, Tmp4));
3616       break;
3617     }
3618 
3619     // SELECT_CC is legal, so the condition code must not be.
3620     bool Legalized = false;
3621     // Try to legalize by inverting the condition.  This is for targets that
3622     // might support an ordered version of a condition, but not the unordered
3623     // version (or vice versa).
3624     ISD::CondCode InvCC = ISD::getSetCCInverse(CCOp,
3625                                                Tmp1.getValueType().isInteger());
3626     if (TLI.isCondCodeLegal(InvCC, Tmp1.getSimpleValueType())) {
3627       // Use the new condition code and swap true and false
3628       Legalized = true;
3629       Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp4, Tmp3, InvCC);
3630     } else {
3631       // If The inverse is not legal, then try to swap the arguments using
3632       // the inverse condition code.
3633       ISD::CondCode SwapInvCC = ISD::getSetCCSwappedOperands(InvCC);
3634       if (TLI.isCondCodeLegal(SwapInvCC, Tmp1.getSimpleValueType())) {
3635         // The swapped inverse condition is legal, so swap true and false,
3636         // lhs and rhs.
3637         Legalized = true;
3638         Tmp1 = DAG.getSelectCC(dl, Tmp2, Tmp1, Tmp4, Tmp3, SwapInvCC);
3639       }
3640     }
3641 
3642     if (!Legalized) {
3643       Legalized = LegalizeSetCCCondCode(
3644           getSetCCResultType(Tmp1.getValueType()), Tmp1, Tmp2, CC, NeedInvert,
3645           dl);
3646 
3647       assert(Legalized && "Can't legalize SELECT_CC with legal condition!");
3648 
3649       // If we expanded the SETCC by inverting the condition code, then swap
3650       // the True/False operands to match.
3651       if (NeedInvert)
3652         std::swap(Tmp3, Tmp4);
3653 
3654       // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
3655       // condition code, create a new SELECT_CC node.
3656       if (CC.getNode()) {
3657         Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0),
3658                            Tmp1, Tmp2, Tmp3, Tmp4, CC);
3659       } else {
3660         Tmp2 = DAG.getConstant(0, dl, Tmp1.getValueType());
3661         CC = DAG.getCondCode(ISD::SETNE);
3662         Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1,
3663                            Tmp2, Tmp3, Tmp4, CC);
3664       }
3665     }
3666     Results.push_back(Tmp1);
3667     break;
3668   }
3669   case ISD::BR_CC: {
3670     Tmp1 = Node->getOperand(0);              // Chain
3671     Tmp2 = Node->getOperand(2);              // LHS
3672     Tmp3 = Node->getOperand(3);              // RHS
3673     Tmp4 = Node->getOperand(1);              // CC
3674 
3675     bool Legalized = LegalizeSetCCCondCode(getSetCCResultType(
3676         Tmp2.getValueType()), Tmp2, Tmp3, Tmp4, NeedInvert, dl);
3677     (void)Legalized;
3678     assert(Legalized && "Can't legalize BR_CC with legal condition!");
3679 
3680     // If we expanded the SETCC by inverting the condition code, then wrap
3681     // the existing SETCC in a NOT to restore the intended condition.
3682     if (NeedInvert)
3683       Tmp4 = DAG.getNOT(dl, Tmp4, Tmp4->getValueType(0));
3684 
3685     // If we expanded the SETCC by swapping LHS and RHS, create a new BR_CC
3686     // node.
3687     if (Tmp4.getNode()) {
3688       Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1,
3689                          Tmp4, Tmp2, Tmp3, Node->getOperand(4));
3690     } else {
3691       Tmp3 = DAG.getConstant(0, dl, Tmp2.getValueType());
3692       Tmp4 = DAG.getCondCode(ISD::SETNE);
3693       Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4,
3694                          Tmp2, Tmp3, Node->getOperand(4));
3695     }
3696     Results.push_back(Tmp1);
3697     break;
3698   }
3699   case ISD::BUILD_VECTOR:
3700     Results.push_back(ExpandBUILD_VECTOR(Node));
3701     break;
3702   case ISD::SRA:
3703   case ISD::SRL:
3704   case ISD::SHL: {
3705     // Scalarize vector SRA/SRL/SHL.
3706     EVT VT = Node->getValueType(0);
3707     assert(VT.isVector() && "Unable to legalize non-vector shift");
3708     assert(TLI.isTypeLegal(VT.getScalarType())&& "Element type must be legal");
3709     unsigned NumElem = VT.getVectorNumElements();
3710 
3711     SmallVector<SDValue, 8> Scalars;
3712     for (unsigned Idx = 0; Idx < NumElem; Idx++) {
3713       SDValue Ex = DAG.getNode(
3714           ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(), Node->getOperand(0),
3715           DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
3716       SDValue Sh = DAG.getNode(
3717           ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(), Node->getOperand(1),
3718           DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
3719       Scalars.push_back(DAG.getNode(Node->getOpcode(), dl,
3720                                     VT.getScalarType(), Ex, Sh));
3721     }
3722     SDValue Result =
3723       DAG.getNode(ISD::BUILD_VECTOR, dl, Node->getValueType(0), Scalars);
3724     ReplaceNode(SDValue(Node, 0), Result);
3725     break;
3726   }
3727   case ISD::GLOBAL_OFFSET_TABLE:
3728   case ISD::GlobalAddress:
3729   case ISD::GlobalTLSAddress:
3730   case ISD::ExternalSymbol:
3731   case ISD::ConstantPool:
3732   case ISD::JumpTable:
3733   case ISD::INTRINSIC_W_CHAIN:
3734   case ISD::INTRINSIC_WO_CHAIN:
3735   case ISD::INTRINSIC_VOID:
3736     // FIXME: Custom lowering for these operations shouldn't return null!
3737     break;
3738   }
3739 
3740   // Replace the original node with the legalized result.
3741   if (Results.empty())
3742     return false;
3743 
3744   ReplaceNode(Node, Results.data());
3745   return true;
3746 }
3747 
3748 void SelectionDAGLegalize::ConvertNodeToLibcall(SDNode *Node) {
3749   SmallVector<SDValue, 8> Results;
3750   SDLoc dl(Node);
3751   SDValue Tmp1, Tmp2, Tmp3, Tmp4;
3752   unsigned Opc = Node->getOpcode();
3753   switch (Opc) {
3754   case ISD::ATOMIC_FENCE: {
3755     // If the target didn't lower this, lower it to '__sync_synchronize()' call
3756     // FIXME: handle "fence singlethread" more efficiently.
3757     TargetLowering::ArgListTy Args;
3758 
3759     TargetLowering::CallLoweringInfo CLI(DAG);
3760     CLI.setDebugLoc(dl)
3761         .setChain(Node->getOperand(0))
3762         .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3763                    DAG.getExternalSymbol("__sync_synchronize",
3764                                          TLI.getPointerTy(DAG.getDataLayout())),
3765                    std::move(Args), 0);
3766 
3767     std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
3768 
3769     Results.push_back(CallResult.second);
3770     break;
3771   }
3772   // By default, atomic intrinsics are marked Legal and lowered. Targets
3773   // which don't support them directly, however, may want libcalls, in which
3774   // case they mark them Expand, and we get here.
3775   case ISD::ATOMIC_SWAP:
3776   case ISD::ATOMIC_LOAD_ADD:
3777   case ISD::ATOMIC_LOAD_SUB:
3778   case ISD::ATOMIC_LOAD_AND:
3779   case ISD::ATOMIC_LOAD_OR:
3780   case ISD::ATOMIC_LOAD_XOR:
3781   case ISD::ATOMIC_LOAD_NAND:
3782   case ISD::ATOMIC_LOAD_MIN:
3783   case ISD::ATOMIC_LOAD_MAX:
3784   case ISD::ATOMIC_LOAD_UMIN:
3785   case ISD::ATOMIC_LOAD_UMAX:
3786   case ISD::ATOMIC_CMP_SWAP: {
3787     MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
3788     RTLIB::Libcall LC = RTLIB::getSYNC(Opc, VT);
3789     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected atomic op or value type!");
3790 
3791     std::pair<SDValue, SDValue> Tmp = ExpandChainLibCall(LC, Node, false);
3792     Results.push_back(Tmp.first);
3793     Results.push_back(Tmp.second);
3794     break;
3795   }
3796   case ISD::TRAP: {
3797     // If this operation is not supported, lower it to 'abort()' call
3798     TargetLowering::ArgListTy Args;
3799     TargetLowering::CallLoweringInfo CLI(DAG);
3800     CLI.setDebugLoc(dl)
3801         .setChain(Node->getOperand(0))
3802         .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3803                    DAG.getExternalSymbol("abort",
3804                                          TLI.getPointerTy(DAG.getDataLayout())),
3805                    std::move(Args), 0);
3806     std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
3807 
3808     Results.push_back(CallResult.second);
3809     break;
3810   }
3811   case ISD::FMINNUM:
3812     Results.push_back(ExpandFPLibCall(Node, RTLIB::FMIN_F32, RTLIB::FMIN_F64,
3813                                       RTLIB::FMIN_F80, RTLIB::FMIN_F128,
3814                                       RTLIB::FMIN_PPCF128));
3815     break;
3816   case ISD::FMAXNUM:
3817     Results.push_back(ExpandFPLibCall(Node, RTLIB::FMAX_F32, RTLIB::FMAX_F64,
3818                                       RTLIB::FMAX_F80, RTLIB::FMAX_F128,
3819                                       RTLIB::FMAX_PPCF128));
3820     break;
3821   case ISD::FSQRT:
3822     Results.push_back(ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
3823                                       RTLIB::SQRT_F80, RTLIB::SQRT_F128,
3824                                       RTLIB::SQRT_PPCF128));
3825     break;
3826   case ISD::FSIN:
3827     Results.push_back(ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64,
3828                                       RTLIB::SIN_F80, RTLIB::SIN_F128,
3829                                       RTLIB::SIN_PPCF128));
3830     break;
3831   case ISD::FCOS:
3832     Results.push_back(ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64,
3833                                       RTLIB::COS_F80, RTLIB::COS_F128,
3834                                       RTLIB::COS_PPCF128));
3835     break;
3836   case ISD::FSINCOS:
3837     // Expand into sincos libcall.
3838     ExpandSinCosLibCall(Node, Results);
3839     break;
3840   case ISD::FLOG:
3841     Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64,
3842                                       RTLIB::LOG_F80, RTLIB::LOG_F128,
3843                                       RTLIB::LOG_PPCF128));
3844     break;
3845   case ISD::FLOG2:
3846     Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
3847                                       RTLIB::LOG2_F80, RTLIB::LOG2_F128,
3848                                       RTLIB::LOG2_PPCF128));
3849     break;
3850   case ISD::FLOG10:
3851     Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
3852                                       RTLIB::LOG10_F80, RTLIB::LOG10_F128,
3853                                       RTLIB::LOG10_PPCF128));
3854     break;
3855   case ISD::FEXP:
3856     Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64,
3857                                       RTLIB::EXP_F80, RTLIB::EXP_F128,
3858                                       RTLIB::EXP_PPCF128));
3859     break;
3860   case ISD::FEXP2:
3861     Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
3862                                       RTLIB::EXP2_F80, RTLIB::EXP2_F128,
3863                                       RTLIB::EXP2_PPCF128));
3864     break;
3865   case ISD::FTRUNC:
3866     Results.push_back(ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
3867                                       RTLIB::TRUNC_F80, RTLIB::TRUNC_F128,
3868                                       RTLIB::TRUNC_PPCF128));
3869     break;
3870   case ISD::FFLOOR:
3871     Results.push_back(ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
3872                                       RTLIB::FLOOR_F80, RTLIB::FLOOR_F128,
3873                                       RTLIB::FLOOR_PPCF128));
3874     break;
3875   case ISD::FCEIL:
3876     Results.push_back(ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
3877                                       RTLIB::CEIL_F80, RTLIB::CEIL_F128,
3878                                       RTLIB::CEIL_PPCF128));
3879     break;
3880   case ISD::FRINT:
3881     Results.push_back(ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64,
3882                                       RTLIB::RINT_F80, RTLIB::RINT_F128,
3883                                       RTLIB::RINT_PPCF128));
3884     break;
3885   case ISD::FNEARBYINT:
3886     Results.push_back(ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32,
3887                                       RTLIB::NEARBYINT_F64,
3888                                       RTLIB::NEARBYINT_F80,
3889                                       RTLIB::NEARBYINT_F128,
3890                                       RTLIB::NEARBYINT_PPCF128));
3891     break;
3892   case ISD::FROUND:
3893     Results.push_back(ExpandFPLibCall(Node, RTLIB::ROUND_F32,
3894                                       RTLIB::ROUND_F64,
3895                                       RTLIB::ROUND_F80,
3896                                       RTLIB::ROUND_F128,
3897                                       RTLIB::ROUND_PPCF128));
3898     break;
3899   case ISD::FPOWI:
3900     Results.push_back(ExpandFPLibCall(Node, RTLIB::POWI_F32, RTLIB::POWI_F64,
3901                                       RTLIB::POWI_F80, RTLIB::POWI_F128,
3902                                       RTLIB::POWI_PPCF128));
3903     break;
3904   case ISD::FPOW:
3905     Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64,
3906                                       RTLIB::POW_F80, RTLIB::POW_F128,
3907                                       RTLIB::POW_PPCF128));
3908     break;
3909   case ISD::FDIV:
3910     Results.push_back(ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64,
3911                                       RTLIB::DIV_F80, RTLIB::DIV_F128,
3912                                       RTLIB::DIV_PPCF128));
3913     break;
3914   case ISD::FREM:
3915     Results.push_back(ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64,
3916                                       RTLIB::REM_F80, RTLIB::REM_F128,
3917                                       RTLIB::REM_PPCF128));
3918     break;
3919   case ISD::FMA:
3920     Results.push_back(ExpandFPLibCall(Node, RTLIB::FMA_F32, RTLIB::FMA_F64,
3921                                       RTLIB::FMA_F80, RTLIB::FMA_F128,
3922                                       RTLIB::FMA_PPCF128));
3923     break;
3924   case ISD::FADD:
3925     Results.push_back(ExpandFPLibCall(Node, RTLIB::ADD_F32, RTLIB::ADD_F64,
3926                                       RTLIB::ADD_F80, RTLIB::ADD_F128,
3927                                       RTLIB::ADD_PPCF128));
3928     break;
3929   case ISD::FMUL:
3930     Results.push_back(ExpandFPLibCall(Node, RTLIB::MUL_F32, RTLIB::MUL_F64,
3931                                       RTLIB::MUL_F80, RTLIB::MUL_F128,
3932                                       RTLIB::MUL_PPCF128));
3933     break;
3934   case ISD::FP16_TO_FP:
3935     if (Node->getValueType(0) == MVT::f32) {
3936       Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false));
3937     }
3938     break;
3939   case ISD::FP_TO_FP16: {
3940     RTLIB::Libcall LC =
3941         RTLIB::getFPROUND(Node->getOperand(0).getValueType(), MVT::f16);
3942     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to expand fp_to_fp16");
3943     Results.push_back(ExpandLibCall(LC, Node, false));
3944     break;
3945   }
3946   case ISD::FSUB:
3947     Results.push_back(ExpandFPLibCall(Node, RTLIB::SUB_F32, RTLIB::SUB_F64,
3948                                       RTLIB::SUB_F80, RTLIB::SUB_F128,
3949                                       RTLIB::SUB_PPCF128));
3950     break;
3951   case ISD::SREM:
3952     Results.push_back(ExpandIntLibCall(Node, true,
3953                                        RTLIB::SREM_I8,
3954                                        RTLIB::SREM_I16, RTLIB::SREM_I32,
3955                                        RTLIB::SREM_I64, RTLIB::SREM_I128));
3956     break;
3957   case ISD::UREM:
3958     Results.push_back(ExpandIntLibCall(Node, false,
3959                                        RTLIB::UREM_I8,
3960                                        RTLIB::UREM_I16, RTLIB::UREM_I32,
3961                                        RTLIB::UREM_I64, RTLIB::UREM_I128));
3962     break;
3963   case ISD::SDIV:
3964     Results.push_back(ExpandIntLibCall(Node, true,
3965                                        RTLIB::SDIV_I8,
3966                                        RTLIB::SDIV_I16, RTLIB::SDIV_I32,
3967                                        RTLIB::SDIV_I64, RTLIB::SDIV_I128));
3968     break;
3969   case ISD::UDIV:
3970     Results.push_back(ExpandIntLibCall(Node, false,
3971                                        RTLIB::UDIV_I8,
3972                                        RTLIB::UDIV_I16, RTLIB::UDIV_I32,
3973                                        RTLIB::UDIV_I64, RTLIB::UDIV_I128));
3974     break;
3975   case ISD::SDIVREM:
3976   case ISD::UDIVREM:
3977     // Expand into divrem libcall
3978     ExpandDivRemLibCall(Node, Results);
3979     break;
3980   case ISD::MUL:
3981     Results.push_back(ExpandIntLibCall(Node, false,
3982                                        RTLIB::MUL_I8,
3983                                        RTLIB::MUL_I16, RTLIB::MUL_I32,
3984                                        RTLIB::MUL_I64, RTLIB::MUL_I128));
3985     break;
3986   }
3987 
3988   // Replace the original node with the legalized result.
3989   if (!Results.empty())
3990     ReplaceNode(Node, Results.data());
3991 }
3992 
3993 // Determine the vector type to use in place of an original scalar element when
3994 // promoting equally sized vectors.
3995 static MVT getPromotedVectorElementType(const TargetLowering &TLI,
3996                                         MVT EltVT, MVT NewEltVT) {
3997   unsigned OldEltsPerNewElt = EltVT.getSizeInBits() / NewEltVT.getSizeInBits();
3998   MVT MidVT = MVT::getVectorVT(NewEltVT, OldEltsPerNewElt);
3999   assert(TLI.isTypeLegal(MidVT) && "unexpected");
4000   return MidVT;
4001 }
4002 
4003 void SelectionDAGLegalize::PromoteNode(SDNode *Node) {
4004   SmallVector<SDValue, 8> Results;
4005   MVT OVT = Node->getSimpleValueType(0);
4006   if (Node->getOpcode() == ISD::UINT_TO_FP ||
4007       Node->getOpcode() == ISD::SINT_TO_FP ||
4008       Node->getOpcode() == ISD::SETCC ||
4009       Node->getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
4010       Node->getOpcode() == ISD::INSERT_VECTOR_ELT) {
4011     OVT = Node->getOperand(0).getSimpleValueType();
4012   }
4013   if (Node->getOpcode() == ISD::BR_CC)
4014     OVT = Node->getOperand(2).getSimpleValueType();
4015   MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
4016   SDLoc dl(Node);
4017   SDValue Tmp1, Tmp2, Tmp3;
4018   switch (Node->getOpcode()) {
4019   case ISD::CTTZ:
4020   case ISD::CTTZ_ZERO_UNDEF:
4021   case ISD::CTLZ:
4022   case ISD::CTLZ_ZERO_UNDEF:
4023   case ISD::CTPOP:
4024     // Zero extend the argument.
4025     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
4026     if (Node->getOpcode() == ISD::CTTZ) {
4027       // The count is the same in the promoted type except if the original
4028       // value was zero.  This can be handled by setting the bit just off
4029       // the top of the original type.
4030       auto TopBit = APInt::getOneBitSet(NVT.getSizeInBits(),
4031                                         OVT.getSizeInBits());
4032       Tmp1 = DAG.getNode(ISD::OR, dl, NVT, Tmp1,
4033                          DAG.getConstant(TopBit, dl, NVT));
4034     }
4035     // Perform the larger operation. For CTPOP and CTTZ_ZERO_UNDEF, this is
4036     // already the correct result.
4037     Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4038     if (Node->getOpcode() == ISD::CTLZ ||
4039         Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF) {
4040       // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
4041       Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
4042                           DAG.getConstant(NVT.getSizeInBits() -
4043                                           OVT.getSizeInBits(), dl, NVT));
4044     }
4045     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
4046     break;
4047   case ISD::BSWAP: {
4048     unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
4049     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
4050     Tmp1 = DAG.getNode(ISD::BSWAP, dl, NVT, Tmp1);
4051     Tmp1 = DAG.getNode(
4052         ISD::SRL, dl, NVT, Tmp1,
4053         DAG.getConstant(DiffBits, dl,
4054                         TLI.getShiftAmountTy(NVT, DAG.getDataLayout())));
4055     Results.push_back(Tmp1);
4056     break;
4057   }
4058   case ISD::FP_TO_UINT:
4059   case ISD::FP_TO_SINT:
4060     Tmp1 = PromoteLegalFP_TO_INT(Node->getOperand(0), Node->getValueType(0),
4061                                  Node->getOpcode() == ISD::FP_TO_SINT, dl);
4062     Results.push_back(Tmp1);
4063     break;
4064   case ISD::UINT_TO_FP:
4065   case ISD::SINT_TO_FP:
4066     Tmp1 = PromoteLegalINT_TO_FP(Node->getOperand(0), Node->getValueType(0),
4067                                  Node->getOpcode() == ISD::SINT_TO_FP, dl);
4068     Results.push_back(Tmp1);
4069     break;
4070   case ISD::VAARG: {
4071     SDValue Chain = Node->getOperand(0); // Get the chain.
4072     SDValue Ptr = Node->getOperand(1); // Get the pointer.
4073 
4074     unsigned TruncOp;
4075     if (OVT.isVector()) {
4076       TruncOp = ISD::BITCAST;
4077     } else {
4078       assert(OVT.isInteger()
4079         && "VAARG promotion is supported only for vectors or integer types");
4080       TruncOp = ISD::TRUNCATE;
4081     }
4082 
4083     // Perform the larger operation, then convert back
4084     Tmp1 = DAG.getVAArg(NVT, dl, Chain, Ptr, Node->getOperand(2),
4085              Node->getConstantOperandVal(3));
4086     Chain = Tmp1.getValue(1);
4087 
4088     Tmp2 = DAG.getNode(TruncOp, dl, OVT, Tmp1);
4089 
4090     // Modified the chain result - switch anything that used the old chain to
4091     // use the new one.
4092     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Tmp2);
4093     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
4094     if (UpdatedNodes) {
4095       UpdatedNodes->insert(Tmp2.getNode());
4096       UpdatedNodes->insert(Chain.getNode());
4097     }
4098     ReplacedNode(Node);
4099     break;
4100   }
4101   case ISD::AND:
4102   case ISD::OR:
4103   case ISD::XOR: {
4104     unsigned ExtOp, TruncOp;
4105     if (OVT.isVector()) {
4106       ExtOp   = ISD::BITCAST;
4107       TruncOp = ISD::BITCAST;
4108     } else {
4109       assert(OVT.isInteger() && "Cannot promote logic operation");
4110       ExtOp   = ISD::ANY_EXTEND;
4111       TruncOp = ISD::TRUNCATE;
4112     }
4113     // Promote each of the values to the new type.
4114     Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4115     Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4116     // Perform the larger operation, then convert back
4117     Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4118     Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1));
4119     break;
4120   }
4121   case ISD::SELECT: {
4122     unsigned ExtOp, TruncOp;
4123     if (Node->getValueType(0).isVector() ||
4124         Node->getValueType(0).getSizeInBits() == NVT.getSizeInBits()) {
4125       ExtOp   = ISD::BITCAST;
4126       TruncOp = ISD::BITCAST;
4127     } else if (Node->getValueType(0).isInteger()) {
4128       ExtOp   = ISD::ANY_EXTEND;
4129       TruncOp = ISD::TRUNCATE;
4130     } else {
4131       ExtOp   = ISD::FP_EXTEND;
4132       TruncOp = ISD::FP_ROUND;
4133     }
4134     Tmp1 = Node->getOperand(0);
4135     // Promote each of the values to the new type.
4136     Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4137     Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
4138     // Perform the larger operation, then round down.
4139     Tmp1 = DAG.getSelect(dl, NVT, Tmp1, Tmp2, Tmp3);
4140     if (TruncOp != ISD::FP_ROUND)
4141       Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1);
4142     else
4143       Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1,
4144                          DAG.getIntPtrConstant(0, dl));
4145     Results.push_back(Tmp1);
4146     break;
4147   }
4148   case ISD::VECTOR_SHUFFLE: {
4149     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
4150 
4151     // Cast the two input vectors.
4152     Tmp1 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0));
4153     Tmp2 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(1));
4154 
4155     // Convert the shuffle mask to the right # elements.
4156     Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
4157     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OVT, Tmp1);
4158     Results.push_back(Tmp1);
4159     break;
4160   }
4161   case ISD::SETCC: {
4162     unsigned ExtOp = ISD::FP_EXTEND;
4163     if (NVT.isInteger()) {
4164       ISD::CondCode CCCode =
4165         cast<CondCodeSDNode>(Node->getOperand(2))->get();
4166       ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4167     }
4168     Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4169     Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4170     Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
4171                                   Tmp1, Tmp2, Node->getOperand(2)));
4172     break;
4173   }
4174   case ISD::BR_CC: {
4175     unsigned ExtOp = ISD::FP_EXTEND;
4176     if (NVT.isInteger()) {
4177       ISD::CondCode CCCode =
4178         cast<CondCodeSDNode>(Node->getOperand(1))->get();
4179       ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4180     }
4181     Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
4182     Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(3));
4183     Results.push_back(DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0),
4184                                   Node->getOperand(0), Node->getOperand(1),
4185                                   Tmp1, Tmp2, Node->getOperand(4)));
4186     break;
4187   }
4188   case ISD::FADD:
4189   case ISD::FSUB:
4190   case ISD::FMUL:
4191   case ISD::FDIV:
4192   case ISD::FREM:
4193   case ISD::FMINNUM:
4194   case ISD::FMAXNUM:
4195   case ISD::FPOW: {
4196     Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4197     Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
4198     Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2,
4199                        Node->getFlags());
4200     Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4201                                   Tmp3, DAG.getIntPtrConstant(0, dl)));
4202     break;
4203   }
4204   case ISD::FMA: {
4205     Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4206     Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
4207     Tmp3 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(2));
4208     Results.push_back(
4209         DAG.getNode(ISD::FP_ROUND, dl, OVT,
4210                     DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2, Tmp3),
4211                     DAG.getIntPtrConstant(0, dl)));
4212     break;
4213   }
4214   case ISD::FCOPYSIGN:
4215   case ISD::FPOWI: {
4216     Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4217     Tmp2 = Node->getOperand(1);
4218     Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4219 
4220     // fcopysign doesn't change anything but the sign bit, so
4221     //   (fp_round (fcopysign (fpext a), b))
4222     // is as precise as
4223     //   (fp_round (fpext a))
4224     // which is a no-op. Mark it as a TRUNCating FP_ROUND.
4225     const bool isTrunc = (Node->getOpcode() == ISD::FCOPYSIGN);
4226     Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4227                                   Tmp3, DAG.getIntPtrConstant(isTrunc, dl)));
4228     break;
4229   }
4230   case ISD::FFLOOR:
4231   case ISD::FCEIL:
4232   case ISD::FRINT:
4233   case ISD::FNEARBYINT:
4234   case ISD::FROUND:
4235   case ISD::FTRUNC:
4236   case ISD::FNEG:
4237   case ISD::FSQRT:
4238   case ISD::FSIN:
4239   case ISD::FCOS:
4240   case ISD::FLOG:
4241   case ISD::FLOG2:
4242   case ISD::FLOG10:
4243   case ISD::FABS:
4244   case ISD::FEXP:
4245   case ISD::FEXP2: {
4246     Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4247     Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4248     Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4249                                   Tmp2, DAG.getIntPtrConstant(0, dl)));
4250     break;
4251   }
4252   case ISD::BUILD_VECTOR: {
4253     MVT EltVT = OVT.getVectorElementType();
4254     MVT NewEltVT = NVT.getVectorElementType();
4255 
4256     // Handle bitcasts to a different vector type with the same total bit size
4257     //
4258     // e.g. v2i64 = build_vector i64:x, i64:y => v4i32
4259     //  =>
4260     //  v4i32 = concat_vectors (v2i32 (bitcast i64:x)), (v2i32 (bitcast i64:y))
4261 
4262     assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
4263            "Invalid promote type for build_vector");
4264     assert(NewEltVT.bitsLT(EltVT) && "not handled");
4265 
4266     MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4267 
4268     SmallVector<SDValue, 8> NewOps;
4269     for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) {
4270       SDValue Op = Node->getOperand(I);
4271       NewOps.push_back(DAG.getNode(ISD::BITCAST, SDLoc(Op), MidVT, Op));
4272     }
4273 
4274     SDLoc SL(Node);
4275     SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewOps);
4276     SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat);
4277     Results.push_back(CvtVec);
4278     break;
4279   }
4280   case ISD::EXTRACT_VECTOR_ELT: {
4281     MVT EltVT = OVT.getVectorElementType();
4282     MVT NewEltVT = NVT.getVectorElementType();
4283 
4284     // Handle bitcasts to a different vector type with the same total bit size.
4285     //
4286     // e.g. v2i64 = extract_vector_elt x:v2i64, y:i32
4287     //  =>
4288     //  v4i32:castx = bitcast x:v2i64
4289     //
4290     // i64 = bitcast
4291     //   (v2i32 build_vector (i32 (extract_vector_elt castx, (2 * y))),
4292     //                       (i32 (extract_vector_elt castx, (2 * y + 1)))
4293     //
4294 
4295     assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
4296            "Invalid promote type for extract_vector_elt");
4297     assert(NewEltVT.bitsLT(EltVT) && "not handled");
4298 
4299     MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4300     unsigned NewEltsPerOldElt = MidVT.getVectorNumElements();
4301 
4302     SDValue Idx = Node->getOperand(1);
4303     EVT IdxVT = Idx.getValueType();
4304     SDLoc SL(Node);
4305     SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SL, IdxVT);
4306     SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor);
4307 
4308     SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0));
4309 
4310     SmallVector<SDValue, 8> NewOps;
4311     for (unsigned I = 0; I < NewEltsPerOldElt; ++I) {
4312       SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT);
4313       SDValue TmpIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset);
4314 
4315       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT,
4316                                 CastVec, TmpIdx);
4317       NewOps.push_back(Elt);
4318     }
4319 
4320     SDValue NewVec = DAG.getNode(ISD::BUILD_VECTOR, SL, MidVT, NewOps);
4321 
4322     Results.push_back(DAG.getNode(ISD::BITCAST, SL, EltVT, NewVec));
4323     break;
4324   }
4325   case ISD::INSERT_VECTOR_ELT: {
4326     MVT EltVT = OVT.getVectorElementType();
4327     MVT NewEltVT = NVT.getVectorElementType();
4328 
4329     // Handle bitcasts to a different vector type with the same total bit size
4330     //
4331     // e.g. v2i64 = insert_vector_elt x:v2i64, y:i64, z:i32
4332     //  =>
4333     //  v4i32:castx = bitcast x:v2i64
4334     //  v2i32:casty = bitcast y:i64
4335     //
4336     // v2i64 = bitcast
4337     //   (v4i32 insert_vector_elt
4338     //       (v4i32 insert_vector_elt v4i32:castx,
4339     //                                (extract_vector_elt casty, 0), 2 * z),
4340     //        (extract_vector_elt casty, 1), (2 * z + 1))
4341 
4342     assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
4343            "Invalid promote type for insert_vector_elt");
4344     assert(NewEltVT.bitsLT(EltVT) && "not handled");
4345 
4346     MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4347     unsigned NewEltsPerOldElt = MidVT.getVectorNumElements();
4348 
4349     SDValue Val = Node->getOperand(1);
4350     SDValue Idx = Node->getOperand(2);
4351     EVT IdxVT = Idx.getValueType();
4352     SDLoc SL(Node);
4353 
4354     SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SDLoc(), IdxVT);
4355     SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor);
4356 
4357     SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0));
4358     SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val);
4359 
4360     SDValue NewVec = CastVec;
4361     for (unsigned I = 0; I < NewEltsPerOldElt; ++I) {
4362       SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT);
4363       SDValue InEltIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset);
4364 
4365       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT,
4366                                 CastVal, IdxOffset);
4367 
4368       NewVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, NVT,
4369                            NewVec, Elt, InEltIdx);
4370     }
4371 
4372     Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewVec));
4373     break;
4374   }
4375   case ISD::SCALAR_TO_VECTOR: {
4376     MVT EltVT = OVT.getVectorElementType();
4377     MVT NewEltVT = NVT.getVectorElementType();
4378 
4379     // Handle bitcasts to different vector type with the smae total bit size.
4380     //
4381     // e.g. v2i64 = scalar_to_vector x:i64
4382     //   =>
4383     //  concat_vectors (v2i32 bitcast x:i64), (v2i32 undef)
4384     //
4385 
4386     MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4387     SDValue Val = Node->getOperand(0);
4388     SDLoc SL(Node);
4389 
4390     SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val);
4391     SDValue Undef = DAG.getUNDEF(MidVT);
4392 
4393     SmallVector<SDValue, 8> NewElts;
4394     NewElts.push_back(CastVal);
4395     for (unsigned I = 1, NElts = OVT.getVectorNumElements(); I != NElts; ++I)
4396       NewElts.push_back(Undef);
4397 
4398     SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewElts);
4399     SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat);
4400     Results.push_back(CvtVec);
4401     break;
4402   }
4403   }
4404 
4405   // Replace the original node with the legalized result.
4406   if (!Results.empty())
4407     ReplaceNode(Node, Results.data());
4408 }
4409 
4410 /// This is the entry point for the file.
4411 void SelectionDAG::Legalize() {
4412   AssignTopologicalOrder();
4413 
4414   SmallPtrSet<SDNode *, 16> LegalizedNodes;
4415   SelectionDAGLegalize Legalizer(*this, LegalizedNodes);
4416 
4417   // Visit all the nodes. We start in topological order, so that we see
4418   // nodes with their original operands intact. Legalization can produce
4419   // new nodes which may themselves need to be legalized. Iterate until all
4420   // nodes have been legalized.
4421   for (;;) {
4422     bool AnyLegalized = false;
4423     for (auto NI = allnodes_end(); NI != allnodes_begin();) {
4424       --NI;
4425 
4426       SDNode *N = &*NI;
4427       if (N->use_empty() && N != getRoot().getNode()) {
4428         ++NI;
4429         DeleteNode(N);
4430         continue;
4431       }
4432 
4433       if (LegalizedNodes.insert(N).second) {
4434         AnyLegalized = true;
4435         Legalizer.LegalizeOp(N);
4436 
4437         if (N->use_empty() && N != getRoot().getNode()) {
4438           ++NI;
4439           DeleteNode(N);
4440         }
4441       }
4442     }
4443     if (!AnyLegalized)
4444       break;
4445 
4446   }
4447 
4448   // Remove dead nodes now.
4449   RemoveDeadNodes();
4450 }
4451 
4452 bool SelectionDAG::LegalizeOp(SDNode *N,
4453                               SmallSetVector<SDNode *, 16> &UpdatedNodes) {
4454   SmallPtrSet<SDNode *, 16> LegalizedNodes;
4455   SelectionDAGLegalize Legalizer(*this, LegalizedNodes, &UpdatedNodes);
4456 
4457   // Directly insert the node in question, and legalize it. This will recurse
4458   // as needed through operands.
4459   LegalizedNodes.insert(N);
4460   Legalizer.LegalizeOp(N);
4461 
4462   return LegalizedNodes.count(N);
4463 }
4464