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