1 //===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the SelectionDAG::Legalize method.
12 //===----------------------------------------------------------------------===//
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"
39 #define DEBUG_TYPE "legalizedag"
41 //===----------------------------------------------------------------------===//
42 /// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
43 /// hacks on it until the target machine can handle it. This involves
44 /// eliminating value sizes the machine cannot handle (promoting small sizes to
45 /// large sizes or splitting up large values into small values) as well as
46 /// eliminating operations the machine cannot handle.
48 /// This code also does a small amount of optimization and recognition of idioms
49 /// as part of its processing. For example, if a target does not support a
50 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
51 /// will attempt merge setcc and brc instructions into brcc's.
54 class SelectionDAGLegalize : public SelectionDAG::DAGUpdateListener {
55 const TargetMachine &TM;
56 const TargetLowering &TLI;
59 /// \brief The iterator being used to walk the DAG. We hold a reference to it
60 /// in order to update it as necessary on node deletion.
61 SelectionDAG::allnodes_iterator &LegalizePosition;
63 /// \brief The set of nodes which have already been legalized. We hold a
64 /// reference to it in order to update as necessary on node deletion.
65 SmallPtrSetImpl<SDNode *> &LegalizedNodes;
67 /// \brief A set of all the nodes updated during legalization.
68 SmallSetVector<SDNode *, 16> *UpdatedNodes;
70 EVT getSetCCResultType(EVT VT) const {
71 return TLI.getSetCCResultType(*DAG.getContext(), VT);
74 // Libcall insertion helpers.
77 SelectionDAGLegalize(SelectionDAG &DAG,
78 SelectionDAG::allnodes_iterator &LegalizePosition,
79 SmallPtrSetImpl<SDNode *> &LegalizedNodes,
80 SmallSetVector<SDNode *, 16> *UpdatedNodes = nullptr)
81 : SelectionDAG::DAGUpdateListener(DAG), TM(DAG.getTarget()),
82 TLI(DAG.getTargetLoweringInfo()), DAG(DAG),
83 LegalizePosition(LegalizePosition), LegalizedNodes(LegalizedNodes),
84 UpdatedNodes(UpdatedNodes) {}
86 /// \brief Legalizes the given operation.
87 void LegalizeOp(SDNode *Node);
90 SDValue OptimizeFloatStore(StoreSDNode *ST);
92 void LegalizeLoadOps(SDNode *Node);
93 void LegalizeStoreOps(SDNode *Node);
95 /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
96 /// insertion index for the INSERT_VECTOR_ELT instruction. In this case, it
97 /// is necessary to spill the vector being inserted into to memory, perform
98 /// the insert there, and then read the result back.
99 SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val,
100 SDValue Idx, SDLoc dl);
101 SDValue ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val,
102 SDValue Idx, SDLoc dl);
104 /// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
105 /// performs the same shuffe in terms of order or result bytes, but on a type
106 /// whose vector element type is narrower than the original shuffle type.
107 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
108 SDValue ShuffleWithNarrowerEltType(EVT NVT, EVT VT, SDLoc dl,
109 SDValue N1, SDValue N2,
110 ArrayRef<int> Mask) const;
112 bool LegalizeSetCCCondCode(EVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC,
113 bool &NeedInvert, SDLoc dl);
115 SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned);
116 SDValue ExpandLibCall(RTLIB::Libcall LC, EVT RetVT, const SDValue *Ops,
117 unsigned NumOps, bool isSigned, SDLoc dl);
119 std::pair<SDValue, SDValue> ExpandChainLibCall(RTLIB::Libcall LC,
120 SDNode *Node, bool isSigned);
121 SDValue ExpandFPLibCall(SDNode *Node, RTLIB::Libcall Call_F32,
122 RTLIB::Libcall Call_F64, RTLIB::Libcall Call_F80,
123 RTLIB::Libcall Call_F128,
124 RTLIB::Libcall Call_PPCF128);
125 SDValue ExpandIntLibCall(SDNode *Node, bool isSigned,
126 RTLIB::Libcall Call_I8,
127 RTLIB::Libcall Call_I16,
128 RTLIB::Libcall Call_I32,
129 RTLIB::Libcall Call_I64,
130 RTLIB::Libcall Call_I128);
131 void ExpandDivRemLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results);
132 void ExpandSinCosLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results);
134 SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT, SDLoc dl);
135 SDValue ExpandBUILD_VECTOR(SDNode *Node);
136 SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
137 void ExpandDYNAMIC_STACKALLOC(SDNode *Node,
138 SmallVectorImpl<SDValue> &Results);
139 SDValue ExpandFCOPYSIGN(SDNode *Node);
140 SDValue ExpandLegalINT_TO_FP(bool isSigned, SDValue LegalOp, EVT DestVT,
142 SDValue PromoteLegalINT_TO_FP(SDValue LegalOp, EVT DestVT, bool isSigned,
144 SDValue PromoteLegalFP_TO_INT(SDValue LegalOp, EVT DestVT, bool isSigned,
147 SDValue ExpandBSWAP(SDValue Op, SDLoc dl);
148 SDValue ExpandBitCount(unsigned Opc, SDValue Op, SDLoc dl);
150 SDValue ExpandExtractFromVectorThroughStack(SDValue Op);
151 SDValue ExpandInsertToVectorThroughStack(SDValue Op);
152 SDValue ExpandVectorBuildThroughStack(SDNode* Node);
154 SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP);
156 std::pair<SDValue, SDValue> ExpandAtomic(SDNode *Node);
158 void ExpandNode(SDNode *Node);
159 void PromoteNode(SDNode *Node);
161 void ForgetNode(SDNode *N) {
162 LegalizedNodes.erase(N);
163 if (LegalizePosition == SelectionDAG::allnodes_iterator(N))
166 UpdatedNodes->remove(N);
170 // DAGUpdateListener implementation.
171 void NodeDeleted(SDNode *N, SDNode *E) override {
174 void NodeUpdated(SDNode *N) override {}
176 // Node replacement helpers
177 void ReplacedNode(SDNode *N) {
178 if (N->use_empty()) {
179 DAG.RemoveDeadNode(N);
184 void ReplaceNode(SDNode *Old, SDNode *New) {
185 DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
186 dbgs() << " with: "; New->dump(&DAG));
188 assert(Old->getNumValues() == New->getNumValues() &&
189 "Replacing one node with another that produces a different number "
191 DAG.ReplaceAllUsesWith(Old, New);
192 for (unsigned i = 0, e = Old->getNumValues(); i != e; ++i)
193 DAG.TransferDbgValues(SDValue(Old, i), SDValue(New, i));
195 UpdatedNodes->insert(New);
198 void ReplaceNode(SDValue Old, SDValue New) {
199 DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
200 dbgs() << " with: "; New->dump(&DAG));
202 DAG.ReplaceAllUsesWith(Old, New);
203 DAG.TransferDbgValues(Old, New);
205 UpdatedNodes->insert(New.getNode());
206 ReplacedNode(Old.getNode());
208 void ReplaceNode(SDNode *Old, const SDValue *New) {
209 DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG));
211 DAG.ReplaceAllUsesWith(Old, New);
212 for (unsigned i = 0, e = Old->getNumValues(); i != e; ++i) {
213 DEBUG(dbgs() << (i == 0 ? " with: "
216 DAG.TransferDbgValues(SDValue(Old, i), New[i]);
218 UpdatedNodes->insert(New[i].getNode());
225 /// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
226 /// performs the same shuffe in terms of order or result bytes, but on a type
227 /// whose vector element type is narrower than the original shuffle type.
228 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
230 SelectionDAGLegalize::ShuffleWithNarrowerEltType(EVT NVT, EVT VT, SDLoc dl,
231 SDValue N1, SDValue N2,
232 ArrayRef<int> Mask) const {
233 unsigned NumMaskElts = VT.getVectorNumElements();
234 unsigned NumDestElts = NVT.getVectorNumElements();
235 unsigned NumEltsGrowth = NumDestElts / NumMaskElts;
237 assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
239 if (NumEltsGrowth == 1)
240 return DAG.getVectorShuffle(NVT, dl, N1, N2, &Mask[0]);
242 SmallVector<int, 8> NewMask;
243 for (unsigned i = 0; i != NumMaskElts; ++i) {
245 for (unsigned j = 0; j != NumEltsGrowth; ++j) {
247 NewMask.push_back(-1);
249 NewMask.push_back(Idx * NumEltsGrowth + j);
252 assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?");
253 assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?");
254 return DAG.getVectorShuffle(NVT, dl, N1, N2, &NewMask[0]);
257 /// ExpandConstantFP - Expands the ConstantFP node to an integer constant or
258 /// a load from the constant pool.
260 SelectionDAGLegalize::ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP) {
264 // If a FP immediate is precise when represented as a float and if the
265 // target can do an extending load from float to double, we put it into
266 // the constant pool as a float, even if it's is statically typed as a
267 // double. This shrinks FP constants and canonicalizes them for targets where
268 // an FP extending load is the same cost as a normal load (such as on the x87
269 // fp stack or PPC FP unit).
270 EVT VT = CFP->getValueType(0);
271 ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
273 assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion");
274 return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(),
275 (VT == MVT::f64) ? MVT::i64 : MVT::i32);
280 while (SVT != MVT::f32 && SVT != MVT::f16) {
281 SVT = (MVT::SimpleValueType)(SVT.getSimpleVT().SimpleTy - 1);
282 if (ConstantFPSDNode::isValueValidForType(SVT, CFP->getValueAPF()) &&
283 // Only do this if the target has a native EXTLOAD instruction from
285 TLI.isLoadExtLegal(ISD::EXTLOAD, SVT) &&
286 TLI.ShouldShrinkFPConstant(OrigVT)) {
287 Type *SType = SVT.getTypeForEVT(*DAG.getContext());
288 LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
294 SDValue CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
295 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
298 DAG.getExtLoad(ISD::EXTLOAD, dl, OrigVT,
300 CPIdx, MachinePointerInfo::getConstantPool(),
301 VT, false, false, false, Alignment);
305 DAG.getLoad(OrigVT, dl, DAG.getEntryNode(), CPIdx,
306 MachinePointerInfo::getConstantPool(), false, false, false,
311 /// ExpandUnalignedStore - Expands an unaligned store to 2 half-size stores.
312 static void ExpandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG,
313 const TargetLowering &TLI,
314 SelectionDAGLegalize *DAGLegalize) {
315 assert(ST->getAddressingMode() == ISD::UNINDEXED &&
316 "unaligned indexed stores not implemented!");
317 SDValue Chain = ST->getChain();
318 SDValue Ptr = ST->getBasePtr();
319 SDValue Val = ST->getValue();
320 EVT VT = Val.getValueType();
321 int Alignment = ST->getAlignment();
322 unsigned AS = ST->getAddressSpace();
325 if (ST->getMemoryVT().isFloatingPoint() ||
326 ST->getMemoryVT().isVector()) {
327 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
328 if (TLI.isTypeLegal(intVT)) {
329 // Expand to a bitconvert of the value to the integer type of the
330 // same size, then a (misaligned) int store.
331 // FIXME: Does not handle truncating floating point stores!
332 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
333 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
334 ST->isVolatile(), ST->isNonTemporal(), Alignment);
335 DAGLegalize->ReplaceNode(SDValue(ST, 0), Result);
338 // Do a (aligned) store to a stack slot, then copy from the stack slot
339 // to the final destination using (unaligned) integer loads and stores.
340 EVT StoredVT = ST->getMemoryVT();
342 TLI.getRegisterType(*DAG.getContext(),
343 EVT::getIntegerVT(*DAG.getContext(),
344 StoredVT.getSizeInBits()));
345 unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
346 unsigned RegBytes = RegVT.getSizeInBits() / 8;
347 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
349 // Make sure the stack slot is also aligned for the register type.
350 SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
352 // Perform the original store, only redirected to the stack slot.
353 SDValue Store = DAG.getTruncStore(Chain, dl,
354 Val, StackPtr, MachinePointerInfo(),
355 StoredVT, false, false, 0);
356 SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy(AS));
357 SmallVector<SDValue, 8> Stores;
360 // Do all but one copies using the full register width.
361 for (unsigned i = 1; i < NumRegs; i++) {
362 // Load one integer register's worth from the stack slot.
363 SDValue Load = DAG.getLoad(RegVT, dl, Store, StackPtr,
364 MachinePointerInfo(),
365 false, false, false, 0);
366 // Store it to the final location. Remember the store.
367 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
368 ST->getPointerInfo().getWithOffset(Offset),
369 ST->isVolatile(), ST->isNonTemporal(),
370 MinAlign(ST->getAlignment(), Offset)));
371 // Increment the pointers.
373 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
375 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
378 // The last store may be partial. Do a truncating store. On big-endian
379 // machines this requires an extending load from the stack slot to ensure
380 // that the bits are in the right place.
381 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
382 8 * (StoredBytes - Offset));
384 // Load from the stack slot.
385 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
386 MachinePointerInfo(),
387 MemVT, false, false, false, 0);
389 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
391 .getWithOffset(Offset),
392 MemVT, ST->isVolatile(),
394 MinAlign(ST->getAlignment(), Offset),
396 // The order of the stores doesn't matter - say it with a TokenFactor.
397 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
398 DAGLegalize->ReplaceNode(SDValue(ST, 0), Result);
401 assert(ST->getMemoryVT().isInteger() &&
402 !ST->getMemoryVT().isVector() &&
403 "Unaligned store of unknown type.");
404 // Get the half-size VT
405 EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
406 int NumBits = NewStoredVT.getSizeInBits();
407 int IncrementSize = NumBits / 8;
409 // Divide the stored value in two parts.
410 SDValue ShiftAmount = DAG.getConstant(NumBits,
411 TLI.getShiftAmountTy(Val.getValueType()));
413 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
415 // Store the two parts
416 SDValue Store1, Store2;
417 Store1 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Lo:Hi, Ptr,
418 ST->getPointerInfo(), NewStoredVT,
419 ST->isVolatile(), ST->isNonTemporal(), Alignment);
421 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
422 DAG.getConstant(IncrementSize, TLI.getPointerTy(AS)));
423 Alignment = MinAlign(Alignment, IncrementSize);
424 Store2 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Hi:Lo, Ptr,
425 ST->getPointerInfo().getWithOffset(IncrementSize),
426 NewStoredVT, ST->isVolatile(), ST->isNonTemporal(),
427 Alignment, ST->getAAInfo());
430 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
431 DAGLegalize->ReplaceNode(SDValue(ST, 0), Result);
434 /// ExpandUnalignedLoad - Expands an unaligned load to 2 half-size loads.
436 ExpandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG,
437 const TargetLowering &TLI,
438 SDValue &ValResult, SDValue &ChainResult) {
439 assert(LD->getAddressingMode() == ISD::UNINDEXED &&
440 "unaligned indexed loads not implemented!");
441 SDValue Chain = LD->getChain();
442 SDValue Ptr = LD->getBasePtr();
443 EVT VT = LD->getValueType(0);
444 EVT LoadedVT = LD->getMemoryVT();
446 if (VT.isFloatingPoint() || VT.isVector()) {
447 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
448 if (TLI.isTypeLegal(intVT) && TLI.isTypeLegal(LoadedVT)) {
449 // Expand to a (misaligned) integer load of the same size,
450 // then bitconvert to floating point or vector.
451 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
452 LD->getMemOperand());
453 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
455 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
456 ISD::ANY_EXTEND, dl, VT, Result);
463 // Copy the value to a (aligned) stack slot using (unaligned) integer
464 // loads and stores, then do a (aligned) load from the stack slot.
465 MVT RegVT = TLI.getRegisterType(*DAG.getContext(), intVT);
466 unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
467 unsigned RegBytes = RegVT.getSizeInBits() / 8;
468 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
470 // Make sure the stack slot is also aligned for the register type.
471 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
473 SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
474 SmallVector<SDValue, 8> Stores;
475 SDValue StackPtr = StackBase;
478 // Do all but one copies using the full register width.
479 for (unsigned i = 1; i < NumRegs; i++) {
480 // Load one integer register's worth from the original location.
481 SDValue Load = DAG.getLoad(RegVT, dl, Chain, Ptr,
482 LD->getPointerInfo().getWithOffset(Offset),
483 LD->isVolatile(), LD->isNonTemporal(),
485 MinAlign(LD->getAlignment(), Offset),
487 // Follow the load with a store to the stack slot. Remember the store.
488 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
489 MachinePointerInfo(), false, false, 0));
490 // Increment the pointers.
492 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
493 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
497 // The last copy may be partial. Do an extending load.
498 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
499 8 * (LoadedBytes - Offset));
500 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
501 LD->getPointerInfo().getWithOffset(Offset),
502 MemVT, LD->isVolatile(),
505 MinAlign(LD->getAlignment(), Offset),
507 // Follow the load with a store to the stack slot. Remember the store.
508 // On big-endian machines this requires a truncating store to ensure
509 // that the bits end up in the right place.
510 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
511 MachinePointerInfo(), MemVT,
514 // The order of the stores doesn't matter - say it with a TokenFactor.
515 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
517 // Finally, perform the original load only redirected to the stack slot.
518 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
519 MachinePointerInfo(), LoadedVT, false,false, false,
522 // Callers expect a MERGE_VALUES node.
527 assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
528 "Unaligned load of unsupported type.");
530 // Compute the new VT that is half the size of the old one. This is an
532 unsigned NumBits = LoadedVT.getSizeInBits();
534 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
537 unsigned Alignment = LD->getAlignment();
538 unsigned IncrementSize = NumBits / 8;
539 ISD::LoadExtType HiExtType = LD->getExtensionType();
541 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
542 if (HiExtType == ISD::NON_EXTLOAD)
543 HiExtType = ISD::ZEXTLOAD;
545 // Load the value in two parts
547 if (TLI.isLittleEndian()) {
548 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
549 NewLoadedVT, LD->isVolatile(),
550 LD->isNonTemporal(), LD->isInvariant(), Alignment,
552 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
553 DAG.getConstant(IncrementSize, Ptr.getValueType()));
554 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
555 LD->getPointerInfo().getWithOffset(IncrementSize),
556 NewLoadedVT, LD->isVolatile(),
557 LD->isNonTemporal(),LD->isInvariant(),
558 MinAlign(Alignment, IncrementSize), LD->getAAInfo());
560 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
561 NewLoadedVT, LD->isVolatile(),
562 LD->isNonTemporal(), LD->isInvariant(), Alignment,
564 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
565 DAG.getConstant(IncrementSize, Ptr.getValueType()));
566 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
567 LD->getPointerInfo().getWithOffset(IncrementSize),
568 NewLoadedVT, LD->isVolatile(),
569 LD->isNonTemporal(), LD->isInvariant(),
570 MinAlign(Alignment, IncrementSize), LD->getAAInfo());
573 // aggregate the two parts
574 SDValue ShiftAmount = DAG.getConstant(NumBits,
575 TLI.getShiftAmountTy(Hi.getValueType()));
576 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
577 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
579 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
586 /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
587 /// insertion index for the INSERT_VECTOR_ELT instruction. In this case, it
588 /// is necessary to spill the vector being inserted into to memory, perform
589 /// the insert there, and then read the result back.
590 SDValue SelectionDAGLegalize::
591 PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx,
597 // If the target doesn't support this, we have to spill the input vector
598 // to a temporary stack slot, update the element, then reload it. This is
599 // badness. We could also load the value into a vector register (either
600 // with a "move to register" or "extload into register" instruction, then
601 // permute it into place, if the idx is a constant and if the idx is
602 // supported by the target.
603 EVT VT = Tmp1.getValueType();
604 EVT EltVT = VT.getVectorElementType();
605 EVT IdxVT = Tmp3.getValueType();
606 EVT PtrVT = TLI.getPointerTy();
607 SDValue StackPtr = DAG.CreateStackTemporary(VT);
609 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
612 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Tmp1, StackPtr,
613 MachinePointerInfo::getFixedStack(SPFI),
616 // Truncate or zero extend offset to target pointer type.
617 unsigned CastOpc = IdxVT.bitsGT(PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
618 Tmp3 = DAG.getNode(CastOpc, dl, PtrVT, Tmp3);
619 // Add the offset to the index.
620 unsigned EltSize = EltVT.getSizeInBits()/8;
621 Tmp3 = DAG.getNode(ISD::MUL, dl, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
622 SDValue StackPtr2 = DAG.getNode(ISD::ADD, dl, IdxVT, Tmp3, StackPtr);
623 // Store the scalar value.
624 Ch = DAG.getTruncStore(Ch, dl, Tmp2, StackPtr2, MachinePointerInfo(), EltVT,
626 // Load the updated vector.
627 return DAG.getLoad(VT, dl, Ch, StackPtr,
628 MachinePointerInfo::getFixedStack(SPFI), false, false,
633 SDValue SelectionDAGLegalize::
634 ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, SDValue Idx, SDLoc dl) {
635 if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) {
636 // SCALAR_TO_VECTOR requires that the type of the value being inserted
637 // match the element type of the vector being created, except for
638 // integers in which case the inserted value can be over width.
639 EVT EltVT = Vec.getValueType().getVectorElementType();
640 if (Val.getValueType() == EltVT ||
641 (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) {
642 SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
643 Vec.getValueType(), Val);
645 unsigned NumElts = Vec.getValueType().getVectorNumElements();
646 // We generate a shuffle of InVec and ScVec, so the shuffle mask
647 // should be 0,1,2,3,4,5... with the appropriate element replaced with
649 SmallVector<int, 8> ShufOps;
650 for (unsigned i = 0; i != NumElts; ++i)
651 ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts);
653 return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec,
657 return PerformInsertVectorEltInMemory(Vec, Val, Idx, dl);
660 SDValue SelectionDAGLegalize::OptimizeFloatStore(StoreSDNode* ST) {
661 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
662 // FIXME: We shouldn't do this for TargetConstantFP's.
663 // FIXME: move this to the DAG Combiner! Note that we can't regress due
664 // to phase ordering between legalized code and the dag combiner. This
665 // probably means that we need to integrate dag combiner and legalizer
667 // We generally can't do this one for long doubles.
668 SDValue Chain = ST->getChain();
669 SDValue Ptr = ST->getBasePtr();
670 unsigned Alignment = ST->getAlignment();
671 bool isVolatile = ST->isVolatile();
672 bool isNonTemporal = ST->isNonTemporal();
673 AAMDNodes AAInfo = ST->getAAInfo();
675 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
676 if (CFP->getValueType(0) == MVT::f32 &&
677 TLI.isTypeLegal(MVT::i32)) {
678 SDValue Con = DAG.getConstant(CFP->getValueAPF().
679 bitcastToAPInt().zextOrTrunc(32),
681 return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(),
682 isVolatile, isNonTemporal, Alignment, AAInfo);
685 if (CFP->getValueType(0) == MVT::f64) {
686 // If this target supports 64-bit registers, do a single 64-bit store.
687 if (TLI.isTypeLegal(MVT::i64)) {
688 SDValue Con = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
689 zextOrTrunc(64), MVT::i64);
690 return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(),
691 isVolatile, isNonTemporal, Alignment, AAInfo);
694 if (TLI.isTypeLegal(MVT::i32) && !ST->isVolatile()) {
695 // Otherwise, if the target supports 32-bit registers, use 2 32-bit
696 // stores. If the target supports neither 32- nor 64-bits, this
697 // xform is certainly not worth it.
698 const APInt &IntVal =CFP->getValueAPF().bitcastToAPInt();
699 SDValue Lo = DAG.getConstant(IntVal.trunc(32), MVT::i32);
700 SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), MVT::i32);
701 if (TLI.isBigEndian()) std::swap(Lo, Hi);
703 Lo = DAG.getStore(Chain, dl, Lo, Ptr, ST->getPointerInfo(), isVolatile,
704 isNonTemporal, Alignment, AAInfo);
705 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
706 DAG.getConstant(4, Ptr.getValueType()));
707 Hi = DAG.getStore(Chain, dl, Hi, Ptr,
708 ST->getPointerInfo().getWithOffset(4),
709 isVolatile, isNonTemporal, MinAlign(Alignment, 4U),
712 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
716 return SDValue(nullptr, 0);
719 void SelectionDAGLegalize::LegalizeStoreOps(SDNode *Node) {
720 StoreSDNode *ST = cast<StoreSDNode>(Node);
721 SDValue Chain = ST->getChain();
722 SDValue Ptr = ST->getBasePtr();
725 unsigned Alignment = ST->getAlignment();
726 bool isVolatile = ST->isVolatile();
727 bool isNonTemporal = ST->isNonTemporal();
728 AAMDNodes AAInfo = ST->getAAInfo();
730 if (!ST->isTruncatingStore()) {
731 if (SDNode *OptStore = OptimizeFloatStore(ST).getNode()) {
732 ReplaceNode(ST, OptStore);
737 SDValue Value = ST->getValue();
738 MVT VT = Value.getSimpleValueType();
739 switch (TLI.getOperationAction(ISD::STORE, VT)) {
740 default: llvm_unreachable("This action is not supported yet!");
741 case TargetLowering::Legal: {
742 // If this is an unaligned store and the target doesn't support it,
744 unsigned AS = ST->getAddressSpace();
745 unsigned Align = ST->getAlignment();
746 if (!TLI.allowsMisalignedMemoryAccesses(ST->getMemoryVT(), AS, Align)) {
747 Type *Ty = ST->getMemoryVT().getTypeForEVT(*DAG.getContext());
748 unsigned ABIAlignment= TLI.getDataLayout()->getABITypeAlignment(Ty);
749 if (Align < ABIAlignment)
750 ExpandUnalignedStore(cast<StoreSDNode>(Node),
755 case TargetLowering::Custom: {
756 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
758 ReplaceNode(SDValue(Node, 0), Res);
761 case TargetLowering::Promote: {
762 MVT NVT = TLI.getTypeToPromoteTo(ISD::STORE, VT);
763 assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
764 "Can only promote stores to same size type");
765 Value = DAG.getNode(ISD::BITCAST, dl, NVT, Value);
767 DAG.getStore(Chain, dl, Value, Ptr,
768 ST->getPointerInfo(), isVolatile,
769 isNonTemporal, Alignment, AAInfo);
770 ReplaceNode(SDValue(Node, 0), Result);
777 SDValue Value = ST->getValue();
779 EVT StVT = ST->getMemoryVT();
780 unsigned StWidth = StVT.getSizeInBits();
782 if (StWidth != StVT.getStoreSizeInBits()) {
783 // Promote to a byte-sized store with upper bits zero if not
784 // storing an integral number of bytes. For example, promote
785 // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
786 EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
787 StVT.getStoreSizeInBits());
788 Value = DAG.getZeroExtendInReg(Value, dl, StVT);
790 DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
791 NVT, isVolatile, isNonTemporal, Alignment,
793 ReplaceNode(SDValue(Node, 0), Result);
794 } else if (StWidth & (StWidth - 1)) {
795 // If not storing a power-of-2 number of bits, expand as two stores.
796 assert(!StVT.isVector() && "Unsupported truncstore!");
797 unsigned RoundWidth = 1 << Log2_32(StWidth);
798 assert(RoundWidth < StWidth);
799 unsigned ExtraWidth = StWidth - RoundWidth;
800 assert(ExtraWidth < RoundWidth);
801 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
802 "Store size not an integral number of bytes!");
803 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
804 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
806 unsigned IncrementSize;
808 if (TLI.isLittleEndian()) {
809 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
810 // Store the bottom RoundWidth bits.
811 Lo = DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
813 isVolatile, isNonTemporal, Alignment,
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 Hi = DAG.getNode(ISD::SRL, dl, Value.getValueType(), Value,
821 DAG.getConstant(RoundWidth,
822 TLI.getShiftAmountTy(Value.getValueType())));
823 Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr,
824 ST->getPointerInfo().getWithOffset(IncrementSize),
825 ExtraVT, isVolatile, isNonTemporal,
826 MinAlign(Alignment, IncrementSize), AAInfo);
828 // Big endian - avoid unaligned stores.
829 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
830 // Store the top RoundWidth bits.
831 Hi = DAG.getNode(ISD::SRL, dl, Value.getValueType(), Value,
832 DAG.getConstant(ExtraWidth,
833 TLI.getShiftAmountTy(Value.getValueType())));
834 Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr, ST->getPointerInfo(),
835 RoundVT, isVolatile, isNonTemporal, Alignment,
838 // Store the remaining ExtraWidth bits.
839 IncrementSize = RoundWidth / 8;
840 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
841 DAG.getConstant(IncrementSize, Ptr.getValueType()));
842 Lo = DAG.getTruncStore(Chain, dl, Value, Ptr,
843 ST->getPointerInfo().getWithOffset(IncrementSize),
844 ExtraVT, isVolatile, isNonTemporal,
845 MinAlign(Alignment, IncrementSize), AAInfo);
848 // The order of the stores doesn't matter.
849 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
850 ReplaceNode(SDValue(Node, 0), Result);
852 switch (TLI.getTruncStoreAction(ST->getValue().getSimpleValueType(),
853 StVT.getSimpleVT())) {
854 default: llvm_unreachable("This action is not supported yet!");
855 case TargetLowering::Legal: {
856 unsigned AS = ST->getAddressSpace();
857 unsigned Align = ST->getAlignment();
858 // If this is an unaligned store and the target doesn't support it,
860 if (!TLI.allowsMisalignedMemoryAccesses(ST->getMemoryVT(), AS, Align)) {
861 Type *Ty = ST->getMemoryVT().getTypeForEVT(*DAG.getContext());
862 unsigned ABIAlignment= TLI.getDataLayout()->getABITypeAlignment(Ty);
863 if (Align < ABIAlignment)
864 ExpandUnalignedStore(cast<StoreSDNode>(Node), DAG, TLI, this);
868 case TargetLowering::Custom: {
869 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
871 ReplaceNode(SDValue(Node, 0), Res);
874 case TargetLowering::Expand:
875 assert(!StVT.isVector() &&
876 "Vector Stores are handled in LegalizeVectorOps");
878 // TRUNCSTORE:i16 i32 -> STORE i16
879 assert(TLI.isTypeLegal(StVT) &&
880 "Do not know how to expand this store!");
881 Value = DAG.getNode(ISD::TRUNCATE, dl, StVT, Value);
883 DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
884 isVolatile, isNonTemporal, Alignment, AAInfo);
885 ReplaceNode(SDValue(Node, 0), Result);
892 void SelectionDAGLegalize::LegalizeLoadOps(SDNode *Node) {
893 LoadSDNode *LD = cast<LoadSDNode>(Node);
894 SDValue Chain = LD->getChain(); // The chain.
895 SDValue Ptr = LD->getBasePtr(); // The base pointer.
896 SDValue Value; // The value returned by the load op.
899 ISD::LoadExtType ExtType = LD->getExtensionType();
900 if (ExtType == ISD::NON_EXTLOAD) {
901 MVT VT = Node->getSimpleValueType(0);
902 SDValue RVal = SDValue(Node, 0);
903 SDValue RChain = SDValue(Node, 1);
905 switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
906 default: llvm_unreachable("This action is not supported yet!");
907 case TargetLowering::Legal: {
908 unsigned AS = LD->getAddressSpace();
909 unsigned Align = LD->getAlignment();
910 // If this is an unaligned load and the target doesn't support it,
912 if (!TLI.allowsMisalignedMemoryAccesses(LD->getMemoryVT(), AS, Align)) {
913 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
914 unsigned ABIAlignment =
915 TLI.getDataLayout()->getABITypeAlignment(Ty);
916 if (Align < ABIAlignment){
917 ExpandUnalignedLoad(cast<LoadSDNode>(Node), DAG, TLI, RVal, RChain);
922 case TargetLowering::Custom: {
923 SDValue Res = TLI.LowerOperation(RVal, DAG);
926 RChain = Res.getValue(1);
930 case TargetLowering::Promote: {
931 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
932 assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
933 "Can only promote loads to same size type");
935 SDValue Res = DAG.getLoad(NVT, dl, Chain, Ptr, LD->getMemOperand());
936 RVal = DAG.getNode(ISD::BITCAST, dl, VT, Res);
937 RChain = Res.getValue(1);
941 if (RChain.getNode() != Node) {
942 assert(RVal.getNode() != Node && "Load must be completely replaced");
943 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), RVal);
944 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), RChain);
946 UpdatedNodes->insert(RVal.getNode());
947 UpdatedNodes->insert(RChain.getNode());
954 EVT SrcVT = LD->getMemoryVT();
955 unsigned SrcWidth = SrcVT.getSizeInBits();
956 unsigned Alignment = LD->getAlignment();
957 bool isVolatile = LD->isVolatile();
958 bool isNonTemporal = LD->isNonTemporal();
959 bool isInvariant = LD->isInvariant();
960 AAMDNodes AAInfo = LD->getAAInfo();
962 if (SrcWidth != SrcVT.getStoreSizeInBits() &&
963 // Some targets pretend to have an i1 loading operation, and actually
964 // load an i8. This trick is correct for ZEXTLOAD because the top 7
965 // bits are guaranteed to be zero; it helps the optimizers understand
966 // that these bits are zero. It is also useful for EXTLOAD, since it
967 // tells the optimizers that those bits are undefined. It would be
968 // nice to have an effective generic way of getting these benefits...
969 // Until such a way is found, don't insist on promoting i1 here.
971 TLI.getLoadExtAction(ExtType, MVT::i1) == TargetLowering::Promote)) {
972 // Promote to a byte-sized load if not loading an integral number of
973 // bytes. For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
974 unsigned NewWidth = SrcVT.getStoreSizeInBits();
975 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), NewWidth);
978 // The extra bits are guaranteed to be zero, since we stored them that
979 // way. A zext load from NVT thus automatically gives zext from SrcVT.
981 ISD::LoadExtType NewExtType =
982 ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
985 DAG.getExtLoad(NewExtType, dl, Node->getValueType(0),
986 Chain, Ptr, LD->getPointerInfo(),
987 NVT, isVolatile, isNonTemporal, isInvariant, Alignment,
990 Ch = Result.getValue(1); // The chain.
992 if (ExtType == ISD::SEXTLOAD)
993 // Having the top bits zero doesn't help when sign extending.
994 Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
995 Result.getValueType(),
996 Result, DAG.getValueType(SrcVT));
997 else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
998 // All the top bits are guaranteed to be zero - inform the optimizers.
999 Result = DAG.getNode(ISD::AssertZext, dl,
1000 Result.getValueType(), Result,
1001 DAG.getValueType(SrcVT));
1005 } else if (SrcWidth & (SrcWidth - 1)) {
1006 // If not loading a power-of-2 number of bits, expand as two loads.
1007 assert(!SrcVT.isVector() && "Unsupported extload!");
1008 unsigned RoundWidth = 1 << Log2_32(SrcWidth);
1009 assert(RoundWidth < SrcWidth);
1010 unsigned ExtraWidth = SrcWidth - RoundWidth;
1011 assert(ExtraWidth < RoundWidth);
1012 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
1013 "Load size not an integral number of bytes!");
1014 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
1015 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
1017 unsigned IncrementSize;
1019 if (TLI.isLittleEndian()) {
1020 // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
1021 // Load the bottom RoundWidth bits.
1022 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0),
1024 LD->getPointerInfo(), RoundVT, isVolatile,
1025 isNonTemporal, isInvariant, Alignment, AAInfo);
1027 // Load the remaining ExtraWidth bits.
1028 IncrementSize = RoundWidth / 8;
1029 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
1030 DAG.getConstant(IncrementSize, Ptr.getValueType()));
1031 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
1032 LD->getPointerInfo().getWithOffset(IncrementSize),
1033 ExtraVT, isVolatile, isNonTemporal, isInvariant,
1034 MinAlign(Alignment, IncrementSize), AAInfo);
1036 // Build a factor node to remember that this load is independent of
1038 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1041 // Move the top bits to the right place.
1042 Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1043 DAG.getConstant(RoundWidth,
1044 TLI.getShiftAmountTy(Hi.getValueType())));
1046 // Join the hi and lo parts.
1047 Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1049 // Big endian - avoid unaligned loads.
1050 // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
1051 // Load the top RoundWidth bits.
1052 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
1053 LD->getPointerInfo(), RoundVT, isVolatile,
1054 isNonTemporal, isInvariant, Alignment, AAInfo);
1056 // Load the remaining ExtraWidth bits.
1057 IncrementSize = RoundWidth / 8;
1058 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
1059 DAG.getConstant(IncrementSize, Ptr.getValueType()));
1060 Lo = DAG.getExtLoad(ISD::ZEXTLOAD,
1061 dl, Node->getValueType(0), Chain, Ptr,
1062 LD->getPointerInfo().getWithOffset(IncrementSize),
1063 ExtraVT, isVolatile, isNonTemporal, isInvariant,
1064 MinAlign(Alignment, IncrementSize), AAInfo);
1066 // Build a factor node to remember that this load is independent of
1068 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1071 // Move the top bits to the right place.
1072 Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1073 DAG.getConstant(ExtraWidth,
1074 TLI.getShiftAmountTy(Hi.getValueType())));
1076 // Join the hi and lo parts.
1077 Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1082 bool isCustom = false;
1083 switch (TLI.getLoadExtAction(ExtType, SrcVT.getSimpleVT())) {
1084 default: llvm_unreachable("This action is not supported yet!");
1085 case TargetLowering::Custom:
1088 case TargetLowering::Legal: {
1089 Value = SDValue(Node, 0);
1090 Chain = SDValue(Node, 1);
1093 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
1094 if (Res.getNode()) {
1096 Chain = Res.getValue(1);
1099 // If this is an unaligned load and the target doesn't support
1101 EVT MemVT = LD->getMemoryVT();
1102 unsigned AS = LD->getAddressSpace();
1103 unsigned Align = LD->getAlignment();
1104 if (!TLI.allowsMisalignedMemoryAccesses(MemVT, AS, Align)) {
1106 LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
1107 unsigned ABIAlignment =
1108 TLI.getDataLayout()->getABITypeAlignment(Ty);
1109 if (Align < ABIAlignment){
1110 ExpandUnalignedLoad(cast<LoadSDNode>(Node),
1111 DAG, TLI, Value, Chain);
1117 case TargetLowering::Expand:
1118 if (!TLI.isLoadExtLegal(ISD::EXTLOAD, SrcVT) &&
1119 TLI.isTypeLegal(SrcVT)) {
1120 SDValue Load = DAG.getLoad(SrcVT, dl, Chain, Ptr,
1121 LD->getMemOperand());
1125 ExtendOp = (SrcVT.isFloatingPoint() ?
1126 ISD::FP_EXTEND : ISD::ANY_EXTEND);
1128 case ISD::SEXTLOAD: ExtendOp = ISD::SIGN_EXTEND; break;
1129 case ISD::ZEXTLOAD: ExtendOp = ISD::ZERO_EXTEND; break;
1130 default: llvm_unreachable("Unexpected extend load type!");
1132 Value = DAG.getNode(ExtendOp, dl, Node->getValueType(0), Load);
1133 Chain = Load.getValue(1);
1137 assert(!SrcVT.isVector() &&
1138 "Vector Loads are handled in LegalizeVectorOps");
1140 // FIXME: This does not work for vectors on most targets. Sign-
1141 // and zero-extend operations are currently folded into extending
1142 // loads, whether they are legal or not, and then we end up here
1143 // without any support for legalizing them.
1144 assert(ExtType != ISD::EXTLOAD &&
1145 "EXTLOAD should always be supported!");
1146 // Turn the unsupported load into an EXTLOAD followed by an
1147 // explicit zero/sign extend inreg.
1148 SDValue Result = DAG.getExtLoad(ISD::EXTLOAD, dl,
1149 Node->getValueType(0),
1151 LD->getMemOperand());
1153 if (ExtType == ISD::SEXTLOAD)
1154 ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
1155 Result.getValueType(),
1156 Result, DAG.getValueType(SrcVT));
1158 ValRes = DAG.getZeroExtendInReg(Result, dl,
1159 SrcVT.getScalarType());
1161 Chain = Result.getValue(1);
1166 // Since loads produce two values, make sure to remember that we legalized
1168 if (Chain.getNode() != Node) {
1169 assert(Value.getNode() != Node && "Load must be completely replaced");
1170 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Value);
1171 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
1173 UpdatedNodes->insert(Value.getNode());
1174 UpdatedNodes->insert(Chain.getNode());
1180 /// LegalizeOp - Return a legal replacement for the given operation, with
1181 /// all legal operands.
1182 void SelectionDAGLegalize::LegalizeOp(SDNode *Node) {
1183 DEBUG(dbgs() << "\nLegalizing: "; Node->dump(&DAG));
1185 if (Node->getOpcode() == ISD::TargetConstant) // Allow illegal target nodes.
1188 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
1189 assert(TLI.getTypeAction(*DAG.getContext(), Node->getValueType(i)) ==
1190 TargetLowering::TypeLegal &&
1191 "Unexpected illegal type!");
1193 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1194 assert((TLI.getTypeAction(*DAG.getContext(),
1195 Node->getOperand(i).getValueType()) ==
1196 TargetLowering::TypeLegal ||
1197 Node->getOperand(i).getOpcode() == ISD::TargetConstant) &&
1198 "Unexpected illegal type!");
1200 // Figure out the correct action; the way to query this varies by opcode
1201 TargetLowering::LegalizeAction Action = TargetLowering::Legal;
1202 bool SimpleFinishLegalizing = true;
1203 switch (Node->getOpcode()) {
1204 case ISD::INTRINSIC_W_CHAIN:
1205 case ISD::INTRINSIC_WO_CHAIN:
1206 case ISD::INTRINSIC_VOID:
1207 case ISD::STACKSAVE:
1208 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
1211 Action = TLI.getOperationAction(Node->getOpcode(),
1212 Node->getValueType(0));
1213 if (Action != TargetLowering::Promote)
1214 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
1216 case ISD::FP_TO_FP16:
1217 case ISD::SINT_TO_FP:
1218 case ISD::UINT_TO_FP:
1219 case ISD::EXTRACT_VECTOR_ELT:
1220 Action = TLI.getOperationAction(Node->getOpcode(),
1221 Node->getOperand(0).getValueType());
1223 case ISD::FP_ROUND_INREG:
1224 case ISD::SIGN_EXTEND_INREG: {
1225 EVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT();
1226 Action = TLI.getOperationAction(Node->getOpcode(), InnerType);
1229 case ISD::ATOMIC_STORE: {
1230 Action = TLI.getOperationAction(Node->getOpcode(),
1231 Node->getOperand(2).getValueType());
1234 case ISD::SELECT_CC:
1237 unsigned CCOperand = Node->getOpcode() == ISD::SELECT_CC ? 4 :
1238 Node->getOpcode() == ISD::SETCC ? 2 : 1;
1239 unsigned CompareOperand = Node->getOpcode() == ISD::BR_CC ? 2 : 0;
1240 MVT OpVT = Node->getOperand(CompareOperand).getSimpleValueType();
1241 ISD::CondCode CCCode =
1242 cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get();
1243 Action = TLI.getCondCodeAction(CCCode, OpVT);
1244 if (Action == TargetLowering::Legal) {
1245 if (Node->getOpcode() == ISD::SELECT_CC)
1246 Action = TLI.getOperationAction(Node->getOpcode(),
1247 Node->getValueType(0));
1249 Action = TLI.getOperationAction(Node->getOpcode(), OpVT);
1255 // FIXME: Model these properly. LOAD and STORE are complicated, and
1256 // STORE expects the unlegalized operand in some cases.
1257 SimpleFinishLegalizing = false;
1259 case ISD::CALLSEQ_START:
1260 case ISD::CALLSEQ_END:
1261 // FIXME: This shouldn't be necessary. These nodes have special properties
1262 // dealing with the recursive nature of legalization. Removing this
1263 // special case should be done as part of making LegalizeDAG non-recursive.
1264 SimpleFinishLegalizing = false;
1266 case ISD::EXTRACT_ELEMENT:
1267 case ISD::FLT_ROUNDS_:
1275 case ISD::MERGE_VALUES:
1276 case ISD::EH_RETURN:
1277 case ISD::FRAME_TO_ARGS_OFFSET:
1278 case ISD::EH_SJLJ_SETJMP:
1279 case ISD::EH_SJLJ_LONGJMP:
1280 // These operations lie about being legal: when they claim to be legal,
1281 // they should actually be expanded.
1282 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1283 if (Action == TargetLowering::Legal)
1284 Action = TargetLowering::Expand;
1286 case ISD::INIT_TRAMPOLINE:
1287 case ISD::ADJUST_TRAMPOLINE:
1288 case ISD::FRAMEADDR:
1289 case ISD::RETURNADDR:
1290 // These operations lie about being legal: when they claim to be legal,
1291 // they should actually be custom-lowered.
1292 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1293 if (Action == TargetLowering::Legal)
1294 Action = TargetLowering::Custom;
1296 case ISD::READ_REGISTER:
1297 case ISD::WRITE_REGISTER:
1298 // Named register is legal in the DAG, but blocked by register name
1299 // selection if not implemented by target (to chose the correct register)
1300 // They'll be converted to Copy(To/From)Reg.
1301 Action = TargetLowering::Legal;
1303 case ISD::DEBUGTRAP:
1304 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1305 if (Action == TargetLowering::Expand) {
1306 // replace ISD::DEBUGTRAP with ISD::TRAP
1308 NewVal = DAG.getNode(ISD::TRAP, SDLoc(Node), Node->getVTList(),
1309 Node->getOperand(0));
1310 ReplaceNode(Node, NewVal.getNode());
1311 LegalizeOp(NewVal.getNode());
1317 if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
1318 Action = TargetLowering::Legal;
1320 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1325 if (SimpleFinishLegalizing) {
1326 SDNode *NewNode = Node;
1327 switch (Node->getOpcode()) {
1334 // Legalizing shifts/rotates requires adjusting the shift amount
1335 // to the appropriate width.
1336 if (!Node->getOperand(1).getValueType().isVector()) {
1338 DAG.getShiftAmountOperand(Node->getOperand(0).getValueType(),
1339 Node->getOperand(1));
1340 HandleSDNode Handle(SAO);
1341 LegalizeOp(SAO.getNode());
1342 NewNode = DAG.UpdateNodeOperands(Node, Node->getOperand(0),
1346 case ISD::SRL_PARTS:
1347 case ISD::SRA_PARTS:
1348 case ISD::SHL_PARTS:
1349 // Legalizing shifts/rotates requires adjusting the shift amount
1350 // to the appropriate width.
1351 if (!Node->getOperand(2).getValueType().isVector()) {
1353 DAG.getShiftAmountOperand(Node->getOperand(0).getValueType(),
1354 Node->getOperand(2));
1355 HandleSDNode Handle(SAO);
1356 LegalizeOp(SAO.getNode());
1357 NewNode = DAG.UpdateNodeOperands(Node, Node->getOperand(0),
1358 Node->getOperand(1),
1364 if (NewNode != Node) {
1365 ReplaceNode(Node, NewNode);
1369 case TargetLowering::Legal:
1371 case TargetLowering::Custom: {
1372 // FIXME: The handling for custom lowering with multiple results is
1374 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
1375 if (Res.getNode()) {
1376 if (!(Res.getNode() != Node || Res.getResNo() != 0))
1379 if (Node->getNumValues() == 1) {
1380 // We can just directly replace this node with the lowered value.
1381 ReplaceNode(SDValue(Node, 0), Res);
1385 SmallVector<SDValue, 8> ResultVals;
1386 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
1387 ResultVals.push_back(Res.getValue(i));
1388 ReplaceNode(Node, ResultVals.data());
1393 case TargetLowering::Expand:
1396 case TargetLowering::Promote:
1402 switch (Node->getOpcode()) {
1409 llvm_unreachable("Do not know how to legalize this operator!");
1411 case ISD::CALLSEQ_START:
1412 case ISD::CALLSEQ_END:
1415 return LegalizeLoadOps(Node);
1418 return LegalizeStoreOps(Node);
1423 SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
1424 SDValue Vec = Op.getOperand(0);
1425 SDValue Idx = Op.getOperand(1);
1428 // Before we generate a new store to a temporary stack slot, see if there is
1429 // already one that we can use. There often is because when we scalarize
1430 // vector operations (using SelectionDAG::UnrollVectorOp for example) a whole
1431 // series of EXTRACT_VECTOR_ELT nodes are generated, one for each element in
1432 // the vector. If all are expanded here, we don't want one store per vector
1434 SDValue StackPtr, Ch;
1435 for (SDNode::use_iterator UI = Vec.getNode()->use_begin(),
1436 UE = Vec.getNode()->use_end(); UI != UE; ++UI) {
1438 if (StoreSDNode *ST = dyn_cast<StoreSDNode>(User)) {
1439 if (ST->isIndexed() || ST->isTruncatingStore() ||
1440 ST->getValue() != Vec)
1443 // Make sure that nothing else could have stored into the destination of
1445 if (!ST->getChain().reachesChainWithoutSideEffects(DAG.getEntryNode()))
1448 StackPtr = ST->getBasePtr();
1449 Ch = SDValue(ST, 0);
1454 if (!Ch.getNode()) {
1455 // Store the value to a temporary stack slot, then LOAD the returned part.
1456 StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
1457 Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr,
1458 MachinePointerInfo(), false, false, 0);
1461 // Add the offset to the index.
1463 Vec.getValueType().getVectorElementType().getSizeInBits()/8;
1464 Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
1465 DAG.getConstant(EltSize, Idx.getValueType()));
1467 Idx = DAG.getZExtOrTrunc(Idx, dl, TLI.getPointerTy());
1468 StackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx, StackPtr);
1470 if (Op.getValueType().isVector())
1471 return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr,MachinePointerInfo(),
1472 false, false, false, 0);
1473 return DAG.getExtLoad(ISD::EXTLOAD, dl, Op.getValueType(), Ch, StackPtr,
1474 MachinePointerInfo(),
1475 Vec.getValueType().getVectorElementType(),
1476 false, false, false, 0);
1479 SDValue SelectionDAGLegalize::ExpandInsertToVectorThroughStack(SDValue Op) {
1480 assert(Op.getValueType().isVector() && "Non-vector insert subvector!");
1482 SDValue Vec = Op.getOperand(0);
1483 SDValue Part = Op.getOperand(1);
1484 SDValue Idx = Op.getOperand(2);
1487 // Store the value to a temporary stack slot, then LOAD the returned part.
1489 SDValue StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
1490 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
1491 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FI);
1493 // First store the whole vector.
1494 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, PtrInfo,
1497 // Then store the inserted part.
1499 // Add the offset to the index.
1501 Vec.getValueType().getVectorElementType().getSizeInBits()/8;
1503 Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
1504 DAG.getConstant(EltSize, Idx.getValueType()));
1505 Idx = DAG.getZExtOrTrunc(Idx, dl, TLI.getPointerTy());
1507 SDValue SubStackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx,
1510 // Store the subvector.
1511 Ch = DAG.getStore(DAG.getEntryNode(), dl, Part, SubStackPtr,
1512 MachinePointerInfo(), false, false, 0);
1514 // Finally, load the updated vector.
1515 return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, PtrInfo,
1516 false, false, false, 0);
1519 SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) {
1520 // We can't handle this case efficiently. Allocate a sufficiently
1521 // aligned object on the stack, store each element into it, then load
1522 // the result as a vector.
1523 // Create the stack frame object.
1524 EVT VT = Node->getValueType(0);
1525 EVT EltVT = VT.getVectorElementType();
1527 SDValue FIPtr = DAG.CreateStackTemporary(VT);
1528 int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
1529 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FI);
1531 // Emit a store of each element to the stack slot.
1532 SmallVector<SDValue, 8> Stores;
1533 unsigned TypeByteSize = EltVT.getSizeInBits() / 8;
1534 // Store (in the right endianness) the elements to memory.
1535 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1536 // Ignore undef elements.
1537 if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1539 unsigned Offset = TypeByteSize*i;
1541 SDValue Idx = DAG.getConstant(Offset, FIPtr.getValueType());
1542 Idx = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, Idx);
1544 // If the destination vector element type is narrower than the source
1545 // element type, only store the bits necessary.
1546 if (EltVT.bitsLT(Node->getOperand(i).getValueType().getScalarType())) {
1547 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
1548 Node->getOperand(i), Idx,
1549 PtrInfo.getWithOffset(Offset),
1550 EltVT, false, false, 0));
1552 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
1553 Node->getOperand(i), Idx,
1554 PtrInfo.getWithOffset(Offset),
1559 if (!Stores.empty()) // Not all undef elements?
1560 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
1562 StoreChain = DAG.getEntryNode();
1564 // Result is a load from the stack slot.
1565 return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo,
1566 false, false, false, 0);
1569 SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode* Node) {
1571 SDValue Tmp1 = Node->getOperand(0);
1572 SDValue Tmp2 = Node->getOperand(1);
1574 // Get the sign bit of the RHS. First obtain a value that has the same
1575 // sign as the sign bit, i.e. negative if and only if the sign bit is 1.
1577 EVT FloatVT = Tmp2.getValueType();
1578 EVT IVT = EVT::getIntegerVT(*DAG.getContext(), FloatVT.getSizeInBits());
1579 if (TLI.isTypeLegal(IVT)) {
1580 // Convert to an integer with the same sign bit.
1581 SignBit = DAG.getNode(ISD::BITCAST, dl, IVT, Tmp2);
1583 // Store the float to memory, then load the sign part out as an integer.
1584 MVT LoadTy = TLI.getPointerTy();
1585 // First create a temporary that is aligned for both the load and store.
1586 SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy);
1587 // Then store the float to it.
1589 DAG.getStore(DAG.getEntryNode(), dl, Tmp2, StackPtr, MachinePointerInfo(),
1591 if (TLI.isBigEndian()) {
1592 assert(FloatVT.isByteSized() && "Unsupported floating point type!");
1593 // Load out a legal integer with the same sign bit as the float.
1594 SignBit = DAG.getLoad(LoadTy, dl, Ch, StackPtr, MachinePointerInfo(),
1595 false, false, false, 0);
1596 } else { // Little endian
1597 SDValue LoadPtr = StackPtr;
1598 // The float may be wider than the integer we are going to load. Advance
1599 // the pointer so that the loaded integer will contain the sign bit.
1600 unsigned Strides = (FloatVT.getSizeInBits()-1)/LoadTy.getSizeInBits();
1601 unsigned ByteOffset = (Strides * LoadTy.getSizeInBits()) / 8;
1602 LoadPtr = DAG.getNode(ISD::ADD, dl, LoadPtr.getValueType(), LoadPtr,
1603 DAG.getConstant(ByteOffset, LoadPtr.getValueType()));
1604 // Load a legal integer containing the sign bit.
1605 SignBit = DAG.getLoad(LoadTy, dl, Ch, LoadPtr, MachinePointerInfo(),
1606 false, false, false, 0);
1607 // Move the sign bit to the top bit of the loaded integer.
1608 unsigned BitShift = LoadTy.getSizeInBits() -
1609 (FloatVT.getSizeInBits() - 8 * ByteOffset);
1610 assert(BitShift < LoadTy.getSizeInBits() && "Pointer advanced wrong?");
1612 SignBit = DAG.getNode(ISD::SHL, dl, LoadTy, SignBit,
1613 DAG.getConstant(BitShift,
1614 TLI.getShiftAmountTy(SignBit.getValueType())));
1617 // Now get the sign bit proper, by seeing whether the value is negative.
1618 SignBit = DAG.getSetCC(dl, getSetCCResultType(SignBit.getValueType()),
1619 SignBit, DAG.getConstant(0, SignBit.getValueType()),
1621 // Get the absolute value of the result.
1622 SDValue AbsVal = DAG.getNode(ISD::FABS, dl, Tmp1.getValueType(), Tmp1);
1623 // Select between the nabs and abs value based on the sign bit of
1625 return DAG.getSelect(dl, AbsVal.getValueType(), SignBit,
1626 DAG.getNode(ISD::FNEG, dl, AbsVal.getValueType(), AbsVal),
1630 void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node,
1631 SmallVectorImpl<SDValue> &Results) {
1632 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1633 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1634 " not tell us which reg is the stack pointer!");
1636 EVT VT = Node->getValueType(0);
1637 SDValue Tmp1 = SDValue(Node, 0);
1638 SDValue Tmp2 = SDValue(Node, 1);
1639 SDValue Tmp3 = Node->getOperand(2);
1640 SDValue Chain = Tmp1.getOperand(0);
1642 // Chain the dynamic stack allocation so that it doesn't modify the stack
1643 // pointer when other instructions are using the stack.
1644 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
1647 SDValue Size = Tmp2.getOperand(1);
1648 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
1649 Chain = SP.getValue(1);
1650 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
1651 unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
1652 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
1653 if (Align > StackAlign)
1654 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
1655 DAG.getConstant(-(uint64_t)Align, VT));
1656 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
1658 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
1659 DAG.getIntPtrConstant(0, true), SDValue(),
1662 Results.push_back(Tmp1);
1663 Results.push_back(Tmp2);
1666 /// LegalizeSetCCCondCode - Legalize a SETCC with given LHS and RHS and
1667 /// condition code CC on the current target.
1669 /// If the SETCC has been legalized using AND / OR, then the legalized node
1670 /// will be stored in LHS. RHS and CC will be set to SDValue(). NeedInvert
1671 /// will be set to false.
1673 /// If the SETCC has been legalized by using getSetCCSwappedOperands(),
1674 /// then the values of LHS and RHS will be swapped, CC will be set to the
1675 /// new condition, and NeedInvert will be set to false.
1677 /// If the SETCC has been legalized using the inverse condcode, then LHS and
1678 /// RHS will be unchanged, CC will set to the inverted condcode, and NeedInvert
1679 /// will be set to true. The caller must invert the result of the SETCC with
1680 /// SelectionDAG::getLogicalNOT() or take equivalent action to swap the effect
1681 /// of a true/false result.
1683 /// \returns true if the SetCC has been legalized, false if it hasn't.
1684 bool SelectionDAGLegalize::LegalizeSetCCCondCode(EVT VT,
1685 SDValue &LHS, SDValue &RHS,
1689 MVT OpVT = LHS.getSimpleValueType();
1690 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
1692 switch (TLI.getCondCodeAction(CCCode, OpVT)) {
1693 default: llvm_unreachable("Unknown condition code action!");
1694 case TargetLowering::Legal:
1697 case TargetLowering::Expand: {
1698 ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode);
1699 if (TLI.isCondCodeLegal(InvCC, OpVT)) {
1700 std::swap(LHS, RHS);
1701 CC = DAG.getCondCode(InvCC);
1704 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
1707 default: llvm_unreachable("Don't know how to expand this condition!");
1709 assert(TLI.getCondCodeAction(ISD::SETOEQ, OpVT)
1710 == TargetLowering::Legal
1711 && "If SETO is expanded, SETOEQ must be legal!");
1712 CC1 = ISD::SETOEQ; CC2 = ISD::SETOEQ; Opc = ISD::AND; break;
1714 assert(TLI.getCondCodeAction(ISD::SETUNE, OpVT)
1715 == TargetLowering::Legal
1716 && "If SETUO is expanded, SETUNE must be legal!");
1717 CC1 = ISD::SETUNE; CC2 = ISD::SETUNE; Opc = ISD::OR; break;
1730 // If we are floating point, assign and break, otherwise fall through.
1731 if (!OpVT.isInteger()) {
1732 // We can use the 4th bit to tell if we are the unordered
1733 // or ordered version of the opcode.
1734 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
1735 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
1736 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
1739 // Fallthrough if we are unsigned integer.
1744 // We only support using the inverted operation, which is computed above
1745 // and not a different manner of supporting expanding these cases.
1746 llvm_unreachable("Don't know how to expand this condition!");
1749 // Try inverting the result of the inverse condition.
1750 InvCC = CCCode == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ;
1751 if (TLI.isCondCodeLegal(InvCC, OpVT)) {
1752 CC = DAG.getCondCode(InvCC);
1756 // If inverting the condition didn't work then we have no means to expand
1758 llvm_unreachable("Don't know how to expand this condition!");
1761 SDValue SetCC1, SetCC2;
1762 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
1763 // If we aren't the ordered or unorder operation,
1764 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
1765 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1);
1766 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2);
1768 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
1769 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1);
1770 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2);
1772 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
1781 /// EmitStackConvert - Emit a store/load combination to the stack. This stores
1782 /// SrcOp to a stack slot of type SlotVT, truncating it if needed. It then does
1783 /// a load from the stack slot to DestVT, extending it if needed.
1784 /// The resultant code need not be legal.
1785 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp,
1789 // Create the stack frame object.
1791 TLI.getDataLayout()->getPrefTypeAlignment(SrcOp.getValueType().
1792 getTypeForEVT(*DAG.getContext()));
1793 SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign);
1795 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
1796 int SPFI = StackPtrFI->getIndex();
1797 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(SPFI);
1799 unsigned SrcSize = SrcOp.getValueType().getSizeInBits();
1800 unsigned SlotSize = SlotVT.getSizeInBits();
1801 unsigned DestSize = DestVT.getSizeInBits();
1802 Type *DestType = DestVT.getTypeForEVT(*DAG.getContext());
1803 unsigned DestAlign = TLI.getDataLayout()->getPrefTypeAlignment(DestType);
1805 // Emit a store to the stack slot. Use a truncstore if the input value is
1806 // later than DestVT.
1809 if (SrcSize > SlotSize)
1810 Store = DAG.getTruncStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
1811 PtrInfo, SlotVT, false, false, SrcAlign);
1813 assert(SrcSize == SlotSize && "Invalid store");
1814 Store = DAG.getStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
1815 PtrInfo, false, false, SrcAlign);
1818 // Result is a load from the stack slot.
1819 if (SlotSize == DestSize)
1820 return DAG.getLoad(DestVT, dl, Store, FIPtr, PtrInfo,
1821 false, false, false, DestAlign);
1823 assert(SlotSize < DestSize && "Unknown extension!");
1824 return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr,
1825 PtrInfo, SlotVT, false, false, false, DestAlign);
1828 SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
1830 // Create a vector sized/aligned stack slot, store the value to element #0,
1831 // then load the whole vector back out.
1832 SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
1834 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
1835 int SPFI = StackPtrFI->getIndex();
1837 SDValue Ch = DAG.getTruncStore(DAG.getEntryNode(), dl, Node->getOperand(0),
1839 MachinePointerInfo::getFixedStack(SPFI),
1840 Node->getValueType(0).getVectorElementType(),
1842 return DAG.getLoad(Node->getValueType(0), dl, Ch, StackPtr,
1843 MachinePointerInfo::getFixedStack(SPFI),
1844 false, false, false, 0);
1848 ExpandBVWithShuffles(SDNode *Node, SelectionDAG &DAG,
1849 const TargetLowering &TLI, SDValue &Res) {
1850 unsigned NumElems = Node->getNumOperands();
1852 EVT VT = Node->getValueType(0);
1854 // Try to group the scalars into pairs, shuffle the pairs together, then
1855 // shuffle the pairs of pairs together, etc. until the vector has
1856 // been built. This will work only if all of the necessary shuffle masks
1859 // We do this in two phases; first to check the legality of the shuffles,
1860 // and next, assuming that all shuffles are legal, to create the new nodes.
1861 for (int Phase = 0; Phase < 2; ++Phase) {
1862 SmallVector<std::pair<SDValue, SmallVector<int, 16> >, 16> IntermedVals,
1864 for (unsigned i = 0; i < NumElems; ++i) {
1865 SDValue V = Node->getOperand(i);
1866 if (V.getOpcode() == ISD::UNDEF)
1871 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, V);
1872 IntermedVals.push_back(std::make_pair(Vec, SmallVector<int, 16>(1, i)));
1875 while (IntermedVals.size() > 2) {
1876 NewIntermedVals.clear();
1877 for (unsigned i = 0, e = (IntermedVals.size() & ~1u); i < e; i += 2) {
1878 // This vector and the next vector are shuffled together (simply to
1879 // append the one to the other).
1880 SmallVector<int, 16> ShuffleVec(NumElems, -1);
1882 SmallVector<int, 16> FinalIndices;
1883 FinalIndices.reserve(IntermedVals[i].second.size() +
1884 IntermedVals[i+1].second.size());
1887 for (unsigned j = 0, f = IntermedVals[i].second.size(); j != f;
1890 FinalIndices.push_back(IntermedVals[i].second[j]);
1892 for (unsigned j = 0, f = IntermedVals[i+1].second.size(); j != f;
1894 ShuffleVec[k] = NumElems + j;
1895 FinalIndices.push_back(IntermedVals[i+1].second[j]);
1900 Shuffle = DAG.getVectorShuffle(VT, dl, IntermedVals[i].first,
1901 IntermedVals[i+1].first,
1903 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
1905 NewIntermedVals.push_back(std::make_pair(Shuffle, FinalIndices));
1908 // If we had an odd number of defined values, then append the last
1909 // element to the array of new vectors.
1910 if ((IntermedVals.size() & 1) != 0)
1911 NewIntermedVals.push_back(IntermedVals.back());
1913 IntermedVals.swap(NewIntermedVals);
1916 assert(IntermedVals.size() <= 2 && IntermedVals.size() > 0 &&
1917 "Invalid number of intermediate vectors");
1918 SDValue Vec1 = IntermedVals[0].first;
1920 if (IntermedVals.size() > 1)
1921 Vec2 = IntermedVals[1].first;
1923 Vec2 = DAG.getUNDEF(VT);
1925 SmallVector<int, 16> ShuffleVec(NumElems, -1);
1926 for (unsigned i = 0, e = IntermedVals[0].second.size(); i != e; ++i)
1927 ShuffleVec[IntermedVals[0].second[i]] = i;
1928 for (unsigned i = 0, e = IntermedVals[1].second.size(); i != e; ++i)
1929 ShuffleVec[IntermedVals[1].second[i]] = NumElems + i;
1932 Res = DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec.data());
1933 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
1940 /// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
1941 /// support the operation, but do support the resultant vector type.
1942 SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
1943 unsigned NumElems = Node->getNumOperands();
1944 SDValue Value1, Value2;
1946 EVT VT = Node->getValueType(0);
1947 EVT OpVT = Node->getOperand(0).getValueType();
1948 EVT EltVT = VT.getVectorElementType();
1950 // If the only non-undef value is the low element, turn this into a
1951 // SCALAR_TO_VECTOR node. If this is { X, X, X, X }, determine X.
1952 bool isOnlyLowElement = true;
1953 bool MoreThanTwoValues = false;
1954 bool isConstant = true;
1955 for (unsigned i = 0; i < NumElems; ++i) {
1956 SDValue V = Node->getOperand(i);
1957 if (V.getOpcode() == ISD::UNDEF)
1960 isOnlyLowElement = false;
1961 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
1964 if (!Value1.getNode()) {
1966 } else if (!Value2.getNode()) {
1969 } else if (V != Value1 && V != Value2) {
1970 MoreThanTwoValues = true;
1974 if (!Value1.getNode())
1975 return DAG.getUNDEF(VT);
1977 if (isOnlyLowElement)
1978 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
1980 // If all elements are constants, create a load from the constant pool.
1982 SmallVector<Constant*, 16> CV;
1983 for (unsigned i = 0, e = NumElems; i != e; ++i) {
1984 if (ConstantFPSDNode *V =
1985 dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
1986 CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
1987 } else if (ConstantSDNode *V =
1988 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
1990 CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
1992 // If OpVT and EltVT don't match, EltVT is not legal and the
1993 // element values have been promoted/truncated earlier. Undo this;
1994 // we don't want a v16i8 to become a v16i32 for example.
1995 const ConstantInt *CI = V->getConstantIntValue();
1996 CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()),
1997 CI->getZExtValue()));
2000 assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
2001 Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext());
2002 CV.push_back(UndefValue::get(OpNTy));
2005 Constant *CP = ConstantVector::get(CV);
2006 SDValue CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
2007 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
2008 return DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
2009 MachinePointerInfo::getConstantPool(),
2010 false, false, false, Alignment);
2013 SmallSet<SDValue, 16> DefinedValues;
2014 for (unsigned i = 0; i < NumElems; ++i) {
2015 if (Node->getOperand(i).getOpcode() == ISD::UNDEF)
2017 DefinedValues.insert(Node->getOperand(i));
2020 if (TLI.shouldExpandBuildVectorWithShuffles(VT, DefinedValues.size())) {
2021 if (!MoreThanTwoValues) {
2022 SmallVector<int, 8> ShuffleVec(NumElems, -1);
2023 for (unsigned i = 0; i < NumElems; ++i) {
2024 SDValue V = Node->getOperand(i);
2025 if (V.getOpcode() == ISD::UNDEF)
2027 ShuffleVec[i] = V == Value1 ? 0 : NumElems;
2029 if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) {
2030 // Get the splatted value into the low element of a vector register.
2031 SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1);
2033 if (Value2.getNode())
2034 Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2);
2036 Vec2 = DAG.getUNDEF(VT);
2038 // Return shuffle(LowValVec, undef, <0,0,0,0>)
2039 return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec.data());
2043 if (ExpandBVWithShuffles(Node, DAG, TLI, Res))
2048 // Otherwise, we can't handle this case efficiently.
2049 return ExpandVectorBuildThroughStack(Node);
2052 // ExpandLibCall - Expand a node into a call to a libcall. If the result value
2053 // does not fit into a register, return the lo part and set the hi part to the
2054 // by-reg argument. If it does fit into a single register, return the result
2055 // and leave the Hi part unset.
2056 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
2058 TargetLowering::ArgListTy Args;
2059 TargetLowering::ArgListEntry Entry;
2060 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
2061 EVT ArgVT = Node->getOperand(i).getValueType();
2062 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2063 Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy;
2064 Entry.isSExt = isSigned;
2065 Entry.isZExt = !isSigned;
2066 Args.push_back(Entry);
2068 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2069 TLI.getPointerTy());
2071 Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
2073 // By default, the input chain to this libcall is the entry node of the
2074 // function. If the libcall is going to be emitted as a tail call then
2075 // TLI.isUsedByReturnOnly will change it to the right chain if the return
2076 // node which is being folded has a non-entry input chain.
2077 SDValue InChain = DAG.getEntryNode();
2079 // isTailCall may be true since the callee does not reference caller stack
2080 // frame. Check if it's in the right position.
2081 SDValue TCChain = InChain;
2082 bool isTailCall = TLI.isInTailCallPosition(DAG, Node, TCChain);
2086 TargetLowering::CallLoweringInfo CLI(DAG);
2087 CLI.setDebugLoc(SDLoc(Node)).setChain(InChain)
2088 .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
2089 .setTailCall(isTailCall).setSExtResult(isSigned).setZExtResult(!isSigned);
2091 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2093 if (!CallInfo.second.getNode())
2094 // It's a tailcall, return the chain (which is the DAG root).
2095 return DAG.getRoot();
2097 return CallInfo.first;
2100 /// ExpandLibCall - Generate a libcall taking the given operands as arguments
2101 /// and returning a result of type RetVT.
2102 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, EVT RetVT,
2103 const SDValue *Ops, unsigned NumOps,
2104 bool isSigned, SDLoc dl) {
2105 TargetLowering::ArgListTy Args;
2106 Args.reserve(NumOps);
2108 TargetLowering::ArgListEntry Entry;
2109 for (unsigned i = 0; i != NumOps; ++i) {
2110 Entry.Node = Ops[i];
2111 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
2112 Entry.isSExt = isSigned;
2113 Entry.isZExt = !isSigned;
2114 Args.push_back(Entry);
2116 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2117 TLI.getPointerTy());
2119 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2121 TargetLowering::CallLoweringInfo CLI(DAG);
2122 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
2123 .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
2124 .setSExtResult(isSigned).setZExtResult(!isSigned);
2126 std::pair<SDValue,SDValue> CallInfo = TLI.LowerCallTo(CLI);
2128 return CallInfo.first;
2131 // ExpandChainLibCall - Expand a node into a call to a libcall. Similar to
2132 // ExpandLibCall except that the first operand is the in-chain.
2133 std::pair<SDValue, SDValue>
2134 SelectionDAGLegalize::ExpandChainLibCall(RTLIB::Libcall LC,
2137 SDValue InChain = Node->getOperand(0);
2139 TargetLowering::ArgListTy Args;
2140 TargetLowering::ArgListEntry Entry;
2141 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) {
2142 EVT ArgVT = Node->getOperand(i).getValueType();
2143 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2144 Entry.Node = Node->getOperand(i);
2146 Entry.isSExt = isSigned;
2147 Entry.isZExt = !isSigned;
2148 Args.push_back(Entry);
2150 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2151 TLI.getPointerTy());
2153 Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
2155 TargetLowering::CallLoweringInfo CLI(DAG);
2156 CLI.setDebugLoc(SDLoc(Node)).setChain(InChain)
2157 .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
2158 .setSExtResult(isSigned).setZExtResult(!isSigned);
2160 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2165 SDValue SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
2166 RTLIB::Libcall Call_F32,
2167 RTLIB::Libcall Call_F64,
2168 RTLIB::Libcall Call_F80,
2169 RTLIB::Libcall Call_F128,
2170 RTLIB::Libcall Call_PPCF128) {
2172 switch (Node->getSimpleValueType(0).SimpleTy) {
2173 default: llvm_unreachable("Unexpected request for libcall!");
2174 case MVT::f32: LC = Call_F32; break;
2175 case MVT::f64: LC = Call_F64; break;
2176 case MVT::f80: LC = Call_F80; break;
2177 case MVT::f128: LC = Call_F128; break;
2178 case MVT::ppcf128: LC = Call_PPCF128; break;
2180 return ExpandLibCall(LC, Node, false);
2183 SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned,
2184 RTLIB::Libcall Call_I8,
2185 RTLIB::Libcall Call_I16,
2186 RTLIB::Libcall Call_I32,
2187 RTLIB::Libcall Call_I64,
2188 RTLIB::Libcall Call_I128) {
2190 switch (Node->getSimpleValueType(0).SimpleTy) {
2191 default: llvm_unreachable("Unexpected request for libcall!");
2192 case MVT::i8: LC = Call_I8; break;
2193 case MVT::i16: LC = Call_I16; break;
2194 case MVT::i32: LC = Call_I32; break;
2195 case MVT::i64: LC = Call_I64; break;
2196 case MVT::i128: LC = Call_I128; break;
2198 return ExpandLibCall(LC, Node, isSigned);
2201 /// isDivRemLibcallAvailable - Return true if divmod libcall is available.
2202 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2203 const TargetLowering &TLI) {
2205 switch (Node->getSimpleValueType(0).SimpleTy) {
2206 default: llvm_unreachable("Unexpected request for libcall!");
2207 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2208 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2209 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2210 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2211 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2214 return TLI.getLibcallName(LC) != nullptr;
2217 /// useDivRem - Only issue divrem libcall if both quotient and remainder are
2219 static bool useDivRem(SDNode *Node, bool isSigned, bool isDIV) {
2220 // The other use might have been replaced with a divrem already.
2221 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2222 unsigned OtherOpcode = 0;
2224 OtherOpcode = isDIV ? ISD::SREM : ISD::SDIV;
2226 OtherOpcode = isDIV ? ISD::UREM : ISD::UDIV;
2228 SDValue Op0 = Node->getOperand(0);
2229 SDValue Op1 = Node->getOperand(1);
2230 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2231 UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2235 if ((User->getOpcode() == OtherOpcode || User->getOpcode() == DivRemOpc) &&
2236 User->getOperand(0) == Op0 &&
2237 User->getOperand(1) == Op1)
2243 /// ExpandDivRemLibCall - Issue libcalls to __{u}divmod to compute div / rem
2246 SelectionDAGLegalize::ExpandDivRemLibCall(SDNode *Node,
2247 SmallVectorImpl<SDValue> &Results) {
2248 unsigned Opcode = Node->getOpcode();
2249 bool isSigned = Opcode == ISD::SDIVREM;
2252 switch (Node->getSimpleValueType(0).SimpleTy) {
2253 default: llvm_unreachable("Unexpected request for libcall!");
2254 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2255 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2256 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2257 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2258 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2261 // The input chain to this libcall is the entry node of the function.
2262 // Legalizing the call will automatically add the previous call to the
2264 SDValue InChain = DAG.getEntryNode();
2266 EVT RetVT = Node->getValueType(0);
2267 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2269 TargetLowering::ArgListTy Args;
2270 TargetLowering::ArgListEntry Entry;
2271 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
2272 EVT ArgVT = Node->getOperand(i).getValueType();
2273 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2274 Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy;
2275 Entry.isSExt = isSigned;
2276 Entry.isZExt = !isSigned;
2277 Args.push_back(Entry);
2280 // Also pass the return address of the remainder.
2281 SDValue FIPtr = DAG.CreateStackTemporary(RetVT);
2283 Entry.Ty = RetTy->getPointerTo();
2284 Entry.isSExt = isSigned;
2285 Entry.isZExt = !isSigned;
2286 Args.push_back(Entry);
2288 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2289 TLI.getPointerTy());
2292 TargetLowering::CallLoweringInfo CLI(DAG);
2293 CLI.setDebugLoc(dl).setChain(InChain)
2294 .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
2295 .setSExtResult(isSigned).setZExtResult(!isSigned);
2297 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2299 // Remainder is loaded back from the stack frame.
2300 SDValue Rem = DAG.getLoad(RetVT, dl, CallInfo.second, FIPtr,
2301 MachinePointerInfo(), false, false, false, 0);
2302 Results.push_back(CallInfo.first);
2303 Results.push_back(Rem);
2306 /// isSinCosLibcallAvailable - Return true if sincos libcall is available.
2307 static bool isSinCosLibcallAvailable(SDNode *Node, const TargetLowering &TLI) {
2309 switch (Node->getSimpleValueType(0).SimpleTy) {
2310 default: llvm_unreachable("Unexpected request for libcall!");
2311 case MVT::f32: LC = RTLIB::SINCOS_F32; break;
2312 case MVT::f64: LC = RTLIB::SINCOS_F64; break;
2313 case MVT::f80: LC = RTLIB::SINCOS_F80; break;
2314 case MVT::f128: LC = RTLIB::SINCOS_F128; break;
2315 case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break;
2317 return TLI.getLibcallName(LC) != nullptr;
2320 /// canCombineSinCosLibcall - Return true if sincos libcall is available and
2321 /// can be used to combine sin and cos.
2322 static bool canCombineSinCosLibcall(SDNode *Node, const TargetLowering &TLI,
2323 const TargetMachine &TM) {
2324 if (!isSinCosLibcallAvailable(Node, TLI))
2326 // GNU sin/cos functions set errno while sincos does not. Therefore
2327 // combining sin and cos is only safe if unsafe-fpmath is enabled.
2328 bool isGNU = Triple(TM.getTargetTriple()).getEnvironment() == Triple::GNU;
2329 if (isGNU && !TM.Options.UnsafeFPMath)
2334 /// useSinCos - Only issue sincos libcall if both sin and cos are
2336 static bool useSinCos(SDNode *Node) {
2337 unsigned OtherOpcode = Node->getOpcode() == ISD::FSIN
2338 ? ISD::FCOS : ISD::FSIN;
2340 SDValue Op0 = Node->getOperand(0);
2341 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2342 UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2346 // The other user might have been turned into sincos already.
2347 if (User->getOpcode() == OtherOpcode || User->getOpcode() == ISD::FSINCOS)
2353 /// ExpandSinCosLibCall - Issue libcalls to sincos to compute sin / cos
2356 SelectionDAGLegalize::ExpandSinCosLibCall(SDNode *Node,
2357 SmallVectorImpl<SDValue> &Results) {
2359 switch (Node->getSimpleValueType(0).SimpleTy) {
2360 default: llvm_unreachable("Unexpected request for libcall!");
2361 case MVT::f32: LC = RTLIB::SINCOS_F32; break;
2362 case MVT::f64: LC = RTLIB::SINCOS_F64; break;
2363 case MVT::f80: LC = RTLIB::SINCOS_F80; break;
2364 case MVT::f128: LC = RTLIB::SINCOS_F128; break;
2365 case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break;
2368 // The input chain to this libcall is the entry node of the function.
2369 // Legalizing the call will automatically add the previous call to the
2371 SDValue InChain = DAG.getEntryNode();
2373 EVT RetVT = Node->getValueType(0);
2374 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2376 TargetLowering::ArgListTy Args;
2377 TargetLowering::ArgListEntry Entry;
2379 // Pass the argument.
2380 Entry.Node = Node->getOperand(0);
2382 Entry.isSExt = false;
2383 Entry.isZExt = false;
2384 Args.push_back(Entry);
2386 // Pass the return address of sin.
2387 SDValue SinPtr = DAG.CreateStackTemporary(RetVT);
2388 Entry.Node = SinPtr;
2389 Entry.Ty = RetTy->getPointerTo();
2390 Entry.isSExt = false;
2391 Entry.isZExt = false;
2392 Args.push_back(Entry);
2394 // Also pass the return address of the cos.
2395 SDValue CosPtr = DAG.CreateStackTemporary(RetVT);
2396 Entry.Node = CosPtr;
2397 Entry.Ty = RetTy->getPointerTo();
2398 Entry.isSExt = false;
2399 Entry.isZExt = false;
2400 Args.push_back(Entry);
2402 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2403 TLI.getPointerTy());
2406 TargetLowering::CallLoweringInfo CLI(DAG);
2407 CLI.setDebugLoc(dl).setChain(InChain)
2408 .setCallee(TLI.getLibcallCallingConv(LC),
2409 Type::getVoidTy(*DAG.getContext()), Callee, std::move(Args), 0);
2411 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2413 Results.push_back(DAG.getLoad(RetVT, dl, CallInfo.second, SinPtr,
2414 MachinePointerInfo(), false, false, false, 0));
2415 Results.push_back(DAG.getLoad(RetVT, dl, CallInfo.second, CosPtr,
2416 MachinePointerInfo(), false, false, false, 0));
2419 /// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
2420 /// INT_TO_FP operation of the specified operand when the target requests that
2421 /// we expand it. At this point, we know that the result and operand types are
2422 /// legal for the target.
2423 SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
2427 if (Op0.getValueType() == MVT::i32 && TLI.isTypeLegal(MVT::f64)) {
2428 // simple 32-bit [signed|unsigned] integer to float/double expansion
2430 // Get the stack frame index of a 8 byte buffer.
2431 SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
2433 // word offset constant for Hi/Lo address computation
2434 SDValue WordOff = DAG.getConstant(sizeof(int), StackSlot.getValueType());
2435 // set up Hi and Lo (into buffer) address based on endian
2436 SDValue Hi = StackSlot;
2437 SDValue Lo = DAG.getNode(ISD::ADD, dl, StackSlot.getValueType(),
2438 StackSlot, WordOff);
2439 if (TLI.isLittleEndian())
2442 // if signed map to unsigned space
2445 // constant used to invert sign bit (signed to unsigned mapping)
2446 SDValue SignBit = DAG.getConstant(0x80000000u, MVT::i32);
2447 Op0Mapped = DAG.getNode(ISD::XOR, dl, MVT::i32, Op0, SignBit);
2451 // store the lo of the constructed double - based on integer input
2452 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl,
2453 Op0Mapped, Lo, MachinePointerInfo(),
2455 // initial hi portion of constructed double
2456 SDValue InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
2457 // store the hi of the constructed double - biased exponent
2458 SDValue Store2 = DAG.getStore(Store1, dl, InitialHi, Hi,
2459 MachinePointerInfo(),
2461 // load the constructed double
2462 SDValue Load = DAG.getLoad(MVT::f64, dl, Store2, StackSlot,
2463 MachinePointerInfo(), false, false, false, 0);
2464 // FP constant to bias correct the final result
2465 SDValue Bias = DAG.getConstantFP(isSigned ?
2466 BitsToDouble(0x4330000080000000ULL) :
2467 BitsToDouble(0x4330000000000000ULL),
2469 // subtract the bias
2470 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
2473 // handle final rounding
2474 if (DestVT == MVT::f64) {
2477 } else if (DestVT.bitsLT(MVT::f64)) {
2478 Result = DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
2479 DAG.getIntPtrConstant(0));
2480 } else if (DestVT.bitsGT(MVT::f64)) {
2481 Result = DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
2485 assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
2486 // Code below here assumes !isSigned without checking again.
2488 // Implementation of unsigned i64 to f64 following the algorithm in
2489 // __floatundidf in compiler_rt. This implementation has the advantage
2490 // of performing rounding correctly, both in the default rounding mode
2491 // and in all alternate rounding modes.
2492 // TODO: Generalize this for use with other types.
2493 if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f64) {
2495 DAG.getConstant(UINT64_C(0x4330000000000000), MVT::i64);
2496 SDValue TwoP84PlusTwoP52 =
2497 DAG.getConstantFP(BitsToDouble(UINT64_C(0x4530000000100000)), MVT::f64);
2499 DAG.getConstant(UINT64_C(0x4530000000000000), MVT::i64);
2501 SDValue Lo = DAG.getZeroExtendInReg(Op0, dl, MVT::i32);
2502 SDValue Hi = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0,
2503 DAG.getConstant(32, MVT::i64));
2504 SDValue LoOr = DAG.getNode(ISD::OR, dl, MVT::i64, Lo, TwoP52);
2505 SDValue HiOr = DAG.getNode(ISD::OR, dl, MVT::i64, Hi, TwoP84);
2506 SDValue LoFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, LoOr);
2507 SDValue HiFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, HiOr);
2508 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, MVT::f64, HiFlt,
2510 return DAG.getNode(ISD::FADD, dl, MVT::f64, LoFlt, HiSub);
2513 // Implementation of unsigned i64 to f32.
2514 // TODO: Generalize this for use with other types.
2515 if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f32) {
2516 // For unsigned conversions, convert them to signed conversions using the
2517 // algorithm from the x86_64 __floatundidf in compiler_rt.
2519 SDValue Fast = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Op0);
2521 SDValue ShiftConst =
2522 DAG.getConstant(1, TLI.getShiftAmountTy(Op0.getValueType()));
2523 SDValue Shr = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0, ShiftConst);
2524 SDValue AndConst = DAG.getConstant(1, MVT::i64);
2525 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0, AndConst);
2526 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And, Shr);
2528 SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Or);
2529 SDValue Slow = DAG.getNode(ISD::FADD, dl, MVT::f32, SignCvt, SignCvt);
2531 // TODO: This really should be implemented using a branch rather than a
2532 // select. We happen to get lucky and machinesink does the right
2533 // thing most of the time. This would be a good candidate for a
2534 //pseudo-op, or, even better, for whole-function isel.
2535 SDValue SignBitTest = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
2536 Op0, DAG.getConstant(0, MVT::i64), ISD::SETLT);
2537 return DAG.getSelect(dl, MVT::f32, SignBitTest, Slow, Fast);
2540 // Otherwise, implement the fully general conversion.
2542 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
2543 DAG.getConstant(UINT64_C(0xfffffffffffff800), MVT::i64));
2544 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And,
2545 DAG.getConstant(UINT64_C(0x800), MVT::i64));
2546 SDValue And2 = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
2547 DAG.getConstant(UINT64_C(0x7ff), MVT::i64));
2548 SDValue Ne = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
2549 And2, DAG.getConstant(UINT64_C(0), MVT::i64), ISD::SETNE);
2550 SDValue Sel = DAG.getSelect(dl, MVT::i64, Ne, Or, Op0);
2551 SDValue Ge = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
2552 Op0, DAG.getConstant(UINT64_C(0x0020000000000000), MVT::i64),
2554 SDValue Sel2 = DAG.getSelect(dl, MVT::i64, Ge, Sel, Op0);
2555 EVT SHVT = TLI.getShiftAmountTy(Sel2.getValueType());
2557 SDValue Sh = DAG.getNode(ISD::SRL, dl, MVT::i64, Sel2,
2558 DAG.getConstant(32, SHVT));
2559 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sh);
2560 SDValue Fcvt = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Trunc);
2562 DAG.getConstantFP(BitsToDouble(UINT64_C(0x41f0000000000000)), MVT::f64);
2563 SDValue Fmul = DAG.getNode(ISD::FMUL, dl, MVT::f64, TwoP32, Fcvt);
2564 SDValue Lo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sel2);
2565 SDValue Fcvt2 = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Lo);
2566 SDValue Fadd = DAG.getNode(ISD::FADD, dl, MVT::f64, Fmul, Fcvt2);
2567 return DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Fadd,
2568 DAG.getIntPtrConstant(0));
2571 SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2573 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(Op0.getValueType()),
2574 Op0, DAG.getConstant(0, Op0.getValueType()),
2576 SDValue Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
2577 SDValue CstOffset = DAG.getSelect(dl, Zero.getValueType(),
2578 SignSet, Four, Zero);
2580 // If the sign bit of the integer is set, the large number will be treated
2581 // as a negative number. To counteract this, the dynamic code adds an
2582 // offset depending on the data type.
2584 switch (Op0.getSimpleValueType().SimpleTy) {
2585 default: llvm_unreachable("Unsupported integer type!");
2586 case MVT::i8 : FF = 0x43800000ULL; break; // 2^8 (as a float)
2587 case MVT::i16: FF = 0x47800000ULL; break; // 2^16 (as a float)
2588 case MVT::i32: FF = 0x4F800000ULL; break; // 2^32 (as a float)
2589 case MVT::i64: FF = 0x5F800000ULL; break; // 2^64 (as a float)
2591 if (TLI.isLittleEndian()) FF <<= 32;
2592 Constant *FudgeFactor = ConstantInt::get(
2593 Type::getInt64Ty(*DAG.getContext()), FF);
2595 SDValue CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
2596 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
2597 CPIdx = DAG.getNode(ISD::ADD, dl, CPIdx.getValueType(), CPIdx, CstOffset);
2598 Alignment = std::min(Alignment, 4u);
2600 if (DestVT == MVT::f32)
2601 FudgeInReg = DAG.getLoad(MVT::f32, dl, DAG.getEntryNode(), CPIdx,
2602 MachinePointerInfo::getConstantPool(),
2603 false, false, false, Alignment);
2605 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT,
2606 DAG.getEntryNode(), CPIdx,
2607 MachinePointerInfo::getConstantPool(),
2608 MVT::f32, false, false, false, Alignment);
2609 HandleSDNode Handle(Load);
2610 LegalizeOp(Load.getNode());
2611 FudgeInReg = Handle.getValue();
2614 return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
2617 /// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
2618 /// *INT_TO_FP operation of the specified operand when the target requests that
2619 /// we promote it. At this point, we know that the result and operand types are
2620 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
2621 /// operation that takes a larger input.
2622 SDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp,
2626 // First step, figure out the appropriate *INT_TO_FP operation to use.
2627 EVT NewInTy = LegalOp.getValueType();
2629 unsigned OpToUse = 0;
2631 // Scan for the appropriate larger type to use.
2633 NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1);
2634 assert(NewInTy.isInteger() && "Ran out of possibilities!");
2636 // If the target supports SINT_TO_FP of this type, use it.
2637 if (TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, NewInTy)) {
2638 OpToUse = ISD::SINT_TO_FP;
2641 if (isSigned) continue;
2643 // If the target supports UINT_TO_FP of this type, use it.
2644 if (TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, NewInTy)) {
2645 OpToUse = ISD::UINT_TO_FP;
2649 // Otherwise, try a larger type.
2652 // Okay, we found the operation and type to use. Zero extend our input to the
2653 // desired type then run the operation on it.
2654 return DAG.getNode(OpToUse, dl, DestVT,
2655 DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
2656 dl, NewInTy, LegalOp));
2659 /// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
2660 /// FP_TO_*INT operation of the specified operand when the target requests that
2661 /// we promote it. At this point, we know that the result and operand types are
2662 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
2663 /// operation that returns a larger result.
2664 SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp,
2668 // First step, figure out the appropriate FP_TO*INT operation to use.
2669 EVT NewOutTy = DestVT;
2671 unsigned OpToUse = 0;
2673 // Scan for the appropriate larger type to use.
2675 NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1);
2676 assert(NewOutTy.isInteger() && "Ran out of possibilities!");
2678 // A larger signed type can hold all unsigned values of the requested type,
2679 // so using FP_TO_SINT is valid
2680 if (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NewOutTy)) {
2681 OpToUse = ISD::FP_TO_SINT;
2685 // However, if the value may be < 0.0, we *must* use some FP_TO_SINT.
2686 if (!isSigned && TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NewOutTy)) {
2687 OpToUse = ISD::FP_TO_UINT;
2691 // Otherwise, try a larger type.
2695 // Okay, we found the operation and type to use.
2696 SDValue Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
2698 // Truncate the result of the extended FP_TO_*INT operation to the desired
2700 return DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
2703 /// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
2705 SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op, SDLoc dl) {
2706 EVT VT = Op.getValueType();
2707 EVT SHVT = TLI.getShiftAmountTy(VT);
2708 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
2709 switch (VT.getSimpleVT().SimpleTy) {
2710 default: llvm_unreachable("Unhandled Expand type in BSWAP!");
2712 Tmp2 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2713 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2714 return DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
2716 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2717 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2718 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2719 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2720 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
2721 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, VT));
2722 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2723 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2724 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2726 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, SHVT));
2727 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, SHVT));
2728 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2729 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2730 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2731 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2732 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, SHVT));
2733 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, SHVT));
2734 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
2735 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
2736 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
2737 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
2738 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
2739 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
2740 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
2741 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
2742 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2743 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2744 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
2745 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2746 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
2750 /// ExpandBitCount - Expand the specified bitcount instruction into operations.
2752 SDValue SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDValue Op,
2755 default: llvm_unreachable("Cannot expand this yet!");
2757 EVT VT = Op.getValueType();
2758 EVT ShVT = TLI.getShiftAmountTy(VT);
2759 unsigned Len = VT.getSizeInBits();
2761 assert(VT.isInteger() && Len <= 128 && Len % 8 == 0 &&
2762 "CTPOP not implemented for this type.");
2764 // This is the "best" algorithm from
2765 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
2767 SDValue Mask55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), VT);
2768 SDValue Mask33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), VT);
2769 SDValue Mask0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), VT);
2770 SDValue Mask01 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), VT);
2772 // v = v - ((v >> 1) & 0x55555555...)
2773 Op = DAG.getNode(ISD::SUB, dl, VT, Op,
2774 DAG.getNode(ISD::AND, dl, VT,
2775 DAG.getNode(ISD::SRL, dl, VT, Op,
2776 DAG.getConstant(1, ShVT)),
2778 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
2779 Op = DAG.getNode(ISD::ADD, dl, VT,
2780 DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
2781 DAG.getNode(ISD::AND, dl, VT,
2782 DAG.getNode(ISD::SRL, dl, VT, Op,
2783 DAG.getConstant(2, ShVT)),
2785 // v = (v + (v >> 4)) & 0x0F0F0F0F...
2786 Op = DAG.getNode(ISD::AND, dl, VT,
2787 DAG.getNode(ISD::ADD, dl, VT, Op,
2788 DAG.getNode(ISD::SRL, dl, VT, Op,
2789 DAG.getConstant(4, ShVT))),
2791 // v = (v * 0x01010101...) >> (Len - 8)
2792 Op = DAG.getNode(ISD::SRL, dl, VT,
2793 DAG.getNode(ISD::MUL, dl, VT, Op, Mask01),
2794 DAG.getConstant(Len - 8, ShVT));
2798 case ISD::CTLZ_ZERO_UNDEF:
2799 // This trivially expands to CTLZ.
2800 return DAG.getNode(ISD::CTLZ, dl, Op.getValueType(), Op);
2802 // for now, we do this:
2803 // x = x | (x >> 1);
2804 // x = x | (x >> 2);
2806 // x = x | (x >>16);
2807 // x = x | (x >>32); // for 64-bit input
2808 // return popcount(~x);
2810 // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
2811 EVT VT = Op.getValueType();
2812 EVT ShVT = TLI.getShiftAmountTy(VT);
2813 unsigned len = VT.getSizeInBits();
2814 for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
2815 SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
2816 Op = DAG.getNode(ISD::OR, dl, VT, Op,
2817 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3));
2819 Op = DAG.getNOT(dl, Op, VT);
2820 return DAG.getNode(ISD::CTPOP, dl, VT, Op);
2822 case ISD::CTTZ_ZERO_UNDEF:
2823 // This trivially expands to CTTZ.
2824 return DAG.getNode(ISD::CTTZ, dl, Op.getValueType(), Op);
2826 // for now, we use: { return popcount(~x & (x - 1)); }
2827 // unless the target has ctlz but not ctpop, in which case we use:
2828 // { return 32 - nlz(~x & (x-1)); }
2829 // see also http://www.hackersdelight.org/HDcode/ntz.cc
2830 EVT VT = Op.getValueType();
2831 SDValue Tmp3 = DAG.getNode(ISD::AND, dl, VT,
2832 DAG.getNOT(dl, Op, VT),
2833 DAG.getNode(ISD::SUB, dl, VT, Op,
2834 DAG.getConstant(1, VT)));
2835 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
2836 if (!TLI.isOperationLegalOrCustom(ISD::CTPOP, VT) &&
2837 TLI.isOperationLegalOrCustom(ISD::CTLZ, VT))
2838 return DAG.getNode(ISD::SUB, dl, VT,
2839 DAG.getConstant(VT.getSizeInBits(), VT),
2840 DAG.getNode(ISD::CTLZ, dl, VT, Tmp3));
2841 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp3);
2846 std::pair <SDValue, SDValue> SelectionDAGLegalize::ExpandAtomic(SDNode *Node) {
2847 unsigned Opc = Node->getOpcode();
2848 MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
2853 llvm_unreachable("Unhandled atomic intrinsic Expand!");
2854 case ISD::ATOMIC_SWAP:
2855 switch (VT.SimpleTy) {
2856 default: llvm_unreachable("Unexpected value type for atomic!");
2857 case MVT::i8: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_1; break;
2858 case MVT::i16: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_2; break;
2859 case MVT::i32: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_4; break;
2860 case MVT::i64: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_8; break;
2861 case MVT::i128:LC = RTLIB::SYNC_LOCK_TEST_AND_SET_16;break;
2864 case ISD::ATOMIC_CMP_SWAP:
2865 switch (VT.SimpleTy) {
2866 default: llvm_unreachable("Unexpected value type for atomic!");
2867 case MVT::i8: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_1; break;
2868 case MVT::i16: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_2; break;
2869 case MVT::i32: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_4; break;
2870 case MVT::i64: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_8; break;
2871 case MVT::i128:LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_16;break;
2874 case ISD::ATOMIC_LOAD_ADD:
2875 switch (VT.SimpleTy) {
2876 default: llvm_unreachable("Unexpected value type for atomic!");
2877 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_ADD_1; break;
2878 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_ADD_2; break;
2879 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_ADD_4; break;
2880 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_ADD_8; break;
2881 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_ADD_16;break;
2884 case ISD::ATOMIC_LOAD_SUB:
2885 switch (VT.SimpleTy) {
2886 default: llvm_unreachable("Unexpected value type for atomic!");
2887 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_SUB_1; break;
2888 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_SUB_2; break;
2889 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_SUB_4; break;
2890 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_SUB_8; break;
2891 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_SUB_16;break;
2894 case ISD::ATOMIC_LOAD_AND:
2895 switch (VT.SimpleTy) {
2896 default: llvm_unreachable("Unexpected value type for atomic!");
2897 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_AND_1; break;
2898 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_AND_2; break;
2899 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_AND_4; break;
2900 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_AND_8; break;
2901 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_AND_16;break;
2904 case ISD::ATOMIC_LOAD_OR:
2905 switch (VT.SimpleTy) {
2906 default: llvm_unreachable("Unexpected value type for atomic!");
2907 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_OR_1; break;
2908 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_OR_2; break;
2909 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_OR_4; break;
2910 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_OR_8; break;
2911 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_OR_16;break;
2914 case ISD::ATOMIC_LOAD_XOR:
2915 switch (VT.SimpleTy) {
2916 default: llvm_unreachable("Unexpected value type for atomic!");
2917 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_XOR_1; break;
2918 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_XOR_2; break;
2919 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_XOR_4; break;
2920 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_XOR_8; break;
2921 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_XOR_16;break;
2924 case ISD::ATOMIC_LOAD_NAND:
2925 switch (VT.SimpleTy) {
2926 default: llvm_unreachable("Unexpected value type for atomic!");
2927 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_NAND_1; break;
2928 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_NAND_2; break;
2929 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_NAND_4; break;
2930 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_NAND_8; break;
2931 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_NAND_16;break;
2934 case ISD::ATOMIC_LOAD_MAX:
2935 switch (VT.SimpleTy) {
2936 default: llvm_unreachable("Unexpected value type for atomic!");
2937 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_MAX_1; break;
2938 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_MAX_2; break;
2939 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_MAX_4; break;
2940 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_MAX_8; break;
2941 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_MAX_16;break;
2944 case ISD::ATOMIC_LOAD_UMAX:
2945 switch (VT.SimpleTy) {
2946 default: llvm_unreachable("Unexpected value type for atomic!");
2947 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_UMAX_1; break;
2948 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_UMAX_2; break;
2949 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_UMAX_4; break;
2950 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_UMAX_8; break;
2951 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_UMAX_16;break;
2954 case ISD::ATOMIC_LOAD_MIN:
2955 switch (VT.SimpleTy) {
2956 default: llvm_unreachable("Unexpected value type for atomic!");
2957 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_MIN_1; break;
2958 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_MIN_2; break;
2959 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_MIN_4; break;
2960 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_MIN_8; break;
2961 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_MIN_16;break;
2964 case ISD::ATOMIC_LOAD_UMIN:
2965 switch (VT.SimpleTy) {
2966 default: llvm_unreachable("Unexpected value type for atomic!");
2967 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_UMIN_1; break;
2968 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_UMIN_2; break;
2969 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_UMIN_4; break;
2970 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_UMIN_8; break;
2971 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_UMIN_16;break;
2976 return ExpandChainLibCall(LC, Node, false);
2979 void SelectionDAGLegalize::ExpandNode(SDNode *Node) {
2980 SmallVector<SDValue, 8> Results;
2982 SDValue Tmp1, Tmp2, Tmp3, Tmp4;
2984 switch (Node->getOpcode()) {
2987 case ISD::CTLZ_ZERO_UNDEF:
2989 case ISD::CTTZ_ZERO_UNDEF:
2990 Tmp1 = ExpandBitCount(Node->getOpcode(), Node->getOperand(0), dl);
2991 Results.push_back(Tmp1);
2994 Results.push_back(ExpandBSWAP(Node->getOperand(0), dl));
2996 case ISD::FRAMEADDR:
2997 case ISD::RETURNADDR:
2998 case ISD::FRAME_TO_ARGS_OFFSET:
2999 Results.push_back(DAG.getConstant(0, Node->getValueType(0)));
3001 case ISD::FLT_ROUNDS_:
3002 Results.push_back(DAG.getConstant(1, Node->getValueType(0)));
3004 case ISD::EH_RETURN:
3008 case ISD::EH_SJLJ_LONGJMP:
3009 // If the target didn't expand these, there's nothing to do, so just
3010 // preserve the chain and be done.
3011 Results.push_back(Node->getOperand(0));
3013 case ISD::EH_SJLJ_SETJMP:
3014 // If the target didn't expand this, just return 'zero' and preserve the
3016 Results.push_back(DAG.getConstant(0, MVT::i32));
3017 Results.push_back(Node->getOperand(0));
3019 case ISD::ATOMIC_FENCE: {
3020 // If the target didn't lower this, lower it to '__sync_synchronize()' call
3021 // FIXME: handle "fence singlethread" more efficiently.
3022 TargetLowering::ArgListTy Args;
3024 TargetLowering::CallLoweringInfo CLI(DAG);
3025 CLI.setDebugLoc(dl).setChain(Node->getOperand(0))
3026 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3027 DAG.getExternalSymbol("__sync_synchronize",
3028 TLI.getPointerTy()), std::move(Args), 0);
3030 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
3032 Results.push_back(CallResult.second);
3035 case ISD::ATOMIC_LOAD: {
3036 // There is no libcall for atomic load; fake it with ATOMIC_CMP_SWAP.
3037 SDValue Zero = DAG.getConstant(0, Node->getValueType(0));
3038 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
3039 SDValue Swap = DAG.getAtomicCmpSwap(
3040 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
3041 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
3042 cast<AtomicSDNode>(Node)->getMemOperand(),
3043 cast<AtomicSDNode>(Node)->getOrdering(),
3044 cast<AtomicSDNode>(Node)->getOrdering(),
3045 cast<AtomicSDNode>(Node)->getSynchScope());
3046 Results.push_back(Swap.getValue(0));
3047 Results.push_back(Swap.getValue(1));
3050 case ISD::ATOMIC_STORE: {
3051 // There is no libcall for atomic store; fake it with ATOMIC_SWAP.
3052 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
3053 cast<AtomicSDNode>(Node)->getMemoryVT(),
3054 Node->getOperand(0),
3055 Node->getOperand(1), Node->getOperand(2),
3056 cast<AtomicSDNode>(Node)->getMemOperand(),
3057 cast<AtomicSDNode>(Node)->getOrdering(),
3058 cast<AtomicSDNode>(Node)->getSynchScope());
3059 Results.push_back(Swap.getValue(1));
3062 // By default, atomic intrinsics are marked Legal and lowered. Targets
3063 // which don't support them directly, however, may want libcalls, in which
3064 // case they mark them Expand, and we get here.
3065 case ISD::ATOMIC_SWAP:
3066 case ISD::ATOMIC_LOAD_ADD:
3067 case ISD::ATOMIC_LOAD_SUB:
3068 case ISD::ATOMIC_LOAD_AND:
3069 case ISD::ATOMIC_LOAD_OR:
3070 case ISD::ATOMIC_LOAD_XOR:
3071 case ISD::ATOMIC_LOAD_NAND:
3072 case ISD::ATOMIC_LOAD_MIN:
3073 case ISD::ATOMIC_LOAD_MAX:
3074 case ISD::ATOMIC_LOAD_UMIN:
3075 case ISD::ATOMIC_LOAD_UMAX:
3076 case ISD::ATOMIC_CMP_SWAP: {
3077 std::pair<SDValue, SDValue> Tmp = ExpandAtomic(Node);
3078 Results.push_back(Tmp.first);
3079 Results.push_back(Tmp.second);
3082 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
3083 // Expanding an ATOMIC_CMP_SWAP_WITH_SUCCESS produces an ATOMIC_CMP_SWAP and
3084 // splits out the success value as a comparison. Expanding the resulting
3085 // ATOMIC_CMP_SWAP will produce a libcall.
3086 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
3087 SDValue Res = DAG.getAtomicCmpSwap(
3088 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
3089 Node->getOperand(0), Node->getOperand(1), Node->getOperand(2),
3090 Node->getOperand(3), cast<MemSDNode>(Node)->getMemOperand(),
3091 cast<AtomicSDNode>(Node)->getSuccessOrdering(),
3092 cast<AtomicSDNode>(Node)->getFailureOrdering(),
3093 cast<AtomicSDNode>(Node)->getSynchScope());
3095 SDValue Success = DAG.getSetCC(SDLoc(Node), Node->getValueType(1),
3096 Res, Node->getOperand(2), ISD::SETEQ);
3098 Results.push_back(Res.getValue(0));
3099 Results.push_back(Success);
3100 Results.push_back(Res.getValue(1));
3103 case ISD::DYNAMIC_STACKALLOC:
3104 ExpandDYNAMIC_STACKALLOC(Node, Results);
3106 case ISD::MERGE_VALUES:
3107 for (unsigned i = 0; i < Node->getNumValues(); i++)
3108 Results.push_back(Node->getOperand(i));
3111 EVT VT = Node->getValueType(0);
3113 Results.push_back(DAG.getConstant(0, VT));
3115 assert(VT.isFloatingPoint() && "Unknown value type!");
3116 Results.push_back(DAG.getConstantFP(0, VT));
3121 // If this operation is not supported, lower it to 'abort()' call
3122 TargetLowering::ArgListTy Args;
3123 TargetLowering::CallLoweringInfo CLI(DAG);
3124 CLI.setDebugLoc(dl).setChain(Node->getOperand(0))
3125 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3126 DAG.getExternalSymbol("abort", TLI.getPointerTy()),
3127 std::move(Args), 0);
3128 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
3130 Results.push_back(CallResult.second);
3135 Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
3136 Node->getValueType(0), dl);
3137 Results.push_back(Tmp1);
3139 case ISD::FP_EXTEND:
3140 Tmp1 = EmitStackConvert(Node->getOperand(0),
3141 Node->getOperand(0).getValueType(),
3142 Node->getValueType(0), dl);
3143 Results.push_back(Tmp1);
3145 case ISD::SIGN_EXTEND_INREG: {
3146 // NOTE: we could fall back on load/store here too for targets without
3147 // SAR. However, it is doubtful that any exist.
3148 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
3149 EVT VT = Node->getValueType(0);
3150 EVT ShiftAmountTy = TLI.getShiftAmountTy(VT);
3153 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
3154 ExtraVT.getScalarType().getSizeInBits();
3155 SDValue ShiftCst = DAG.getConstant(BitsDiff, ShiftAmountTy);
3156 Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0),
3157 Node->getOperand(0), ShiftCst);
3158 Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst);
3159 Results.push_back(Tmp1);
3162 case ISD::FP_ROUND_INREG: {
3163 // The only way we can lower this is to turn it into a TRUNCSTORE,
3164 // EXTLOAD pair, targeting a temporary location (a stack slot).
3166 // NOTE: there is a choice here between constantly creating new stack
3167 // slots and always reusing the same one. We currently always create
3168 // new ones, as reuse may inhibit scheduling.
3169 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
3170 Tmp1 = EmitStackConvert(Node->getOperand(0), ExtraVT,
3171 Node->getValueType(0), dl);
3172 Results.push_back(Tmp1);
3175 case ISD::SINT_TO_FP:
3176 case ISD::UINT_TO_FP:
3177 Tmp1 = ExpandLegalINT_TO_FP(Node->getOpcode() == ISD::SINT_TO_FP,
3178 Node->getOperand(0), Node->getValueType(0), dl);
3179 Results.push_back(Tmp1);
3181 case ISD::FP_TO_SINT:
3182 if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG))
3183 Results.push_back(Tmp1);
3185 case ISD::FP_TO_UINT: {
3186 SDValue True, False;
3187 EVT VT = Node->getOperand(0).getValueType();
3188 EVT NVT = Node->getValueType(0);
3189 APFloat apf(DAG.EVTToAPFloatSemantics(VT),
3190 APInt::getNullValue(VT.getSizeInBits()));
3191 APInt x = APInt::getSignBit(NVT.getSizeInBits());
3192 (void)apf.convertFromAPInt(x, false, APFloat::rmNearestTiesToEven);
3193 Tmp1 = DAG.getConstantFP(apf, VT);
3194 Tmp2 = DAG.getSetCC(dl, getSetCCResultType(VT),
3195 Node->getOperand(0),
3197 True = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, Node->getOperand(0));
3198 False = DAG.getNode(ISD::FP_TO_SINT, dl, NVT,
3199 DAG.getNode(ISD::FSUB, dl, VT,
3200 Node->getOperand(0), Tmp1));
3201 False = DAG.getNode(ISD::XOR, dl, NVT, False,
3202 DAG.getConstant(x, NVT));
3203 Tmp1 = DAG.getSelect(dl, NVT, Tmp2, True, False);
3204 Results.push_back(Tmp1);
3208 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3209 EVT VT = Node->getValueType(0);
3210 Tmp1 = Node->getOperand(0);
3211 Tmp2 = Node->getOperand(1);
3212 unsigned Align = Node->getConstantOperandVal(3);
3214 SDValue VAListLoad = DAG.getLoad(TLI.getPointerTy(), dl, Tmp1, Tmp2,
3215 MachinePointerInfo(V),
3216 false, false, false, 0);
3217 SDValue VAList = VAListLoad;
3219 if (Align > TLI.getMinStackArgumentAlignment()) {
3220 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
3222 VAList = DAG.getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
3223 DAG.getConstant(Align - 1,
3224 VAList.getValueType()));
3226 VAList = DAG.getNode(ISD::AND, dl, VAList.getValueType(), VAList,
3227 DAG.getConstant(-(int64_t)Align,
3228 VAList.getValueType()));
3231 // Increment the pointer, VAList, to the next vaarg
3232 Tmp3 = DAG.getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
3233 DAG.getConstant(TLI.getDataLayout()->
3234 getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext())),
3235 VAList.getValueType()));
3236 // Store the incremented VAList to the legalized pointer
3237 Tmp3 = DAG.getStore(VAListLoad.getValue(1), dl, Tmp3, Tmp2,
3238 MachinePointerInfo(V), false, false, 0);
3239 // Load the actual argument out of the pointer VAList
3240 Results.push_back(DAG.getLoad(VT, dl, Tmp3, VAList, MachinePointerInfo(),
3241 false, false, false, 0));
3242 Results.push_back(Results[0].getValue(1));
3246 // This defaults to loading a pointer from the input and storing it to the
3247 // output, returning the chain.
3248 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
3249 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
3250 Tmp1 = DAG.getLoad(TLI.getPointerTy(), dl, Node->getOperand(0),
3251 Node->getOperand(2), MachinePointerInfo(VS),
3252 false, false, false, 0);
3253 Tmp1 = DAG.getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
3254 MachinePointerInfo(VD), false, false, 0);
3255 Results.push_back(Tmp1);
3258 case ISD::EXTRACT_VECTOR_ELT:
3259 if (Node->getOperand(0).getValueType().getVectorNumElements() == 1)
3260 // This must be an access of the only element. Return it.
3261 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0),
3262 Node->getOperand(0));
3264 Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0));
3265 Results.push_back(Tmp1);
3267 case ISD::EXTRACT_SUBVECTOR:
3268 Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0)));
3270 case ISD::INSERT_SUBVECTOR:
3271 Results.push_back(ExpandInsertToVectorThroughStack(SDValue(Node, 0)));
3273 case ISD::CONCAT_VECTORS: {
3274 Results.push_back(ExpandVectorBuildThroughStack(Node));
3277 case ISD::SCALAR_TO_VECTOR:
3278 Results.push_back(ExpandSCALAR_TO_VECTOR(Node));
3280 case ISD::INSERT_VECTOR_ELT:
3281 Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0),
3282 Node->getOperand(1),
3283 Node->getOperand(2), dl));
3285 case ISD::VECTOR_SHUFFLE: {
3286 SmallVector<int, 32> NewMask;
3287 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
3289 EVT VT = Node->getValueType(0);
3290 EVT EltVT = VT.getVectorElementType();
3291 SDValue Op0 = Node->getOperand(0);
3292 SDValue Op1 = Node->getOperand(1);
3293 if (!TLI.isTypeLegal(EltVT)) {
3295 EVT NewEltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT);
3297 // BUILD_VECTOR operands are allowed to be wider than the element type.
3298 // But if NewEltVT is smaller that EltVT the BUILD_VECTOR does not accept
3300 if (NewEltVT.bitsLT(EltVT)) {
3302 // Convert shuffle node.
3303 // If original node was v4i64 and the new EltVT is i32,
3304 // cast operands to v8i32 and re-build the mask.
3306 // Calculate new VT, the size of the new VT should be equal to original.
3308 EVT::getVectorVT(*DAG.getContext(), NewEltVT,
3309 VT.getSizeInBits() / NewEltVT.getSizeInBits());
3310 assert(NewVT.bitsEq(VT));
3312 // cast operands to new VT
3313 Op0 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op0);
3314 Op1 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op1);
3316 // Convert the shuffle mask
3317 unsigned int factor =
3318 NewVT.getVectorNumElements()/VT.getVectorNumElements();
3320 // EltVT gets smaller
3323 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
3325 for (unsigned fi = 0; fi < factor; ++fi)
3326 NewMask.push_back(Mask[i]);
3329 for (unsigned fi = 0; fi < factor; ++fi)
3330 NewMask.push_back(Mask[i]*factor+fi);
3338 unsigned NumElems = VT.getVectorNumElements();
3339 SmallVector<SDValue, 16> Ops;
3340 for (unsigned i = 0; i != NumElems; ++i) {
3342 Ops.push_back(DAG.getUNDEF(EltVT));
3345 unsigned Idx = Mask[i];
3347 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
3349 DAG.getConstant(Idx, TLI.getVectorIdxTy())));
3351 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
3353 DAG.getConstant(Idx - NumElems,
3354 TLI.getVectorIdxTy())));
3357 Tmp1 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
3358 // We may have changed the BUILD_VECTOR type. Cast it back to the Node type.
3359 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), Tmp1);
3360 Results.push_back(Tmp1);
3363 case ISD::EXTRACT_ELEMENT: {
3364 EVT OpTy = Node->getOperand(0).getValueType();
3365 if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
3367 Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0),
3368 DAG.getConstant(OpTy.getSizeInBits()/2,
3369 TLI.getShiftAmountTy(Node->getOperand(0).getValueType())));
3370 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
3373 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
3374 Node->getOperand(0));
3376 Results.push_back(Tmp1);
3379 case ISD::STACKSAVE:
3380 // Expand to CopyFromReg if the target set
3381 // StackPointerRegisterToSaveRestore.
3382 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
3383 Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP,
3384 Node->getValueType(0)));
3385 Results.push_back(Results[0].getValue(1));
3387 Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
3388 Results.push_back(Node->getOperand(0));
3391 case ISD::STACKRESTORE:
3392 // Expand to CopyToReg if the target set
3393 // StackPointerRegisterToSaveRestore.
3394 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
3395 Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP,
3396 Node->getOperand(1)));
3398 Results.push_back(Node->getOperand(0));
3401 case ISD::FCOPYSIGN:
3402 Results.push_back(ExpandFCOPYSIGN(Node));
3405 // Expand Y = FNEG(X) -> Y = SUB -0.0, X
3406 Tmp1 = DAG.getConstantFP(-0.0, Node->getValueType(0));
3407 Tmp1 = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp1,
3408 Node->getOperand(0));
3409 Results.push_back(Tmp1);
3412 // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
3413 EVT VT = Node->getValueType(0);
3414 Tmp1 = Node->getOperand(0);
3415 Tmp2 = DAG.getConstantFP(0.0, VT);
3416 Tmp2 = DAG.getSetCC(dl, getSetCCResultType(Tmp1.getValueType()),
3417 Tmp1, Tmp2, ISD::SETUGT);
3418 Tmp3 = DAG.getNode(ISD::FNEG, dl, VT, Tmp1);
3419 Tmp1 = DAG.getSelect(dl, VT, Tmp2, Tmp1, Tmp3);
3420 Results.push_back(Tmp1);
3424 Results.push_back(ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
3425 RTLIB::SQRT_F80, RTLIB::SQRT_F128,
3426 RTLIB::SQRT_PPCF128));
3430 EVT VT = Node->getValueType(0);
3431 bool isSIN = Node->getOpcode() == ISD::FSIN;
3432 // Turn fsin / fcos into ISD::FSINCOS node if there are a pair of fsin /
3433 // fcos which share the same operand and both are used.
3434 if ((TLI.isOperationLegalOrCustom(ISD::FSINCOS, VT) ||
3435 canCombineSinCosLibcall(Node, TLI, TM))
3436 && useSinCos(Node)) {
3437 SDVTList VTs = DAG.getVTList(VT, VT);
3438 Tmp1 = DAG.getNode(ISD::FSINCOS, dl, VTs, Node->getOperand(0));
3440 Tmp1 = Tmp1.getValue(1);
3441 Results.push_back(Tmp1);
3443 Results.push_back(ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64,
3444 RTLIB::SIN_F80, RTLIB::SIN_F128,
3445 RTLIB::SIN_PPCF128));
3447 Results.push_back(ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64,
3448 RTLIB::COS_F80, RTLIB::COS_F128,
3449 RTLIB::COS_PPCF128));
3454 // Expand into sincos libcall.
3455 ExpandSinCosLibCall(Node, Results);
3458 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64,
3459 RTLIB::LOG_F80, RTLIB::LOG_F128,
3460 RTLIB::LOG_PPCF128));
3463 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
3464 RTLIB::LOG2_F80, RTLIB::LOG2_F128,
3465 RTLIB::LOG2_PPCF128));
3468 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
3469 RTLIB::LOG10_F80, RTLIB::LOG10_F128,
3470 RTLIB::LOG10_PPCF128));
3473 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64,
3474 RTLIB::EXP_F80, RTLIB::EXP_F128,
3475 RTLIB::EXP_PPCF128));
3478 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
3479 RTLIB::EXP2_F80, RTLIB::EXP2_F128,
3480 RTLIB::EXP2_PPCF128));
3483 Results.push_back(ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
3484 RTLIB::TRUNC_F80, RTLIB::TRUNC_F128,
3485 RTLIB::TRUNC_PPCF128));
3488 Results.push_back(ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
3489 RTLIB::FLOOR_F80, RTLIB::FLOOR_F128,
3490 RTLIB::FLOOR_PPCF128));
3493 Results.push_back(ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
3494 RTLIB::CEIL_F80, RTLIB::CEIL_F128,
3495 RTLIB::CEIL_PPCF128));
3498 Results.push_back(ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64,
3499 RTLIB::RINT_F80, RTLIB::RINT_F128,
3500 RTLIB::RINT_PPCF128));
3502 case ISD::FNEARBYINT:
3503 Results.push_back(ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32,
3504 RTLIB::NEARBYINT_F64,
3505 RTLIB::NEARBYINT_F80,
3506 RTLIB::NEARBYINT_F128,
3507 RTLIB::NEARBYINT_PPCF128));
3510 Results.push_back(ExpandFPLibCall(Node, RTLIB::ROUND_F32,
3514 RTLIB::ROUND_PPCF128));
3517 Results.push_back(ExpandFPLibCall(Node, RTLIB::POWI_F32, RTLIB::POWI_F64,
3518 RTLIB::POWI_F80, RTLIB::POWI_F128,
3519 RTLIB::POWI_PPCF128));
3522 Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64,
3523 RTLIB::POW_F80, RTLIB::POW_F128,
3524 RTLIB::POW_PPCF128));
3527 Results.push_back(ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64,
3528 RTLIB::DIV_F80, RTLIB::DIV_F128,
3529 RTLIB::DIV_PPCF128));
3532 Results.push_back(ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64,
3533 RTLIB::REM_F80, RTLIB::REM_F128,
3534 RTLIB::REM_PPCF128));
3537 Results.push_back(ExpandFPLibCall(Node, RTLIB::FMA_F32, RTLIB::FMA_F64,
3538 RTLIB::FMA_F80, RTLIB::FMA_F128,
3539 RTLIB::FMA_PPCF128));
3541 case ISD::FP16_TO_FP: {
3542 if (Node->getValueType(0) == MVT::f32) {
3543 Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false));
3547 // We can extend to types bigger than f32 in two steps without changing the
3548 // result. Since "f16 -> f32" is much more commonly available, give CodeGen
3549 // the option of emitting that before resorting to a libcall.
3551 DAG.getNode(ISD::FP16_TO_FP, dl, MVT::f32, Node->getOperand(0));
3553 DAG.getNode(ISD::FP_EXTEND, dl, Node->getValueType(0), Res));
3556 case ISD::FP_TO_FP16: {
3558 RTLIB::getFPROUND(Node->getOperand(0).getValueType(), MVT::f16);
3559 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to expand fp_to_fp16");
3560 Results.push_back(ExpandLibCall(LC, Node, false));
3563 case ISD::ConstantFP: {
3564 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
3565 // Check to see if this FP immediate is already legal.
3566 // If this is a legal constant, turn it into a TargetConstantFP node.
3567 if (!TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0)))
3568 Results.push_back(ExpandConstantFP(CFP, true));
3572 EVT VT = Node->getValueType(0);
3573 assert(TLI.isOperationLegalOrCustom(ISD::FADD, VT) &&
3574 TLI.isOperationLegalOrCustom(ISD::FNEG, VT) &&
3575 "Don't know how to expand this FP subtraction!");
3576 Tmp1 = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(1));
3577 Tmp1 = DAG.getNode(ISD::FADD, dl, VT, Node->getOperand(0), Tmp1);
3578 Results.push_back(Tmp1);
3582 EVT VT = Node->getValueType(0);
3583 assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
3584 TLI.isOperationLegalOrCustom(ISD::XOR, VT) &&
3585 "Don't know how to expand this subtraction!");
3586 Tmp1 = DAG.getNode(ISD::XOR, dl, VT, Node->getOperand(1),
3587 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT));
3588 Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp1, DAG.getConstant(1, VT));
3589 Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1));
3594 EVT VT = Node->getValueType(0);
3595 bool isSigned = Node->getOpcode() == ISD::SREM;
3596 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
3597 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3598 Tmp2 = Node->getOperand(0);
3599 Tmp3 = Node->getOperand(1);
3600 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT) ||
3601 (isDivRemLibcallAvailable(Node, isSigned, TLI) &&
3602 // If div is legal, it's better to do the normal expansion
3603 !TLI.isOperationLegalOrCustom(DivOpc, Node->getValueType(0)) &&
3604 useDivRem(Node, isSigned, false))) {
3605 SDVTList VTs = DAG.getVTList(VT, VT);
3606 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Tmp2, Tmp3).getValue(1);
3607 } else if (TLI.isOperationLegalOrCustom(DivOpc, VT)) {
3609 Tmp1 = DAG.getNode(DivOpc, dl, VT, Tmp2, Tmp3);
3610 Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Tmp3);
3611 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Tmp2, Tmp1);
3612 } else if (isSigned)
3613 Tmp1 = ExpandIntLibCall(Node, true,
3615 RTLIB::SREM_I16, RTLIB::SREM_I32,
3616 RTLIB::SREM_I64, RTLIB::SREM_I128);
3618 Tmp1 = ExpandIntLibCall(Node, false,
3620 RTLIB::UREM_I16, RTLIB::UREM_I32,
3621 RTLIB::UREM_I64, RTLIB::UREM_I128);
3622 Results.push_back(Tmp1);
3627 bool isSigned = Node->getOpcode() == ISD::SDIV;
3628 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3629 EVT VT = Node->getValueType(0);
3630 SDVTList VTs = DAG.getVTList(VT, VT);
3631 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT) ||
3632 (isDivRemLibcallAvailable(Node, isSigned, TLI) &&
3633 useDivRem(Node, isSigned, true)))
3634 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0),
3635 Node->getOperand(1));
3637 Tmp1 = ExpandIntLibCall(Node, true,
3639 RTLIB::SDIV_I16, RTLIB::SDIV_I32,
3640 RTLIB::SDIV_I64, RTLIB::SDIV_I128);
3642 Tmp1 = ExpandIntLibCall(Node, false,
3644 RTLIB::UDIV_I16, RTLIB::UDIV_I32,
3645 RTLIB::UDIV_I64, RTLIB::UDIV_I128);
3646 Results.push_back(Tmp1);
3651 unsigned ExpandOpcode = Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI :
3653 EVT VT = Node->getValueType(0);
3654 SDVTList VTs = DAG.getVTList(VT, VT);
3655 assert(TLI.isOperationLegalOrCustom(ExpandOpcode, VT) &&
3656 "If this wasn't legal, it shouldn't have been created!");
3657 Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0),
3658 Node->getOperand(1));
3659 Results.push_back(Tmp1.getValue(1));
3664 // Expand into divrem libcall
3665 ExpandDivRemLibCall(Node, Results);
3668 EVT VT = Node->getValueType(0);
3669 SDVTList VTs = DAG.getVTList(VT, VT);
3670 // See if multiply or divide can be lowered using two-result operations.
3671 // We just need the low half of the multiply; try both the signed
3672 // and unsigned forms. If the target supports both SMUL_LOHI and
3673 // UMUL_LOHI, form a preference by checking which forms of plain
3674 // MULH it supports.
3675 bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
3676 bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
3677 bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
3678 bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
3679 unsigned OpToUse = 0;
3680 if (HasSMUL_LOHI && !HasMULHS) {
3681 OpToUse = ISD::SMUL_LOHI;
3682 } else if (HasUMUL_LOHI && !HasMULHU) {
3683 OpToUse = ISD::UMUL_LOHI;
3684 } else if (HasSMUL_LOHI) {
3685 OpToUse = ISD::SMUL_LOHI;
3686 } else if (HasUMUL_LOHI) {
3687 OpToUse = ISD::UMUL_LOHI;
3690 Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0),
3691 Node->getOperand(1)));
3696 EVT HalfType = VT.getHalfSizedIntegerVT(*DAG.getContext());
3697 if (TLI.isOperationLegalOrCustom(ISD::ZERO_EXTEND, VT) &&
3698 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND, VT) &&
3699 TLI.isOperationLegalOrCustom(ISD::SHL, VT) &&
3700 TLI.isOperationLegalOrCustom(ISD::OR, VT) &&
3701 TLI.expandMUL(Node, Lo, Hi, HalfType, DAG)) {
3702 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
3703 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Hi);
3704 SDValue Shift = DAG.getConstant(HalfType.getSizeInBits(),
3705 TLI.getShiftAmountTy(HalfType));
3706 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
3707 Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi));
3711 Tmp1 = ExpandIntLibCall(Node, false,
3713 RTLIB::MUL_I16, RTLIB::MUL_I32,
3714 RTLIB::MUL_I64, RTLIB::MUL_I128);
3715 Results.push_back(Tmp1);
3720 SDValue LHS = Node->getOperand(0);
3721 SDValue RHS = Node->getOperand(1);
3722 SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
3723 ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3725 Results.push_back(Sum);
3726 EVT ResultType = Node->getValueType(1);
3727 EVT OType = getSetCCResultType(Node->getValueType(0));
3729 SDValue Zero = DAG.getConstant(0, LHS.getValueType());
3731 // LHSSign -> LHS >= 0
3732 // RHSSign -> RHS >= 0
3733 // SumSign -> Sum >= 0
3736 // Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
3738 // Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
3740 SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
3741 SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
3742 SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
3743 Node->getOpcode() == ISD::SADDO ?
3744 ISD::SETEQ : ISD::SETNE);
3746 SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
3747 SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
3749 SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
3750 Results.push_back(DAG.getBoolExtOrTrunc(Cmp, dl, ResultType, ResultType));
3755 SDValue LHS = Node->getOperand(0);
3756 SDValue RHS = Node->getOperand(1);
3757 SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::UADDO ?
3758 ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3760 Results.push_back(Sum);
3762 EVT ResultType = Node->getValueType(1);
3763 EVT SetCCType = getSetCCResultType(Node->getValueType(0));
3765 = Node->getOpcode() == ISD::UADDO ? ISD::SETULT : ISD::SETUGT;
3766 SDValue SetCC = DAG.getSetCC(dl, SetCCType, Sum, LHS, CC);
3768 Results.push_back(DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType));
3773 EVT VT = Node->getValueType(0);
3774 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits() * 2);
3775 SDValue LHS = Node->getOperand(0);
3776 SDValue RHS = Node->getOperand(1);
3779 static const unsigned Ops[2][3] =
3780 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
3781 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
3782 bool isSigned = Node->getOpcode() == ISD::SMULO;
3783 if (TLI.isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
3784 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
3785 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
3786 } else if (TLI.isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
3787 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
3789 TopHalf = BottomHalf.getValue(1);
3790 } else if (TLI.isTypeLegal(WideVT)) {
3791 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
3792 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
3793 Tmp1 = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
3794 BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
3795 DAG.getIntPtrConstant(0));
3796 TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
3797 DAG.getIntPtrConstant(1));
3799 // We can fall back to a libcall with an illegal type for the MUL if we
3800 // have a libcall big enough.
3801 // Also, we can fall back to a division in some cases, but that's a big
3802 // performance hit in the general case.
3803 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3804 if (WideVT == MVT::i16)
3805 LC = RTLIB::MUL_I16;
3806 else if (WideVT == MVT::i32)
3807 LC = RTLIB::MUL_I32;
3808 else if (WideVT == MVT::i64)
3809 LC = RTLIB::MUL_I64;
3810 else if (WideVT == MVT::i128)
3811 LC = RTLIB::MUL_I128;
3812 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!");
3814 // The high part is obtained by SRA'ing all but one of the bits of low
3816 unsigned LoSize = VT.getSizeInBits();
3817 SDValue HiLHS = DAG.getNode(ISD::SRA, dl, VT, RHS,
3818 DAG.getConstant(LoSize-1, TLI.getPointerTy()));
3819 SDValue HiRHS = DAG.getNode(ISD::SRA, dl, VT, LHS,
3820 DAG.getConstant(LoSize-1, TLI.getPointerTy()));
3822 // Here we're passing the 2 arguments explicitly as 4 arguments that are
3823 // pre-lowered to the correct types. This all depends upon WideVT not
3824 // being a legal type for the architecture and thus has to be split to
3826 SDValue Args[] = { LHS, HiLHS, RHS, HiRHS };
3827 SDValue Ret = ExpandLibCall(LC, WideVT, Args, 4, isSigned, dl);
3828 BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Ret,
3829 DAG.getIntPtrConstant(0));
3830 TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Ret,
3831 DAG.getIntPtrConstant(1));
3832 // Ret is a node with an illegal type. Because such things are not
3833 // generally permitted during this phase of legalization, delete the
3834 // node. The above EXTRACT_ELEMENT nodes should have been folded.
3835 DAG.DeleteNode(Ret.getNode());
3839 Tmp1 = DAG.getConstant(VT.getSizeInBits() - 1,
3840 TLI.getShiftAmountTy(BottomHalf.getValueType()));
3841 Tmp1 = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, Tmp1);
3842 TopHalf = DAG.getSetCC(dl, getSetCCResultType(VT), TopHalf, Tmp1,
3845 TopHalf = DAG.getSetCC(dl, getSetCCResultType(VT), TopHalf,
3846 DAG.getConstant(0, VT), ISD::SETNE);
3848 Results.push_back(BottomHalf);
3849 Results.push_back(TopHalf);
3852 case ISD::BUILD_PAIR: {
3853 EVT PairTy = Node->getValueType(0);
3854 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0));
3855 Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1));
3856 Tmp2 = DAG.getNode(ISD::SHL, dl, PairTy, Tmp2,
3857 DAG.getConstant(PairTy.getSizeInBits()/2,
3858 TLI.getShiftAmountTy(PairTy)));
3859 Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2));
3863 Tmp1 = Node->getOperand(0);
3864 Tmp2 = Node->getOperand(1);
3865 Tmp3 = Node->getOperand(2);
3866 if (Tmp1.getOpcode() == ISD::SETCC) {
3867 Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1),
3869 cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
3871 Tmp1 = DAG.getSelectCC(dl, Tmp1,
3872 DAG.getConstant(0, Tmp1.getValueType()),
3873 Tmp2, Tmp3, ISD::SETNE);
3875 Results.push_back(Tmp1);
3878 SDValue Chain = Node->getOperand(0);
3879 SDValue Table = Node->getOperand(1);
3880 SDValue Index = Node->getOperand(2);
3882 EVT PTy = TLI.getPointerTy();
3884 const DataLayout &TD = *TLI.getDataLayout();
3885 unsigned EntrySize =
3886 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
3888 Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(),
3889 Index, DAG.getConstant(EntrySize, Index.getValueType()));
3890 SDValue Addr = DAG.getNode(ISD::ADD, dl, Index.getValueType(),
3893 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
3894 SDValue LD = DAG.getExtLoad(ISD::SEXTLOAD, dl, PTy, Chain, Addr,
3895 MachinePointerInfo::getJumpTable(), MemVT,
3896 false, false, false, 0);
3898 if (TM.getRelocationModel() == Reloc::PIC_) {
3899 // For PIC, the sequence is:
3900 // BRIND(load(Jumptable + index) + RelocBase)
3901 // RelocBase can be JumpTable, GOT or some sort of global base.
3902 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr,
3903 TLI.getPICJumpTableRelocBase(Table, DAG));
3905 Tmp1 = DAG.getNode(ISD::BRIND, dl, MVT::Other, LD.getValue(1), Addr);
3906 Results.push_back(Tmp1);
3910 // Expand brcond's setcc into its constituent parts and create a BR_CC
3912 Tmp1 = Node->getOperand(0);
3913 Tmp2 = Node->getOperand(1);
3914 if (Tmp2.getOpcode() == ISD::SETCC) {
3915 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other,
3916 Tmp1, Tmp2.getOperand(2),
3917 Tmp2.getOperand(0), Tmp2.getOperand(1),
3918 Node->getOperand(2));
3920 // We test only the i1 bit. Skip the AND if UNDEF.
3921 Tmp3 = (Tmp2.getOpcode() == ISD::UNDEF) ? Tmp2 :
3922 DAG.getNode(ISD::AND, dl, Tmp2.getValueType(), Tmp2,
3923 DAG.getConstant(1, Tmp2.getValueType()));
3924 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
3925 DAG.getCondCode(ISD::SETNE), Tmp3,
3926 DAG.getConstant(0, Tmp3.getValueType()),
3927 Node->getOperand(2));
3929 Results.push_back(Tmp1);
3932 Tmp1 = Node->getOperand(0);
3933 Tmp2 = Node->getOperand(1);
3934 Tmp3 = Node->getOperand(2);
3935 bool Legalized = LegalizeSetCCCondCode(Node->getValueType(0), Tmp1, Tmp2,
3936 Tmp3, NeedInvert, dl);
3939 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
3940 // condition code, create a new SETCC node.
3942 Tmp1 = DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
3945 // If we expanded the SETCC by inverting the condition code, then wrap
3946 // the existing SETCC in a NOT to restore the intended condition.
3948 Tmp1 = DAG.getLogicalNOT(dl, Tmp1, Tmp1->getValueType(0));
3950 Results.push_back(Tmp1);
3954 // Otherwise, SETCC for the given comparison type must be completely
3955 // illegal; expand it into a SELECT_CC.
3956 EVT VT = Node->getValueType(0);
3958 switch (TLI.getBooleanContents(Tmp1->getValueType(0))) {
3959 case TargetLowering::ZeroOrOneBooleanContent:
3960 case TargetLowering::UndefinedBooleanContent:
3963 case TargetLowering::ZeroOrNegativeOneBooleanContent:
3967 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
3968 DAG.getConstant(TrueValue, VT), DAG.getConstant(0, VT),
3970 Results.push_back(Tmp1);
3973 case ISD::SELECT_CC: {
3974 Tmp1 = Node->getOperand(0); // LHS
3975 Tmp2 = Node->getOperand(1); // RHS
3976 Tmp3 = Node->getOperand(2); // True
3977 Tmp4 = Node->getOperand(3); // False
3978 EVT VT = Node->getValueType(0);
3979 SDValue CC = Node->getOperand(4);
3980 ISD::CondCode CCOp = cast<CondCodeSDNode>(CC)->get();
3982 if (TLI.isCondCodeLegal(CCOp, Tmp1.getSimpleValueType())) {
3983 // If the condition code is legal, then we need to expand this
3984 // node using SETCC and SELECT.
3985 EVT CmpVT = Tmp1.getValueType();
3986 assert(!TLI.isOperationExpand(ISD::SELECT, VT) &&
3987 "Cannot expand ISD::SELECT_CC when ISD::SELECT also needs to be "
3989 EVT CCVT = TLI.getSetCCResultType(*DAG.getContext(), CmpVT);
3990 SDValue Cond = DAG.getNode(ISD::SETCC, dl, CCVT, Tmp1, Tmp2, CC);
3991 Results.push_back(DAG.getSelect(dl, VT, Cond, Tmp3, Tmp4));
3995 // SELECT_CC is legal, so the condition code must not be.
3996 bool Legalized = false;
3997 // Try to legalize by inverting the condition. This is for targets that
3998 // might support an ordered version of a condition, but not the unordered
3999 // version (or vice versa).
4000 ISD::CondCode InvCC = ISD::getSetCCInverse(CCOp,
4001 Tmp1.getValueType().isInteger());
4002 if (TLI.isCondCodeLegal(InvCC, Tmp1.getSimpleValueType())) {
4003 // Use the new condition code and swap true and false
4005 Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp4, Tmp3, InvCC);
4007 // If The inverse is not legal, then try to swap the arguments using
4008 // the inverse condition code.
4009 ISD::CondCode SwapInvCC = ISD::getSetCCSwappedOperands(InvCC);
4010 if (TLI.isCondCodeLegal(SwapInvCC, Tmp1.getSimpleValueType())) {
4011 // The swapped inverse condition is legal, so swap true and false,
4014 Tmp1 = DAG.getSelectCC(dl, Tmp2, Tmp1, Tmp4, Tmp3, SwapInvCC);
4019 Legalized = LegalizeSetCCCondCode(
4020 getSetCCResultType(Tmp1.getValueType()), Tmp1, Tmp2, CC, NeedInvert,
4023 assert(Legalized && "Can't legalize SELECT_CC with legal condition!");
4025 // If we expanded the SETCC by inverting the condition code, then swap
4026 // the True/False operands to match.
4028 std::swap(Tmp3, Tmp4);
4030 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
4031 // condition code, create a new SELECT_CC node.
4033 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0),
4034 Tmp1, Tmp2, Tmp3, Tmp4, CC);
4036 Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
4037 CC = DAG.getCondCode(ISD::SETNE);
4038 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1,
4039 Tmp2, Tmp3, Tmp4, CC);
4042 Results.push_back(Tmp1);
4046 Tmp1 = Node->getOperand(0); // Chain
4047 Tmp2 = Node->getOperand(2); // LHS
4048 Tmp3 = Node->getOperand(3); // RHS
4049 Tmp4 = Node->getOperand(1); // CC
4051 bool Legalized = LegalizeSetCCCondCode(getSetCCResultType(
4052 Tmp2.getValueType()), Tmp2, Tmp3, Tmp4, NeedInvert, dl);
4054 assert(Legalized && "Can't legalize BR_CC with legal condition!");
4056 // If we expanded the SETCC by inverting the condition code, then wrap
4057 // the existing SETCC in a NOT to restore the intended condition.
4059 Tmp4 = DAG.getNOT(dl, Tmp4, Tmp4->getValueType(0));
4061 // If we expanded the SETCC by swapping LHS and RHS, create a new BR_CC
4063 if (Tmp4.getNode()) {
4064 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1,
4065 Tmp4, Tmp2, Tmp3, Node->getOperand(4));
4067 Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
4068 Tmp4 = DAG.getCondCode(ISD::SETNE);
4069 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4,
4070 Tmp2, Tmp3, Node->getOperand(4));
4072 Results.push_back(Tmp1);
4075 case ISD::BUILD_VECTOR:
4076 Results.push_back(ExpandBUILD_VECTOR(Node));
4081 // Scalarize vector SRA/SRL/SHL.
4082 EVT VT = Node->getValueType(0);
4083 assert(VT.isVector() && "Unable to legalize non-vector shift");
4084 assert(TLI.isTypeLegal(VT.getScalarType())&& "Element type must be legal");
4085 unsigned NumElem = VT.getVectorNumElements();
4087 SmallVector<SDValue, 8> Scalars;
4088 for (unsigned Idx = 0; Idx < NumElem; Idx++) {
4089 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
4091 Node->getOperand(0), DAG.getConstant(Idx,
4092 TLI.getVectorIdxTy()));
4093 SDValue Sh = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
4095 Node->getOperand(1), DAG.getConstant(Idx,
4096 TLI.getVectorIdxTy()));
4097 Scalars.push_back(DAG.getNode(Node->getOpcode(), dl,
4098 VT.getScalarType(), Ex, Sh));
4101 DAG.getNode(ISD::BUILD_VECTOR, dl, Node->getValueType(0), Scalars);
4102 ReplaceNode(SDValue(Node, 0), Result);
4105 case ISD::GLOBAL_OFFSET_TABLE:
4106 case ISD::GlobalAddress:
4107 case ISD::GlobalTLSAddress:
4108 case ISD::ExternalSymbol:
4109 case ISD::ConstantPool:
4110 case ISD::JumpTable:
4111 case ISD::INTRINSIC_W_CHAIN:
4112 case ISD::INTRINSIC_WO_CHAIN:
4113 case ISD::INTRINSIC_VOID:
4114 // FIXME: Custom lowering for these operations shouldn't return null!
4118 // Replace the original node with the legalized result.
4119 if (!Results.empty())
4120 ReplaceNode(Node, Results.data());
4123 void SelectionDAGLegalize::PromoteNode(SDNode *Node) {
4124 SmallVector<SDValue, 8> Results;
4125 MVT OVT = Node->getSimpleValueType(0);
4126 if (Node->getOpcode() == ISD::UINT_TO_FP ||
4127 Node->getOpcode() == ISD::SINT_TO_FP ||
4128 Node->getOpcode() == ISD::SETCC) {
4129 OVT = Node->getOperand(0).getSimpleValueType();
4131 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
4133 SDValue Tmp1, Tmp2, Tmp3;
4134 switch (Node->getOpcode()) {
4136 case ISD::CTTZ_ZERO_UNDEF:
4138 case ISD::CTLZ_ZERO_UNDEF:
4140 // Zero extend the argument.
4141 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
4142 // Perform the larger operation. For CTPOP and CTTZ_ZERO_UNDEF, this is
4143 // already the correct result.
4144 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4145 if (Node->getOpcode() == ISD::CTTZ) {
4146 // FIXME: This should set a bit in the zero extended value instead.
4147 Tmp2 = DAG.getSetCC(dl, getSetCCResultType(NVT),
4148 Tmp1, DAG.getConstant(NVT.getSizeInBits(), NVT),
4150 Tmp1 = DAG.getSelect(dl, NVT, Tmp2,
4151 DAG.getConstant(OVT.getSizeInBits(), NVT), Tmp1);
4152 } else if (Node->getOpcode() == ISD::CTLZ ||
4153 Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF) {
4154 // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
4155 Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
4156 DAG.getConstant(NVT.getSizeInBits() -
4157 OVT.getSizeInBits(), NVT));
4159 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
4162 unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
4163 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
4164 Tmp1 = DAG.getNode(ISD::BSWAP, dl, NVT, Tmp1);
4165 Tmp1 = DAG.getNode(ISD::SRL, dl, NVT, Tmp1,
4166 DAG.getConstant(DiffBits, TLI.getShiftAmountTy(NVT)));
4167 Results.push_back(Tmp1);
4170 case ISD::FP_TO_UINT:
4171 case ISD::FP_TO_SINT:
4172 Tmp1 = PromoteLegalFP_TO_INT(Node->getOperand(0), Node->getValueType(0),
4173 Node->getOpcode() == ISD::FP_TO_SINT, dl);
4174 Results.push_back(Tmp1);
4176 case ISD::UINT_TO_FP:
4177 case ISD::SINT_TO_FP:
4178 Tmp1 = PromoteLegalINT_TO_FP(Node->getOperand(0), Node->getValueType(0),
4179 Node->getOpcode() == ISD::SINT_TO_FP, dl);
4180 Results.push_back(Tmp1);
4183 SDValue Chain = Node->getOperand(0); // Get the chain.
4184 SDValue Ptr = Node->getOperand(1); // Get the pointer.
4187 if (OVT.isVector()) {
4188 TruncOp = ISD::BITCAST;
4190 assert(OVT.isInteger()
4191 && "VAARG promotion is supported only for vectors or integer types");
4192 TruncOp = ISD::TRUNCATE;
4195 // Perform the larger operation, then convert back
4196 Tmp1 = DAG.getVAArg(NVT, dl, Chain, Ptr, Node->getOperand(2),
4197 Node->getConstantOperandVal(3));
4198 Chain = Tmp1.getValue(1);
4200 Tmp2 = DAG.getNode(TruncOp, dl, OVT, Tmp1);
4202 // Modified the chain result - switch anything that used the old chain to
4204 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Tmp2);
4205 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
4207 UpdatedNodes->insert(Tmp2.getNode());
4208 UpdatedNodes->insert(Chain.getNode());
4216 unsigned ExtOp, TruncOp;
4217 if (OVT.isVector()) {
4218 ExtOp = ISD::BITCAST;
4219 TruncOp = ISD::BITCAST;
4221 assert(OVT.isInteger() && "Cannot promote logic operation");
4222 ExtOp = ISD::ANY_EXTEND;
4223 TruncOp = ISD::TRUNCATE;
4225 // Promote each of the values to the new type.
4226 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4227 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4228 // Perform the larger operation, then convert back
4229 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4230 Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1));
4234 unsigned ExtOp, TruncOp;
4235 if (Node->getValueType(0).isVector() ||
4236 Node->getValueType(0).getSizeInBits() == NVT.getSizeInBits()) {
4237 ExtOp = ISD::BITCAST;
4238 TruncOp = ISD::BITCAST;
4239 } else if (Node->getValueType(0).isInteger()) {
4240 ExtOp = ISD::ANY_EXTEND;
4241 TruncOp = ISD::TRUNCATE;
4243 ExtOp = ISD::FP_EXTEND;
4244 TruncOp = ISD::FP_ROUND;
4246 Tmp1 = Node->getOperand(0);
4247 // Promote each of the values to the new type.
4248 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4249 Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
4250 // Perform the larger operation, then round down.
4251 Tmp1 = DAG.getSelect(dl, NVT, Tmp1, Tmp2, Tmp3);
4252 if (TruncOp != ISD::FP_ROUND)
4253 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1);
4255 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1,
4256 DAG.getIntPtrConstant(0));
4257 Results.push_back(Tmp1);
4260 case ISD::VECTOR_SHUFFLE: {
4261 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
4263 // Cast the two input vectors.
4264 Tmp1 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0));
4265 Tmp2 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(1));
4267 // Convert the shuffle mask to the right # elements.
4268 Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
4269 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OVT, Tmp1);
4270 Results.push_back(Tmp1);
4274 unsigned ExtOp = ISD::FP_EXTEND;
4275 if (NVT.isInteger()) {
4276 ISD::CondCode CCCode =
4277 cast<CondCodeSDNode>(Node->getOperand(2))->get();
4278 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4280 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4281 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4282 Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
4283 Tmp1, Tmp2, Node->getOperand(2)));
4289 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4290 Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
4291 Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4292 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4293 Tmp3, DAG.getIntPtrConstant(0)));
4300 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4301 Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4302 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4303 Tmp2, DAG.getIntPtrConstant(0)));
4308 // Replace the original node with the legalized result.
4309 if (!Results.empty())
4310 ReplaceNode(Node, Results.data());
4313 // SelectionDAG::Legalize - This is the entry point for the file.
4315 void SelectionDAG::Legalize() {
4316 AssignTopologicalOrder();
4318 allnodes_iterator LegalizePosition;
4319 SmallPtrSet<SDNode *, 16> LegalizedNodes;
4320 SelectionDAGLegalize Legalizer(*this, LegalizePosition, LegalizedNodes);
4322 // Visit all the nodes. We start in topological order, so that we see
4323 // nodes with their original operands intact. Legalization can produce
4324 // new nodes which may themselves need to be legalized. Iterate until all
4325 // nodes have been legalized.
4327 bool AnyLegalized = false;
4328 for (LegalizePosition = allnodes_end();
4329 LegalizePosition != allnodes_begin(); ) {
4332 SDNode *N = LegalizePosition;
4333 if (LegalizedNodes.insert(N)) {
4334 AnyLegalized = true;
4335 Legalizer.LegalizeOp(N);
4343 // Remove dead nodes now.
4347 bool SelectionDAG::LegalizeOp(SDNode *N,
4348 SmallSetVector<SDNode *, 16> &UpdatedNodes) {
4349 allnodes_iterator LegalizePosition(N);
4350 SmallPtrSet<SDNode *, 16> LegalizedNodes;
4351 SelectionDAGLegalize Legalizer(*this, LegalizePosition, LegalizedNodes,
4354 // Directly insert the node in question, and legalize it. This will recurse
4355 // as needed through operands.
4356 LegalizedNodes.insert(N);
4357 Legalizer.LegalizeOp(N);
4359 return LegalizedNodes.count(N);