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