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