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