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