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