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