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