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