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