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