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