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