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