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