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