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