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"
37 #include "llvm/Target/TargetSubtargetInfo.h"
40 #define DEBUG_TYPE "legalizedag"
44 struct FloatSignAsInt;
46 //===----------------------------------------------------------------------===//
47 /// This takes an arbitrary SelectionDAG as input and
48 /// hacks on it until the target machine can handle it. This involves
49 /// eliminating value sizes the machine cannot handle (promoting small sizes to
50 /// large sizes or splitting up large values into small values) as well as
51 /// eliminating operations the machine cannot handle.
53 /// This code also does a small amount of optimization and recognition of idioms
54 /// as part of its processing. For example, if a target does not support a
55 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
56 /// will attempt merge setcc and brc instructions into brcc's.
58 class SelectionDAGLegalize {
59 const TargetMachine &TM;
60 const TargetLowering &TLI;
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.getDataLayout(), *DAG.getContext(), VT);
74 // Libcall insertion helpers.
77 SelectionDAGLegalize(SelectionDAG &DAG,
78 SmallPtrSetImpl<SDNode *> &LegalizedNodes,
79 SmallSetVector<SDNode *, 16> *UpdatedNodes = nullptr)
80 : TM(DAG.getTarget()), TLI(DAG.getTargetLoweringInfo()), DAG(DAG),
81 LegalizedNodes(LegalizedNodes), UpdatedNodes(UpdatedNodes) {}
83 /// \brief Legalizes the given operation.
84 void LegalizeOp(SDNode *Node);
87 SDValue OptimizeFloatStore(StoreSDNode *ST);
89 void LegalizeLoadOps(SDNode *Node);
90 void LegalizeStoreOps(SDNode *Node);
92 /// Some targets cannot handle a variable
93 /// insertion index for the INSERT_VECTOR_ELT instruction. In this case, it
94 /// is necessary to spill the vector being inserted into to memory, perform
95 /// the insert there, and then read the result back.
96 SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val,
97 SDValue Idx, SDLoc dl);
98 SDValue ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val,
99 SDValue Idx, SDLoc dl);
101 /// Return a vector shuffle operation which
102 /// performs the same shuffe in terms of order or result bytes, but on a type
103 /// whose vector element type is narrower than the original shuffle type.
104 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
105 SDValue ShuffleWithNarrowerEltType(EVT NVT, EVT VT, SDLoc dl,
106 SDValue N1, SDValue N2,
107 ArrayRef<int> Mask) const;
109 bool LegalizeSetCCCondCode(EVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC,
110 bool &NeedInvert, SDLoc dl);
112 SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned);
113 SDValue ExpandLibCall(RTLIB::Libcall LC, EVT RetVT, const SDValue *Ops,
114 unsigned NumOps, bool isSigned, SDLoc dl);
116 std::pair<SDValue, SDValue> ExpandChainLibCall(RTLIB::Libcall LC,
117 SDNode *Node, bool isSigned);
118 SDValue ExpandFPLibCall(SDNode *Node, RTLIB::Libcall Call_F32,
119 RTLIB::Libcall Call_F64, RTLIB::Libcall Call_F80,
120 RTLIB::Libcall Call_F128,
121 RTLIB::Libcall Call_PPCF128);
122 SDValue ExpandIntLibCall(SDNode *Node, bool isSigned,
123 RTLIB::Libcall Call_I8,
124 RTLIB::Libcall Call_I16,
125 RTLIB::Libcall Call_I32,
126 RTLIB::Libcall Call_I64,
127 RTLIB::Libcall Call_I128);
128 void ExpandDivRemLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results);
129 void ExpandSinCosLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results);
131 SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT, SDLoc dl);
132 SDValue ExpandBUILD_VECTOR(SDNode *Node);
133 SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
134 void ExpandDYNAMIC_STACKALLOC(SDNode *Node,
135 SmallVectorImpl<SDValue> &Results);
136 void getSignAsIntValue(FloatSignAsInt &State, SDLoc DL, SDValue Value) const;
137 SDValue modifySignAsInt(const FloatSignAsInt &State, SDLoc DL,
138 SDValue NewIntValue) const;
139 SDValue ExpandFCOPYSIGN(SDNode *Node) const;
140 SDValue ExpandFABS(SDNode *Node) const;
141 SDValue ExpandLegalINT_TO_FP(bool isSigned, SDValue LegalOp, EVT DestVT,
143 SDValue PromoteLegalINT_TO_FP(SDValue LegalOp, EVT DestVT, bool isSigned,
145 SDValue PromoteLegalFP_TO_INT(SDValue LegalOp, EVT DestVT, bool isSigned,
148 SDValue ExpandBSWAP(SDValue Op, SDLoc dl);
149 SDValue ExpandBitCount(unsigned Opc, SDValue Op, SDLoc dl);
151 SDValue ExpandExtractFromVectorThroughStack(SDValue Op);
152 SDValue ExpandInsertToVectorThroughStack(SDValue Op);
153 SDValue ExpandVectorBuildThroughStack(SDNode* Node);
155 SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP);
157 // if ExpandNode returns false, LegalizeOp falls back to ConvertNodeToLibcall
158 bool ExpandNode(SDNode *Node);
159 void ConvertNodeToLibcall(SDNode *Node);
160 void PromoteNode(SDNode *Node);
163 // Node replacement helpers
164 void ReplacedNode(SDNode *N) {
165 LegalizedNodes.erase(N);
167 UpdatedNodes->insert(N);
169 void ReplaceNode(SDNode *Old, SDNode *New) {
170 DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
171 dbgs() << " with: "; New->dump(&DAG));
173 assert(Old->getNumValues() == New->getNumValues() &&
174 "Replacing one node with another that produces a different number "
176 DAG.ReplaceAllUsesWith(Old, New);
177 for (unsigned i = 0, e = Old->getNumValues(); i != e; ++i)
178 DAG.TransferDbgValues(SDValue(Old, i), SDValue(New, i));
180 UpdatedNodes->insert(New);
183 void ReplaceNode(SDValue Old, SDValue New) {
184 DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
185 dbgs() << " with: "; New->dump(&DAG));
187 DAG.ReplaceAllUsesWith(Old, New);
188 DAG.TransferDbgValues(Old, New);
190 UpdatedNodes->insert(New.getNode());
191 ReplacedNode(Old.getNode());
193 void ReplaceNode(SDNode *Old, const SDValue *New) {
194 DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG));
196 DAG.ReplaceAllUsesWith(Old, New);
197 for (unsigned i = 0, e = Old->getNumValues(); i != e; ++i) {
198 DEBUG(dbgs() << (i == 0 ? " with: "
201 DAG.TransferDbgValues(SDValue(Old, i), New[i]);
203 UpdatedNodes->insert(New[i].getNode());
210 /// Return a vector shuffle operation which
211 /// performs the same shuffe in terms of order or result bytes, but on a type
212 /// whose vector element type is narrower than the original shuffle type.
213 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
215 SelectionDAGLegalize::ShuffleWithNarrowerEltType(EVT NVT, EVT VT, SDLoc dl,
216 SDValue N1, SDValue N2,
217 ArrayRef<int> Mask) const {
218 unsigned NumMaskElts = VT.getVectorNumElements();
219 unsigned NumDestElts = NVT.getVectorNumElements();
220 unsigned NumEltsGrowth = NumDestElts / NumMaskElts;
222 assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
224 if (NumEltsGrowth == 1)
225 return DAG.getVectorShuffle(NVT, dl, N1, N2, &Mask[0]);
227 SmallVector<int, 8> NewMask;
228 for (unsigned i = 0; i != NumMaskElts; ++i) {
230 for (unsigned j = 0; j != NumEltsGrowth; ++j) {
232 NewMask.push_back(-1);
234 NewMask.push_back(Idx * NumEltsGrowth + j);
237 assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?");
238 assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?");
239 return DAG.getVectorShuffle(NVT, dl, N1, N2, &NewMask[0]);
242 /// Expands the ConstantFP node to an integer constant or
243 /// a load from the constant pool.
245 SelectionDAGLegalize::ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP) {
249 // If a FP immediate is precise when represented as a float and if the
250 // target can do an extending load from float to double, we put it into
251 // the constant pool as a float, even if it's is statically typed as a
252 // double. This shrinks FP constants and canonicalizes them for targets where
253 // an FP extending load is the same cost as a normal load (such as on the x87
254 // fp stack or PPC FP unit).
255 EVT VT = CFP->getValueType(0);
256 ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
258 assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion");
259 return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(), dl,
260 (VT == MVT::f64) ? MVT::i64 : MVT::i32);
265 while (SVT != MVT::f32 && SVT != MVT::f16) {
266 SVT = (MVT::SimpleValueType)(SVT.getSimpleVT().SimpleTy - 1);
267 if (ConstantFPSDNode::isValueValidForType(SVT, CFP->getValueAPF()) &&
268 // Only do this if the target has a native EXTLOAD instruction from
270 TLI.isLoadExtLegal(ISD::EXTLOAD, OrigVT, SVT) &&
271 TLI.ShouldShrinkFPConstant(OrigVT)) {
272 Type *SType = SVT.getTypeForEVT(*DAG.getContext());
273 LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
280 DAG.getConstantPool(LLVMC, TLI.getPointerTy(DAG.getDataLayout()));
281 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
283 SDValue Result = DAG.getExtLoad(
284 ISD::EXTLOAD, dl, OrigVT, DAG.getEntryNode(), CPIdx,
285 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), VT,
286 false, false, false, Alignment);
290 DAG.getLoad(OrigVT, dl, DAG.getEntryNode(), CPIdx,
291 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
292 false, false, false, Alignment);
296 /// Expands an unaligned store to 2 half-size stores.
297 static void ExpandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG,
298 const TargetLowering &TLI,
299 SelectionDAGLegalize *DAGLegalize) {
300 assert(ST->getAddressingMode() == ISD::UNINDEXED &&
301 "unaligned indexed stores not implemented!");
302 SDValue Chain = ST->getChain();
303 SDValue Ptr = ST->getBasePtr();
304 SDValue Val = ST->getValue();
305 EVT VT = Val.getValueType();
306 int Alignment = ST->getAlignment();
307 unsigned AS = ST->getAddressSpace();
310 if (ST->getMemoryVT().isFloatingPoint() ||
311 ST->getMemoryVT().isVector()) {
312 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
313 if (TLI.isTypeLegal(intVT)) {
314 // Expand to a bitconvert of the value to the integer type of the
315 // same size, then a (misaligned) int store.
316 // FIXME: Does not handle truncating floating point stores!
317 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
318 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
319 ST->isVolatile(), ST->isNonTemporal(), Alignment);
320 DAGLegalize->ReplaceNode(SDValue(ST, 0), Result);
323 // Do a (aligned) store to a stack slot, then copy from the stack slot
324 // to the final destination using (unaligned) integer loads and stores.
325 EVT StoredVT = ST->getMemoryVT();
327 TLI.getRegisterType(*DAG.getContext(),
328 EVT::getIntegerVT(*DAG.getContext(),
329 StoredVT.getSizeInBits()));
330 unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
331 unsigned RegBytes = RegVT.getSizeInBits() / 8;
332 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
334 // Make sure the stack slot is also aligned for the register type.
335 SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
337 // Perform the original store, only redirected to the stack slot.
338 SDValue Store = DAG.getTruncStore(Chain, dl,
339 Val, StackPtr, MachinePointerInfo(),
340 StoredVT, false, false, 0);
341 SDValue Increment = DAG.getConstant(
342 RegBytes, dl, TLI.getPointerTy(DAG.getDataLayout(), AS));
343 SmallVector<SDValue, 8> Stores;
346 // Do all but one copies using the full register width.
347 for (unsigned i = 1; i < NumRegs; i++) {
348 // Load one integer register's worth from the stack slot.
349 SDValue Load = DAG.getLoad(RegVT, dl, Store, StackPtr,
350 MachinePointerInfo(),
351 false, false, false, 0);
352 // Store it to the final location. Remember the store.
353 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
354 ST->getPointerInfo().getWithOffset(Offset),
355 ST->isVolatile(), ST->isNonTemporal(),
356 MinAlign(ST->getAlignment(), Offset)));
357 // Increment the pointers.
359 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
361 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
364 // The last store may be partial. Do a truncating store. On big-endian
365 // machines this requires an extending load from the stack slot to ensure
366 // that the bits are in the right place.
367 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
368 8 * (StoredBytes - Offset));
370 // Load from the stack slot.
371 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
372 MachinePointerInfo(),
373 MemVT, false, false, false, 0);
375 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
377 .getWithOffset(Offset),
378 MemVT, ST->isVolatile(),
380 MinAlign(ST->getAlignment(), Offset),
382 // The order of the stores doesn't matter - say it with a TokenFactor.
383 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
384 DAGLegalize->ReplaceNode(SDValue(ST, 0), Result);
387 assert(ST->getMemoryVT().isInteger() &&
388 !ST->getMemoryVT().isVector() &&
389 "Unaligned store of unknown type.");
390 // Get the half-size VT
391 EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
392 int NumBits = NewStoredVT.getSizeInBits();
393 int IncrementSize = NumBits / 8;
395 // Divide the stored value in two parts.
396 SDValue ShiftAmount =
397 DAG.getConstant(NumBits, dl, TLI.getShiftAmountTy(Val.getValueType(),
398 DAG.getDataLayout()));
400 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
402 // Store the two parts
403 SDValue Store1, Store2;
404 Store1 = DAG.getTruncStore(Chain, dl,
405 DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
406 Ptr, ST->getPointerInfo(), NewStoredVT,
407 ST->isVolatile(), ST->isNonTemporal(), Alignment);
409 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
410 DAG.getConstant(IncrementSize, dl,
411 TLI.getPointerTy(DAG.getDataLayout(), AS)));
412 Alignment = MinAlign(Alignment, IncrementSize);
413 Store2 = DAG.getTruncStore(
414 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
415 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT,
416 ST->isVolatile(), ST->isNonTemporal(), Alignment, ST->getAAInfo());
419 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
420 DAGLegalize->ReplaceNode(SDValue(ST, 0), Result);
423 /// Expands an unaligned load to 2 half-size loads.
425 ExpandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG,
426 const TargetLowering &TLI,
427 SDValue &ValResult, SDValue &ChainResult) {
428 assert(LD->getAddressingMode() == ISD::UNINDEXED &&
429 "unaligned indexed loads not implemented!");
430 SDValue Chain = LD->getChain();
431 SDValue Ptr = LD->getBasePtr();
432 EVT VT = LD->getValueType(0);
433 EVT LoadedVT = LD->getMemoryVT();
435 if (VT.isFloatingPoint() || VT.isVector()) {
436 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
437 if (TLI.isTypeLegal(intVT) && TLI.isTypeLegal(LoadedVT)) {
438 // Expand to a (misaligned) integer load of the same size,
439 // then bitconvert to floating point or vector.
440 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
441 LD->getMemOperand());
442 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
444 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
445 ISD::ANY_EXTEND, dl, VT, Result);
448 ChainResult = newLoad.getValue(1);
452 // Copy the value to a (aligned) stack slot using (unaligned) integer
453 // loads and stores, then do a (aligned) load from the stack slot.
454 MVT RegVT = TLI.getRegisterType(*DAG.getContext(), intVT);
455 unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
456 unsigned RegBytes = RegVT.getSizeInBits() / 8;
457 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
459 // Make sure the stack slot is also aligned for the register type.
460 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
463 DAG.getConstant(RegBytes, dl, TLI.getPointerTy(DAG.getDataLayout()));
464 SmallVector<SDValue, 8> Stores;
465 SDValue StackPtr = StackBase;
468 // Do all but one copies using the full register width.
469 for (unsigned i = 1; i < NumRegs; i++) {
470 // Load one integer register's worth from the original location.
471 SDValue Load = DAG.getLoad(RegVT, dl, Chain, Ptr,
472 LD->getPointerInfo().getWithOffset(Offset),
473 LD->isVolatile(), LD->isNonTemporal(),
475 MinAlign(LD->getAlignment(), Offset),
477 // Follow the load with a store to the stack slot. Remember the store.
478 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
479 MachinePointerInfo(), false, false, 0));
480 // Increment the pointers.
482 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
483 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
487 // The last copy may be partial. Do an extending load.
488 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
489 8 * (LoadedBytes - Offset));
490 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
491 LD->getPointerInfo().getWithOffset(Offset),
492 MemVT, LD->isVolatile(),
495 MinAlign(LD->getAlignment(), Offset),
497 // Follow the load with a store to the stack slot. Remember the store.
498 // On big-endian machines this requires a truncating store to ensure
499 // that the bits end up in the right place.
500 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
501 MachinePointerInfo(), MemVT,
504 // The order of the stores doesn't matter - say it with a TokenFactor.
505 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
507 // Finally, perform the original load only redirected to the stack slot.
508 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
509 MachinePointerInfo(), LoadedVT, false,false, false,
512 // Callers expect a MERGE_VALUES node.
517 assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
518 "Unaligned load of unsupported type.");
520 // Compute the new VT that is half the size of the old one. This is an
522 unsigned NumBits = LoadedVT.getSizeInBits();
524 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
527 unsigned Alignment = LD->getAlignment();
528 unsigned IncrementSize = NumBits / 8;
529 ISD::LoadExtType HiExtType = LD->getExtensionType();
531 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
532 if (HiExtType == ISD::NON_EXTLOAD)
533 HiExtType = ISD::ZEXTLOAD;
535 // Load the value in two parts
537 if (DAG.getDataLayout().isLittleEndian()) {
538 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
539 NewLoadedVT, LD->isVolatile(),
540 LD->isNonTemporal(), LD->isInvariant(), Alignment,
542 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
543 DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
544 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
545 LD->getPointerInfo().getWithOffset(IncrementSize),
546 NewLoadedVT, LD->isVolatile(),
547 LD->isNonTemporal(),LD->isInvariant(),
548 MinAlign(Alignment, IncrementSize), LD->getAAInfo());
550 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
551 NewLoadedVT, LD->isVolatile(),
552 LD->isNonTemporal(), LD->isInvariant(), Alignment,
554 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
555 DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
556 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
557 LD->getPointerInfo().getWithOffset(IncrementSize),
558 NewLoadedVT, LD->isVolatile(),
559 LD->isNonTemporal(), LD->isInvariant(),
560 MinAlign(Alignment, IncrementSize), LD->getAAInfo());
563 // aggregate the two parts
564 SDValue ShiftAmount =
565 DAG.getConstant(NumBits, dl, TLI.getShiftAmountTy(Hi.getValueType(),
566 DAG.getDataLayout()));
567 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
568 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
570 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
577 /// Some target cannot handle a variable insertion index for the
578 /// INSERT_VECTOR_ELT instruction. In this case, it
579 /// is necessary to spill the vector being inserted into to memory, perform
580 /// the insert there, and then read the result back.
581 SDValue SelectionDAGLegalize::
582 PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx,
588 // If the target doesn't support this, we have to spill the input vector
589 // to a temporary stack slot, update the element, then reload it. This is
590 // badness. We could also load the value into a vector register (either
591 // with a "move to register" or "extload into register" instruction, then
592 // permute it into place, if the idx is a constant and if the idx is
593 // supported by the target.
594 EVT VT = Tmp1.getValueType();
595 EVT EltVT = VT.getVectorElementType();
596 EVT IdxVT = Tmp3.getValueType();
597 EVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
598 SDValue StackPtr = DAG.CreateStackTemporary(VT);
600 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
603 SDValue Ch = DAG.getStore(
604 DAG.getEntryNode(), dl, Tmp1, StackPtr,
605 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI), false,
608 // Truncate or zero extend offset to target pointer type.
609 Tmp3 = DAG.getZExtOrTrunc(Tmp3, dl, PtrVT);
610 // Add the offset to the index.
611 unsigned EltSize = EltVT.getSizeInBits()/8;
612 Tmp3 = DAG.getNode(ISD::MUL, dl, IdxVT, Tmp3,
613 DAG.getConstant(EltSize, dl, IdxVT));
614 SDValue StackPtr2 = DAG.getNode(ISD::ADD, dl, IdxVT, Tmp3, StackPtr);
615 // Store the scalar value.
616 Ch = DAG.getTruncStore(Ch, dl, Tmp2, StackPtr2, MachinePointerInfo(), EltVT,
618 // Load the updated vector.
619 return DAG.getLoad(VT, dl, Ch, StackPtr, MachinePointerInfo::getFixedStack(
620 DAG.getMachineFunction(), SPFI),
621 false, false, false, 0);
625 SDValue SelectionDAGLegalize::
626 ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, SDValue Idx, SDLoc dl) {
627 if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) {
628 // SCALAR_TO_VECTOR requires that the type of the value being inserted
629 // match the element type of the vector being created, except for
630 // integers in which case the inserted value can be over width.
631 EVT EltVT = Vec.getValueType().getVectorElementType();
632 if (Val.getValueType() == EltVT ||
633 (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) {
634 SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
635 Vec.getValueType(), Val);
637 unsigned NumElts = Vec.getValueType().getVectorNumElements();
638 // We generate a shuffle of InVec and ScVec, so the shuffle mask
639 // should be 0,1,2,3,4,5... with the appropriate element replaced with
641 SmallVector<int, 8> ShufOps;
642 for (unsigned i = 0; i != NumElts; ++i)
643 ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts);
645 return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec,
649 return PerformInsertVectorEltInMemory(Vec, Val, Idx, dl);
652 SDValue SelectionDAGLegalize::OptimizeFloatStore(StoreSDNode* ST) {
653 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
654 // FIXME: We shouldn't do this for TargetConstantFP's.
655 // FIXME: move this to the DAG Combiner! Note that we can't regress due
656 // to phase ordering between legalized code and the dag combiner. This
657 // probably means that we need to integrate dag combiner and legalizer
659 // We generally can't do this one for long doubles.
660 SDValue Chain = ST->getChain();
661 SDValue Ptr = ST->getBasePtr();
662 unsigned Alignment = ST->getAlignment();
663 bool isVolatile = ST->isVolatile();
664 bool isNonTemporal = ST->isNonTemporal();
665 AAMDNodes AAInfo = ST->getAAInfo();
667 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
668 if (CFP->getValueType(0) == MVT::f32 &&
669 TLI.isTypeLegal(MVT::i32)) {
670 SDValue Con = DAG.getConstant(CFP->getValueAPF().
671 bitcastToAPInt().zextOrTrunc(32),
672 SDLoc(CFP), MVT::i32);
673 return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(),
674 isVolatile, isNonTemporal, Alignment, AAInfo);
677 if (CFP->getValueType(0) == MVT::f64) {
678 // If this target supports 64-bit registers, do a single 64-bit store.
679 if (TLI.isTypeLegal(MVT::i64)) {
680 SDValue Con = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
681 zextOrTrunc(64), SDLoc(CFP), MVT::i64);
682 return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(),
683 isVolatile, isNonTemporal, Alignment, AAInfo);
686 if (TLI.isTypeLegal(MVT::i32) && !ST->isVolatile()) {
687 // Otherwise, if the target supports 32-bit registers, use 2 32-bit
688 // stores. If the target supports neither 32- nor 64-bits, this
689 // xform is certainly not worth it.
690 const APInt &IntVal = CFP->getValueAPF().bitcastToAPInt();
691 SDValue Lo = DAG.getConstant(IntVal.trunc(32), dl, MVT::i32);
692 SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), dl, MVT::i32);
693 if (DAG.getDataLayout().isBigEndian())
696 Lo = DAG.getStore(Chain, dl, Lo, Ptr, ST->getPointerInfo(), isVolatile,
697 isNonTemporal, Alignment, AAInfo);
698 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
699 DAG.getConstant(4, dl, Ptr.getValueType()));
700 Hi = DAG.getStore(Chain, dl, Hi, Ptr,
701 ST->getPointerInfo().getWithOffset(4),
702 isVolatile, isNonTemporal, MinAlign(Alignment, 4U),
705 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
709 return SDValue(nullptr, 0);
712 void SelectionDAGLegalize::LegalizeStoreOps(SDNode *Node) {
713 StoreSDNode *ST = cast<StoreSDNode>(Node);
714 SDValue Chain = ST->getChain();
715 SDValue Ptr = ST->getBasePtr();
718 unsigned Alignment = ST->getAlignment();
719 bool isVolatile = ST->isVolatile();
720 bool isNonTemporal = ST->isNonTemporal();
721 AAMDNodes AAInfo = ST->getAAInfo();
723 if (!ST->isTruncatingStore()) {
724 if (SDNode *OptStore = OptimizeFloatStore(ST).getNode()) {
725 ReplaceNode(ST, OptStore);
730 SDValue Value = ST->getValue();
731 MVT VT = Value.getSimpleValueType();
732 switch (TLI.getOperationAction(ISD::STORE, VT)) {
733 default: llvm_unreachable("This action is not supported yet!");
734 case TargetLowering::Legal: {
735 // If this is an unaligned store and the target doesn't support it,
737 EVT MemVT = ST->getMemoryVT();
738 unsigned AS = ST->getAddressSpace();
739 unsigned Align = ST->getAlignment();
740 const DataLayout &DL = DAG.getDataLayout();
741 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Align))
742 ExpandUnalignedStore(cast<StoreSDNode>(Node), DAG, TLI, this);
745 case TargetLowering::Custom: {
746 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
747 if (Res && Res != SDValue(Node, 0))
748 ReplaceNode(SDValue(Node, 0), Res);
751 case TargetLowering::Promote: {
752 MVT NVT = TLI.getTypeToPromoteTo(ISD::STORE, VT);
753 assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
754 "Can only promote stores to same size type");
755 Value = DAG.getNode(ISD::BITCAST, dl, NVT, Value);
757 DAG.getStore(Chain, dl, Value, Ptr,
758 ST->getPointerInfo(), isVolatile,
759 isNonTemporal, Alignment, AAInfo);
760 ReplaceNode(SDValue(Node, 0), Result);
767 SDValue Value = ST->getValue();
769 EVT StVT = ST->getMemoryVT();
770 unsigned StWidth = StVT.getSizeInBits();
771 auto &DL = DAG.getDataLayout();
773 if (StWidth != StVT.getStoreSizeInBits()) {
774 // Promote to a byte-sized store with upper bits zero if not
775 // storing an integral number of bytes. For example, promote
776 // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
777 EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
778 StVT.getStoreSizeInBits());
779 Value = DAG.getZeroExtendInReg(Value, dl, StVT);
781 DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
782 NVT, isVolatile, isNonTemporal, Alignment, AAInfo);
783 ReplaceNode(SDValue(Node, 0), Result);
784 } else if (StWidth & (StWidth - 1)) {
785 // If not storing a power-of-2 number of bits, expand as two stores.
786 assert(!StVT.isVector() && "Unsupported truncstore!");
787 unsigned RoundWidth = 1 << Log2_32(StWidth);
788 assert(RoundWidth < StWidth);
789 unsigned ExtraWidth = StWidth - RoundWidth;
790 assert(ExtraWidth < RoundWidth);
791 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
792 "Store size not an integral number of bytes!");
793 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
794 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
796 unsigned IncrementSize;
798 if (DL.isLittleEndian()) {
799 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
800 // Store the bottom RoundWidth bits.
801 Lo = DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
803 isVolatile, isNonTemporal, Alignment,
806 // Store the remaining ExtraWidth bits.
807 IncrementSize = RoundWidth / 8;
808 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
809 DAG.getConstant(IncrementSize, dl,
810 Ptr.getValueType()));
812 ISD::SRL, dl, Value.getValueType(), Value,
813 DAG.getConstant(RoundWidth, dl,
814 TLI.getShiftAmountTy(Value.getValueType(), DL)));
815 Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr,
816 ST->getPointerInfo().getWithOffset(IncrementSize),
817 ExtraVT, isVolatile, isNonTemporal,
818 MinAlign(Alignment, IncrementSize), AAInfo);
820 // Big endian - avoid unaligned stores.
821 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
822 // Store the top RoundWidth bits.
824 ISD::SRL, dl, Value.getValueType(), Value,
825 DAG.getConstant(ExtraWidth, dl,
826 TLI.getShiftAmountTy(Value.getValueType(), DL)));
827 Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr, ST->getPointerInfo(),
828 RoundVT, isVolatile, isNonTemporal, Alignment,
831 // Store the remaining ExtraWidth bits.
832 IncrementSize = RoundWidth / 8;
833 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
834 DAG.getConstant(IncrementSize, dl,
835 Ptr.getValueType()));
836 Lo = DAG.getTruncStore(Chain, dl, Value, Ptr,
837 ST->getPointerInfo().getWithOffset(IncrementSize),
838 ExtraVT, isVolatile, isNonTemporal,
839 MinAlign(Alignment, IncrementSize), AAInfo);
842 // The order of the stores doesn't matter.
843 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
844 ReplaceNode(SDValue(Node, 0), Result);
846 switch (TLI.getTruncStoreAction(ST->getValue().getSimpleValueType(),
847 StVT.getSimpleVT())) {
848 default: llvm_unreachable("This action is not supported yet!");
849 case TargetLowering::Legal: {
850 EVT MemVT = ST->getMemoryVT();
851 unsigned AS = ST->getAddressSpace();
852 unsigned Align = ST->getAlignment();
853 // If this is an unaligned store and the target doesn't support it,
855 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Align))
856 ExpandUnalignedStore(cast<StoreSDNode>(Node), DAG, TLI, this);
859 case TargetLowering::Custom: {
860 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
861 if (Res && Res != SDValue(Node, 0))
862 ReplaceNode(SDValue(Node, 0), Res);
865 case TargetLowering::Expand:
866 assert(!StVT.isVector() &&
867 "Vector Stores are handled in LegalizeVectorOps");
869 // TRUNCSTORE:i16 i32 -> STORE i16
870 assert(TLI.isTypeLegal(StVT) &&
871 "Do not know how to expand this store!");
872 Value = DAG.getNode(ISD::TRUNCATE, dl, StVT, Value);
874 DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
875 isVolatile, isNonTemporal, Alignment, AAInfo);
876 ReplaceNode(SDValue(Node, 0), Result);
883 void SelectionDAGLegalize::LegalizeLoadOps(SDNode *Node) {
884 LoadSDNode *LD = cast<LoadSDNode>(Node);
885 SDValue Chain = LD->getChain(); // The chain.
886 SDValue Ptr = LD->getBasePtr(); // The base pointer.
887 SDValue Value; // The value returned by the load op.
890 ISD::LoadExtType ExtType = LD->getExtensionType();
891 if (ExtType == ISD::NON_EXTLOAD) {
892 MVT VT = Node->getSimpleValueType(0);
893 SDValue RVal = SDValue(Node, 0);
894 SDValue RChain = SDValue(Node, 1);
896 switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
897 default: llvm_unreachable("This action is not supported yet!");
898 case TargetLowering::Legal: {
899 EVT MemVT = LD->getMemoryVT();
900 unsigned AS = LD->getAddressSpace();
901 unsigned Align = LD->getAlignment();
902 const DataLayout &DL = DAG.getDataLayout();
903 // If this is an unaligned load and the target doesn't support it,
905 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Align))
906 ExpandUnalignedLoad(cast<LoadSDNode>(Node), DAG, TLI, RVal, RChain);
909 case TargetLowering::Custom: {
910 SDValue Res = TLI.LowerOperation(RVal, DAG);
913 RChain = Res.getValue(1);
917 case TargetLowering::Promote: {
918 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
919 assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
920 "Can only promote loads to same size type");
922 SDValue Res = DAG.getLoad(NVT, dl, Chain, Ptr, LD->getMemOperand());
923 RVal = DAG.getNode(ISD::BITCAST, dl, VT, Res);
924 RChain = Res.getValue(1);
928 if (RChain.getNode() != Node) {
929 assert(RVal.getNode() != Node && "Load must be completely replaced");
930 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), RVal);
931 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), RChain);
933 UpdatedNodes->insert(RVal.getNode());
934 UpdatedNodes->insert(RChain.getNode());
941 EVT SrcVT = LD->getMemoryVT();
942 unsigned SrcWidth = SrcVT.getSizeInBits();
943 unsigned Alignment = LD->getAlignment();
944 bool isVolatile = LD->isVolatile();
945 bool isNonTemporal = LD->isNonTemporal();
946 bool isInvariant = LD->isInvariant();
947 AAMDNodes AAInfo = LD->getAAInfo();
949 if (SrcWidth != SrcVT.getStoreSizeInBits() &&
950 // Some targets pretend to have an i1 loading operation, and actually
951 // load an i8. This trick is correct for ZEXTLOAD because the top 7
952 // bits are guaranteed to be zero; it helps the optimizers understand
953 // that these bits are zero. It is also useful for EXTLOAD, since it
954 // tells the optimizers that those bits are undefined. It would be
955 // nice to have an effective generic way of getting these benefits...
956 // Until such a way is found, don't insist on promoting i1 here.
958 TLI.getLoadExtAction(ExtType, Node->getValueType(0), MVT::i1) ==
959 TargetLowering::Promote)) {
960 // Promote to a byte-sized load if not loading an integral number of
961 // bytes. For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
962 unsigned NewWidth = SrcVT.getStoreSizeInBits();
963 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), NewWidth);
966 // The extra bits are guaranteed to be zero, since we stored them that
967 // way. A zext load from NVT thus automatically gives zext from SrcVT.
969 ISD::LoadExtType NewExtType =
970 ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
973 DAG.getExtLoad(NewExtType, dl, Node->getValueType(0),
974 Chain, Ptr, LD->getPointerInfo(),
975 NVT, isVolatile, isNonTemporal, isInvariant, Alignment,
978 Ch = Result.getValue(1); // The chain.
980 if (ExtType == ISD::SEXTLOAD)
981 // Having the top bits zero doesn't help when sign extending.
982 Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
983 Result.getValueType(),
984 Result, DAG.getValueType(SrcVT));
985 else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
986 // All the top bits are guaranteed to be zero - inform the optimizers.
987 Result = DAG.getNode(ISD::AssertZext, dl,
988 Result.getValueType(), Result,
989 DAG.getValueType(SrcVT));
993 } else if (SrcWidth & (SrcWidth - 1)) {
994 // If not loading a power-of-2 number of bits, expand as two loads.
995 assert(!SrcVT.isVector() && "Unsupported extload!");
996 unsigned RoundWidth = 1 << Log2_32(SrcWidth);
997 assert(RoundWidth < SrcWidth);
998 unsigned ExtraWidth = SrcWidth - RoundWidth;
999 assert(ExtraWidth < RoundWidth);
1000 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
1001 "Load size not an integral number of bytes!");
1002 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
1003 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
1005 unsigned IncrementSize;
1006 auto &DL = DAG.getDataLayout();
1008 if (DL.isLittleEndian()) {
1009 // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
1010 // Load the bottom RoundWidth bits.
1011 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0),
1013 LD->getPointerInfo(), RoundVT, isVolatile,
1014 isNonTemporal, isInvariant, Alignment, AAInfo);
1016 // Load the remaining ExtraWidth bits.
1017 IncrementSize = RoundWidth / 8;
1018 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
1019 DAG.getConstant(IncrementSize, dl,
1020 Ptr.getValueType()));
1021 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
1022 LD->getPointerInfo().getWithOffset(IncrementSize),
1023 ExtraVT, isVolatile, isNonTemporal, isInvariant,
1024 MinAlign(Alignment, IncrementSize), AAInfo);
1026 // Build a factor node to remember that this load is independent of
1028 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1031 // Move the top bits to the right place.
1033 ISD::SHL, dl, Hi.getValueType(), Hi,
1034 DAG.getConstant(RoundWidth, dl,
1035 TLI.getShiftAmountTy(Hi.getValueType(), DL)));
1037 // Join the hi and lo parts.
1038 Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1040 // Big endian - avoid unaligned loads.
1041 // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
1042 // Load the top RoundWidth bits.
1043 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
1044 LD->getPointerInfo(), RoundVT, isVolatile,
1045 isNonTemporal, isInvariant, Alignment, AAInfo);
1047 // Load the remaining ExtraWidth bits.
1048 IncrementSize = RoundWidth / 8;
1049 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
1050 DAG.getConstant(IncrementSize, dl,
1051 Ptr.getValueType()));
1052 Lo = DAG.getExtLoad(ISD::ZEXTLOAD,
1053 dl, Node->getValueType(0), Chain, Ptr,
1054 LD->getPointerInfo().getWithOffset(IncrementSize),
1055 ExtraVT, isVolatile, isNonTemporal, isInvariant,
1056 MinAlign(Alignment, IncrementSize), AAInfo);
1058 // Build a factor node to remember that this load is independent of
1060 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1063 // Move the top bits to the right place.
1065 ISD::SHL, dl, Hi.getValueType(), Hi,
1066 DAG.getConstant(ExtraWidth, dl,
1067 TLI.getShiftAmountTy(Hi.getValueType(), DL)));
1069 // Join the hi and lo parts.
1070 Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1075 bool isCustom = false;
1076 switch (TLI.getLoadExtAction(ExtType, Node->getValueType(0),
1077 SrcVT.getSimpleVT())) {
1078 default: llvm_unreachable("This action is not supported yet!");
1079 case TargetLowering::Custom:
1082 case TargetLowering::Legal: {
1083 Value = SDValue(Node, 0);
1084 Chain = SDValue(Node, 1);
1087 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
1088 if (Res.getNode()) {
1090 Chain = Res.getValue(1);
1093 // If this is an unaligned load and the target doesn't support it,
1095 EVT MemVT = LD->getMemoryVT();
1096 unsigned AS = LD->getAddressSpace();
1097 unsigned Align = LD->getAlignment();
1098 const DataLayout &DL = DAG.getDataLayout();
1099 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Align))
1100 ExpandUnalignedLoad(cast<LoadSDNode>(Node), DAG, TLI, Value, Chain);
1104 case TargetLowering::Expand:
1105 EVT DestVT = Node->getValueType(0);
1106 if (!TLI.isLoadExtLegal(ISD::EXTLOAD, DestVT, SrcVT)) {
1107 // If the source type is not legal, see if there is a legal extload to
1108 // an intermediate type that we can then extend further.
1109 EVT LoadVT = TLI.getRegisterType(SrcVT.getSimpleVT());
1110 if (TLI.isTypeLegal(SrcVT) || // Same as SrcVT == LoadVT?
1111 TLI.isLoadExtLegal(ExtType, LoadVT, SrcVT)) {
1112 // If we are loading a legal type, this is a non-extload followed by a
1114 ISD::LoadExtType MidExtType =
1115 (LoadVT == SrcVT) ? ISD::NON_EXTLOAD : ExtType;
1117 SDValue Load = DAG.getExtLoad(MidExtType, dl, LoadVT, Chain, Ptr,
1118 SrcVT, LD->getMemOperand());
1120 ISD::getExtForLoadExtType(SrcVT.isFloatingPoint(), ExtType);
1121 Value = DAG.getNode(ExtendOp, dl, Node->getValueType(0), Load);
1122 Chain = Load.getValue(1);
1126 // Handle the special case of fp16 extloads. EXTLOAD doesn't have the
1127 // normal undefined upper bits behavior to allow using an in-reg extend
1128 // with the illegal FP type, so load as an integer and do the
1129 // from-integer conversion.
1130 if (SrcVT.getScalarType() == MVT::f16) {
1131 EVT ISrcVT = SrcVT.changeTypeToInteger();
1132 EVT IDestVT = DestVT.changeTypeToInteger();
1133 EVT LoadVT = TLI.getRegisterType(IDestVT.getSimpleVT());
1135 SDValue Result = DAG.getExtLoad(ISD::ZEXTLOAD, dl, LoadVT,
1137 LD->getMemOperand());
1138 Value = DAG.getNode(ISD::FP16_TO_FP, dl, DestVT, Result);
1139 Chain = Result.getValue(1);
1144 assert(!SrcVT.isVector() &&
1145 "Vector Loads are handled in LegalizeVectorOps");
1147 // FIXME: This does not work for vectors on most targets. Sign-
1148 // and zero-extend operations are currently folded into extending
1149 // loads, whether they are legal or not, and then we end up here
1150 // without any support for legalizing them.
1151 assert(ExtType != ISD::EXTLOAD &&
1152 "EXTLOAD should always be supported!");
1153 // Turn the unsupported load into an EXTLOAD followed by an
1154 // explicit zero/sign extend inreg.
1155 SDValue Result = DAG.getExtLoad(ISD::EXTLOAD, dl,
1156 Node->getValueType(0),
1158 LD->getMemOperand());
1160 if (ExtType == ISD::SEXTLOAD)
1161 ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
1162 Result.getValueType(),
1163 Result, DAG.getValueType(SrcVT));
1165 ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT.getScalarType());
1167 Chain = Result.getValue(1);
1172 // Since loads produce two values, make sure to remember that we legalized
1174 if (Chain.getNode() != Node) {
1175 assert(Value.getNode() != Node && "Load must be completely replaced");
1176 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Value);
1177 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
1179 UpdatedNodes->insert(Value.getNode());
1180 UpdatedNodes->insert(Chain.getNode());
1186 /// Return a legal replacement for the given operation, with all legal operands.
1187 void SelectionDAGLegalize::LegalizeOp(SDNode *Node) {
1188 DEBUG(dbgs() << "\nLegalizing: "; Node->dump(&DAG));
1190 if (Node->getOpcode() == ISD::TargetConstant) // Allow illegal target nodes.
1194 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
1195 assert(TLI.getTypeAction(*DAG.getContext(), Node->getValueType(i)) ==
1196 TargetLowering::TypeLegal &&
1197 "Unexpected illegal type!");
1199 for (const SDValue &Op : Node->op_values())
1200 assert((TLI.getTypeAction(*DAG.getContext(),
1201 Op.getValueType()) == TargetLowering::TypeLegal ||
1202 Op.getOpcode() == ISD::TargetConstant) &&
1203 "Unexpected illegal type!");
1206 // Figure out the correct action; the way to query this varies by opcode
1207 TargetLowering::LegalizeAction Action = TargetLowering::Legal;
1208 bool SimpleFinishLegalizing = true;
1209 switch (Node->getOpcode()) {
1210 case ISD::INTRINSIC_W_CHAIN:
1211 case ISD::INTRINSIC_WO_CHAIN:
1212 case ISD::INTRINSIC_VOID:
1213 case ISD::STACKSAVE:
1214 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
1217 Action = TLI.getOperationAction(Node->getOpcode(),
1218 Node->getValueType(0));
1219 if (Action != TargetLowering::Promote)
1220 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
1222 case ISD::FP_TO_FP16:
1223 case ISD::SINT_TO_FP:
1224 case ISD::UINT_TO_FP:
1225 case ISD::EXTRACT_VECTOR_ELT:
1226 Action = TLI.getOperationAction(Node->getOpcode(),
1227 Node->getOperand(0).getValueType());
1229 case ISD::FP_ROUND_INREG:
1230 case ISD::SIGN_EXTEND_INREG: {
1231 EVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT();
1232 Action = TLI.getOperationAction(Node->getOpcode(), InnerType);
1235 case ISD::ATOMIC_STORE: {
1236 Action = TLI.getOperationAction(Node->getOpcode(),
1237 Node->getOperand(2).getValueType());
1240 case ISD::SELECT_CC:
1243 unsigned CCOperand = Node->getOpcode() == ISD::SELECT_CC ? 4 :
1244 Node->getOpcode() == ISD::SETCC ? 2 : 1;
1245 unsigned CompareOperand = Node->getOpcode() == ISD::BR_CC ? 2 : 0;
1246 MVT OpVT = Node->getOperand(CompareOperand).getSimpleValueType();
1247 ISD::CondCode CCCode =
1248 cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get();
1249 Action = TLI.getCondCodeAction(CCCode, OpVT);
1250 if (Action == TargetLowering::Legal) {
1251 if (Node->getOpcode() == ISD::SELECT_CC)
1252 Action = TLI.getOperationAction(Node->getOpcode(),
1253 Node->getValueType(0));
1255 Action = TLI.getOperationAction(Node->getOpcode(), OpVT);
1261 // FIXME: Model these properly. LOAD and STORE are complicated, and
1262 // STORE expects the unlegalized operand in some cases.
1263 SimpleFinishLegalizing = false;
1265 case ISD::CALLSEQ_START:
1266 case ISD::CALLSEQ_END:
1267 // FIXME: This shouldn't be necessary. These nodes have special properties
1268 // dealing with the recursive nature of legalization. Removing this
1269 // special case should be done as part of making LegalizeDAG non-recursive.
1270 SimpleFinishLegalizing = false;
1272 case ISD::EXTRACT_ELEMENT:
1273 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 case ISD::EH_SJLJ_SETUP_DISPATCH:
1281 // These operations lie about being legal: when they claim to be legal,
1282 // they should actually be expanded.
1283 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1284 if (Action == TargetLowering::Legal)
1285 Action = TargetLowering::Expand;
1287 case ISD::INIT_TRAMPOLINE:
1288 case ISD::ADJUST_TRAMPOLINE:
1289 case ISD::FRAMEADDR:
1290 case ISD::RETURNADDR:
1291 // These operations lie about being legal: when they claim to be legal,
1292 // they should actually be custom-lowered.
1293 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1294 if (Action == TargetLowering::Legal)
1295 Action = TargetLowering::Custom;
1297 case ISD::READCYCLECOUNTER:
1298 // READCYCLECOUNTER returns an i64, even if type legalization might have
1299 // expanded that to several smaller types.
1300 Action = TLI.getOperationAction(Node->getOpcode(), MVT::i64);
1302 case ISD::READ_REGISTER:
1303 case ISD::WRITE_REGISTER:
1304 // Named register is legal in the DAG, but blocked by register name
1305 // selection if not implemented by target (to chose the correct register)
1306 // They'll be converted to Copy(To/From)Reg.
1307 Action = TargetLowering::Legal;
1309 case ISD::DEBUGTRAP:
1310 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1311 if (Action == TargetLowering::Expand) {
1312 // replace ISD::DEBUGTRAP with ISD::TRAP
1314 NewVal = DAG.getNode(ISD::TRAP, SDLoc(Node), Node->getVTList(),
1315 Node->getOperand(0));
1316 ReplaceNode(Node, NewVal.getNode());
1317 LegalizeOp(NewVal.getNode());
1323 if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
1324 Action = TargetLowering::Legal;
1326 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1331 if (SimpleFinishLegalizing) {
1332 SDNode *NewNode = Node;
1333 switch (Node->getOpcode()) {
1340 // Legalizing shifts/rotates requires adjusting the shift amount
1341 // to the appropriate width.
1342 if (!Node->getOperand(1).getValueType().isVector()) {
1344 DAG.getShiftAmountOperand(Node->getOperand(0).getValueType(),
1345 Node->getOperand(1));
1346 HandleSDNode Handle(SAO);
1347 LegalizeOp(SAO.getNode());
1348 NewNode = DAG.UpdateNodeOperands(Node, Node->getOperand(0),
1352 case ISD::SRL_PARTS:
1353 case ISD::SRA_PARTS:
1354 case ISD::SHL_PARTS:
1355 // Legalizing shifts/rotates requires adjusting the shift amount
1356 // to the appropriate width.
1357 if (!Node->getOperand(2).getValueType().isVector()) {
1359 DAG.getShiftAmountOperand(Node->getOperand(0).getValueType(),
1360 Node->getOperand(2));
1361 HandleSDNode Handle(SAO);
1362 LegalizeOp(SAO.getNode());
1363 NewNode = DAG.UpdateNodeOperands(Node, Node->getOperand(0),
1364 Node->getOperand(1),
1370 if (NewNode != Node) {
1371 ReplaceNode(Node, NewNode);
1375 case TargetLowering::Legal:
1377 case TargetLowering::Custom: {
1378 // FIXME: The handling for custom lowering with multiple results is
1380 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
1381 if (Res.getNode()) {
1382 if (!(Res.getNode() != Node || Res.getResNo() != 0))
1385 if (Node->getNumValues() == 1) {
1386 // We can just directly replace this node with the lowered value.
1387 ReplaceNode(SDValue(Node, 0), Res);
1391 SmallVector<SDValue, 8> ResultVals;
1392 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
1393 ResultVals.push_back(Res.getValue(i));
1394 ReplaceNode(Node, ResultVals.data());
1399 case TargetLowering::Expand:
1400 if (ExpandNode(Node))
1403 case TargetLowering::LibCall:
1404 ConvertNodeToLibcall(Node);
1406 case TargetLowering::Promote:
1412 switch (Node->getOpcode()) {
1419 llvm_unreachable("Do not know how to legalize this operator!");
1421 case ISD::CALLSEQ_START:
1422 case ISD::CALLSEQ_END:
1425 return LegalizeLoadOps(Node);
1428 return LegalizeStoreOps(Node);
1433 SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
1434 SDValue Vec = Op.getOperand(0);
1435 SDValue Idx = Op.getOperand(1);
1438 // Before we generate a new store to a temporary stack slot, see if there is
1439 // already one that we can use. There often is because when we scalarize
1440 // vector operations (using SelectionDAG::UnrollVectorOp for example) a whole
1441 // series of EXTRACT_VECTOR_ELT nodes are generated, one for each element in
1442 // the vector. If all are expanded here, we don't want one store per vector
1444 SDValue StackPtr, Ch;
1445 for (SDNode::use_iterator UI = Vec.getNode()->use_begin(),
1446 UE = Vec.getNode()->use_end(); UI != UE; ++UI) {
1448 if (StoreSDNode *ST = dyn_cast<StoreSDNode>(User)) {
1449 if (ST->isIndexed() || ST->isTruncatingStore() ||
1450 ST->getValue() != Vec)
1453 // Make sure that nothing else could have stored into the destination of
1455 if (!ST->getChain().reachesChainWithoutSideEffects(DAG.getEntryNode()))
1458 StackPtr = ST->getBasePtr();
1459 Ch = SDValue(ST, 0);
1464 if (!Ch.getNode()) {
1465 // Store the value to a temporary stack slot, then LOAD the returned part.
1466 StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
1467 Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr,
1468 MachinePointerInfo(), false, false, 0);
1471 // Add the offset to the index.
1473 Vec.getValueType().getVectorElementType().getSizeInBits()/8;
1474 Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
1475 DAG.getConstant(EltSize, SDLoc(Vec), Idx.getValueType()));
1477 Idx = DAG.getZExtOrTrunc(Idx, dl, TLI.getPointerTy(DAG.getDataLayout()));
1478 StackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx, StackPtr);
1482 if (Op.getValueType().isVector())
1483 NewLoad = DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr,
1484 MachinePointerInfo(), false, false, false, 0);
1486 NewLoad = DAG.getExtLoad(
1487 ISD::EXTLOAD, dl, Op.getValueType(), Ch, StackPtr, MachinePointerInfo(),
1488 Vec.getValueType().getVectorElementType(), false, false, false, 0);
1490 // Replace the chain going out of the store, by the one out of the load.
1491 DAG.ReplaceAllUsesOfValueWith(Ch, SDValue(NewLoad.getNode(), 1));
1493 // We introduced a cycle though, so update the loads operands, making sure
1494 // to use the original store's chain as an incoming chain.
1495 SmallVector<SDValue, 6> NewLoadOperands(NewLoad->op_begin(),
1497 NewLoadOperands[0] = Ch;
1499 SDValue(DAG.UpdateNodeOperands(NewLoad.getNode(), NewLoadOperands), 0);
1503 SDValue SelectionDAGLegalize::ExpandInsertToVectorThroughStack(SDValue Op) {
1504 assert(Op.getValueType().isVector() && "Non-vector insert subvector!");
1506 SDValue Vec = Op.getOperand(0);
1507 SDValue Part = Op.getOperand(1);
1508 SDValue Idx = Op.getOperand(2);
1511 // Store the value to a temporary stack slot, then LOAD the returned part.
1513 SDValue StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
1514 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
1515 MachinePointerInfo PtrInfo =
1516 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
1518 // First store the whole vector.
1519 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, PtrInfo,
1522 // Then store the inserted part.
1524 // Add the offset to the index.
1526 Vec.getValueType().getVectorElementType().getSizeInBits()/8;
1528 Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
1529 DAG.getConstant(EltSize, SDLoc(Vec), Idx.getValueType()));
1530 Idx = DAG.getZExtOrTrunc(Idx, dl, TLI.getPointerTy(DAG.getDataLayout()));
1532 SDValue SubStackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx,
1535 // Store the subvector.
1536 Ch = DAG.getStore(Ch, dl, Part, SubStackPtr,
1537 MachinePointerInfo(), false, false, 0);
1539 // Finally, load the updated vector.
1540 return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, PtrInfo,
1541 false, false, false, 0);
1544 SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) {
1545 // We can't handle this case efficiently. Allocate a sufficiently
1546 // aligned object on the stack, store each element into it, then load
1547 // the result as a vector.
1548 // Create the stack frame object.
1549 EVT VT = Node->getValueType(0);
1550 EVT EltVT = VT.getVectorElementType();
1552 SDValue FIPtr = DAG.CreateStackTemporary(VT);
1553 int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
1554 MachinePointerInfo PtrInfo =
1555 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
1557 // Emit a store of each element to the stack slot.
1558 SmallVector<SDValue, 8> Stores;
1559 unsigned TypeByteSize = EltVT.getSizeInBits() / 8;
1560 // Store (in the right endianness) the elements to memory.
1561 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1562 // Ignore undef elements.
1563 if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1565 unsigned Offset = TypeByteSize*i;
1567 SDValue Idx = DAG.getConstant(Offset, dl, FIPtr.getValueType());
1568 Idx = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, Idx);
1570 // If the destination vector element type is narrower than the source
1571 // element type, only store the bits necessary.
1572 if (EltVT.bitsLT(Node->getOperand(i).getValueType().getScalarType())) {
1573 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
1574 Node->getOperand(i), Idx,
1575 PtrInfo.getWithOffset(Offset),
1576 EltVT, false, false, 0));
1578 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
1579 Node->getOperand(i), Idx,
1580 PtrInfo.getWithOffset(Offset),
1585 if (!Stores.empty()) // Not all undef elements?
1586 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
1588 StoreChain = DAG.getEntryNode();
1590 // Result is a load from the stack slot.
1591 return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo,
1592 false, false, false, 0);
1596 /// Keeps track of state when getting the sign of a floating-point value as an
1598 struct FloatSignAsInt {
1603 MachinePointerInfo IntPointerInfo;
1604 MachinePointerInfo FloatPointerInfo;
1610 /// Bitcast a floating-point value to an integer value. Only bitcast the part
1611 /// containing the sign bit if the target has no integer value capable of
1612 /// holding all bits of the floating-point value.
1613 void SelectionDAGLegalize::getSignAsIntValue(FloatSignAsInt &State,
1614 SDLoc DL, SDValue Value) const {
1615 EVT FloatVT = Value.getValueType();
1616 unsigned NumBits = FloatVT.getSizeInBits();
1617 State.FloatVT = FloatVT;
1618 EVT IVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
1619 // Convert to an integer of the same size.
1620 if (TLI.isTypeLegal(IVT)) {
1621 State.IntValue = DAG.getNode(ISD::BITCAST, DL, IVT, Value);
1622 State.SignMask = APInt::getSignBit(NumBits);
1626 auto &DataLayout = DAG.getDataLayout();
1627 // Store the float to memory, then load the sign part out as an integer.
1628 MVT LoadTy = TLI.getRegisterType(*DAG.getContext(), MVT::i8);
1629 // First create a temporary that is aligned for both the load and store.
1630 SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy);
1631 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
1632 // Then store the float to it.
1633 State.FloatPtr = StackPtr;
1634 MachineFunction &MF = DAG.getMachineFunction();
1635 State.FloatPointerInfo = MachinePointerInfo::getFixedStack(MF, FI);
1636 State.Chain = DAG.getStore(DAG.getEntryNode(), DL, Value, State.FloatPtr,
1637 State.FloatPointerInfo, false, false, 0);
1640 if (DataLayout.isBigEndian()) {
1641 assert(FloatVT.isByteSized() && "Unsupported floating point type!");
1642 // Load out a legal integer with the same sign bit as the float.
1644 State.IntPointerInfo = State.FloatPointerInfo;
1646 // Advance the pointer so that the loaded byte will contain the sign bit.
1647 unsigned ByteOffset = (FloatVT.getSizeInBits() / 8) - 1;
1648 IntPtr = DAG.getNode(ISD::ADD, DL, StackPtr.getValueType(), StackPtr,
1649 DAG.getConstant(ByteOffset, DL, StackPtr.getValueType()));
1650 State.IntPointerInfo = MachinePointerInfo::getFixedStack(MF, FI,
1654 State.IntPtr = IntPtr;
1655 State.IntValue = DAG.getExtLoad(ISD::EXTLOAD, DL, LoadTy, State.Chain,
1656 IntPtr, State.IntPointerInfo, MVT::i8,
1657 false, false, false, 0);
1658 State.SignMask = APInt::getOneBitSet(LoadTy.getSizeInBits(), 7);
1661 /// Replace the integer value produced by getSignAsIntValue() with a new value
1662 /// and cast the result back to a floating-point type.
1663 SDValue SelectionDAGLegalize::modifySignAsInt(const FloatSignAsInt &State,
1664 SDLoc DL, SDValue NewIntValue) const {
1666 return DAG.getNode(ISD::BITCAST, DL, State.FloatVT, NewIntValue);
1668 // Override the part containing the sign bit in the value stored on the stack.
1669 SDValue Chain = DAG.getTruncStore(State.Chain, DL, NewIntValue, State.IntPtr,
1670 State.IntPointerInfo, MVT::i8, false, false,
1672 return DAG.getLoad(State.FloatVT, DL, Chain, State.FloatPtr,
1673 State.FloatPointerInfo, false, false, false, 0);
1676 SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode *Node) const {
1678 SDValue Mag = Node->getOperand(0);
1679 SDValue Sign = Node->getOperand(1);
1681 // Get sign bit into an integer value.
1682 FloatSignAsInt SignAsInt;
1683 getSignAsIntValue(SignAsInt, DL, Sign);
1685 EVT IntVT = SignAsInt.IntValue.getValueType();
1686 SDValue SignMask = DAG.getConstant(SignAsInt.SignMask, DL, IntVT);
1687 SDValue SignBit = DAG.getNode(ISD::AND, DL, IntVT, SignAsInt.IntValue,
1690 // If FABS is legal transform FCOPYSIGN(x, y) => sign(x) ? -FABS(x) : FABS(X)
1691 EVT FloatVT = Mag.getValueType();
1692 if (TLI.isOperationLegalOrCustom(ISD::FABS, FloatVT) &&
1693 TLI.isOperationLegalOrCustom(ISD::FNEG, FloatVT)) {
1694 SDValue AbsValue = DAG.getNode(ISD::FABS, DL, FloatVT, Mag);
1695 SDValue NegValue = DAG.getNode(ISD::FNEG, DL, FloatVT, AbsValue);
1696 SDValue Cond = DAG.getSetCC(DL, getSetCCResultType(IntVT), SignBit,
1697 DAG.getConstant(0, DL, IntVT), ISD::SETNE);
1698 return DAG.getSelect(DL, FloatVT, Cond, NegValue, AbsValue);
1701 // Transform values to integer, copy the sign bit and transform back.
1702 FloatSignAsInt MagAsInt;
1703 getSignAsIntValue(MagAsInt, DL, Mag);
1704 assert(SignAsInt.SignMask == MagAsInt.SignMask);
1705 SDValue ClearSignMask = DAG.getConstant(~SignAsInt.SignMask, DL, IntVT);
1706 SDValue ClearedSign = DAG.getNode(ISD::AND, DL, IntVT, MagAsInt.IntValue,
1708 SDValue CopiedSign = DAG.getNode(ISD::OR, DL, IntVT, ClearedSign, SignBit);
1710 return modifySignAsInt(MagAsInt, DL, CopiedSign);
1713 SDValue SelectionDAGLegalize::ExpandFABS(SDNode *Node) const {
1715 SDValue Value = Node->getOperand(0);
1717 // Transform FABS(x) => FCOPYSIGN(x, 0.0) if FCOPYSIGN is legal.
1718 EVT FloatVT = Value.getValueType();
1719 if (TLI.isOperationLegalOrCustom(ISD::FCOPYSIGN, FloatVT)) {
1720 SDValue Zero = DAG.getConstantFP(0.0, DL, FloatVT);
1721 return DAG.getNode(ISD::FCOPYSIGN, DL, FloatVT, Value, Zero);
1724 // Transform value to integer, clear the sign bit and transform back.
1725 FloatSignAsInt ValueAsInt;
1726 getSignAsIntValue(ValueAsInt, DL, Value);
1727 EVT IntVT = ValueAsInt.IntValue.getValueType();
1728 SDValue ClearSignMask = DAG.getConstant(~ValueAsInt.SignMask, DL, IntVT);
1729 SDValue ClearedSign = DAG.getNode(ISD::AND, DL, IntVT, ValueAsInt.IntValue,
1731 return modifySignAsInt(ValueAsInt, DL, ClearedSign);
1734 void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node,
1735 SmallVectorImpl<SDValue> &Results) {
1736 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1737 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1738 " not tell us which reg is the stack pointer!");
1740 EVT VT = Node->getValueType(0);
1741 SDValue Tmp1 = SDValue(Node, 0);
1742 SDValue Tmp2 = SDValue(Node, 1);
1743 SDValue Tmp3 = Node->getOperand(2);
1744 SDValue Chain = Tmp1.getOperand(0);
1746 // Chain the dynamic stack allocation so that it doesn't modify the stack
1747 // pointer when other instructions are using the stack.
1748 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true), dl);
1750 SDValue Size = Tmp2.getOperand(1);
1751 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
1752 Chain = SP.getValue(1);
1753 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
1754 unsigned StackAlign =
1755 DAG.getSubtarget().getFrameLowering()->getStackAlignment();
1756 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
1757 if (Align > StackAlign)
1758 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
1759 DAG.getConstant(-(uint64_t)Align, dl, VT));
1760 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
1762 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
1763 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
1765 Results.push_back(Tmp1);
1766 Results.push_back(Tmp2);
1769 /// Legalize a SETCC with given LHS and RHS and condition code CC on the current
1772 /// If the SETCC has been legalized using AND / OR, then the legalized node
1773 /// will be stored in LHS. RHS and CC will be set to SDValue(). NeedInvert
1774 /// will be set to false.
1776 /// If the SETCC has been legalized by using getSetCCSwappedOperands(),
1777 /// then the values of LHS and RHS will be swapped, CC will be set to the
1778 /// new condition, and NeedInvert will be set to false.
1780 /// If the SETCC has been legalized using the inverse condcode, then LHS and
1781 /// RHS will be unchanged, CC will set to the inverted condcode, and NeedInvert
1782 /// will be set to true. The caller must invert the result of the SETCC with
1783 /// SelectionDAG::getLogicalNOT() or take equivalent action to swap the effect
1784 /// of a true/false result.
1786 /// \returns true if the SetCC has been legalized, false if it hasn't.
1787 bool SelectionDAGLegalize::LegalizeSetCCCondCode(EVT VT,
1788 SDValue &LHS, SDValue &RHS,
1792 MVT OpVT = LHS.getSimpleValueType();
1793 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
1795 switch (TLI.getCondCodeAction(CCCode, OpVT)) {
1796 default: llvm_unreachable("Unknown condition code action!");
1797 case TargetLowering::Legal:
1800 case TargetLowering::Expand: {
1801 ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode);
1802 if (TLI.isCondCodeLegal(InvCC, OpVT)) {
1803 std::swap(LHS, RHS);
1804 CC = DAG.getCondCode(InvCC);
1807 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
1810 default: llvm_unreachable("Don't know how to expand this condition!");
1812 assert(TLI.getCondCodeAction(ISD::SETOEQ, OpVT)
1813 == TargetLowering::Legal
1814 && "If SETO is expanded, SETOEQ must be legal!");
1815 CC1 = ISD::SETOEQ; CC2 = ISD::SETOEQ; Opc = ISD::AND; break;
1817 assert(TLI.getCondCodeAction(ISD::SETUNE, OpVT)
1818 == TargetLowering::Legal
1819 && "If SETUO is expanded, SETUNE must be legal!");
1820 CC1 = ISD::SETUNE; CC2 = ISD::SETUNE; Opc = ISD::OR; break;
1833 // If we are floating point, assign and break, otherwise fall through.
1834 if (!OpVT.isInteger()) {
1835 // We can use the 4th bit to tell if we are the unordered
1836 // or ordered version of the opcode.
1837 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
1838 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
1839 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
1842 // Fallthrough if we are unsigned integer.
1847 // We only support using the inverted operation, which is computed above
1848 // and not a different manner of supporting expanding these cases.
1849 llvm_unreachable("Don't know how to expand this condition!");
1852 // Try inverting the result of the inverse condition.
1853 InvCC = CCCode == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ;
1854 if (TLI.isCondCodeLegal(InvCC, OpVT)) {
1855 CC = DAG.getCondCode(InvCC);
1859 // If inverting the condition didn't work then we have no means to expand
1861 llvm_unreachable("Don't know how to expand this condition!");
1864 SDValue SetCC1, SetCC2;
1865 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
1866 // If we aren't the ordered or unorder operation,
1867 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
1868 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1);
1869 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2);
1871 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
1872 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1);
1873 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2);
1875 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
1884 /// Emit a store/load combination to the stack. This stores
1885 /// SrcOp to a stack slot of type SlotVT, truncating it if needed. It then does
1886 /// a load from the stack slot to DestVT, extending it if needed.
1887 /// The resultant code need not be legal.
1888 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp,
1892 // Create the stack frame object.
1893 unsigned SrcAlign = DAG.getDataLayout().getPrefTypeAlignment(
1894 SrcOp.getValueType().getTypeForEVT(*DAG.getContext()));
1895 SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign);
1897 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
1898 int SPFI = StackPtrFI->getIndex();
1899 MachinePointerInfo PtrInfo =
1900 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
1902 unsigned SrcSize = SrcOp.getValueType().getSizeInBits();
1903 unsigned SlotSize = SlotVT.getSizeInBits();
1904 unsigned DestSize = DestVT.getSizeInBits();
1905 Type *DestType = DestVT.getTypeForEVT(*DAG.getContext());
1906 unsigned DestAlign = DAG.getDataLayout().getPrefTypeAlignment(DestType);
1908 // Emit a store to the stack slot. Use a truncstore if the input value is
1909 // later than DestVT.
1912 if (SrcSize > SlotSize)
1913 Store = DAG.getTruncStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
1914 PtrInfo, SlotVT, false, false, SrcAlign);
1916 assert(SrcSize == SlotSize && "Invalid store");
1917 Store = DAG.getStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
1918 PtrInfo, false, false, SrcAlign);
1921 // Result is a load from the stack slot.
1922 if (SlotSize == DestSize)
1923 return DAG.getLoad(DestVT, dl, Store, FIPtr, PtrInfo,
1924 false, false, false, DestAlign);
1926 assert(SlotSize < DestSize && "Unknown extension!");
1927 return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr,
1928 PtrInfo, SlotVT, false, false, false, DestAlign);
1931 SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
1933 // Create a vector sized/aligned stack slot, store the value to element #0,
1934 // then load the whole vector back out.
1935 SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
1937 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
1938 int SPFI = StackPtrFI->getIndex();
1940 SDValue Ch = DAG.getTruncStore(
1941 DAG.getEntryNode(), dl, Node->getOperand(0), StackPtr,
1942 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI),
1943 Node->getValueType(0).getVectorElementType(), false, false, 0);
1945 Node->getValueType(0), dl, Ch, StackPtr,
1946 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI), false,
1951 ExpandBVWithShuffles(SDNode *Node, SelectionDAG &DAG,
1952 const TargetLowering &TLI, SDValue &Res) {
1953 unsigned NumElems = Node->getNumOperands();
1955 EVT VT = Node->getValueType(0);
1957 // Try to group the scalars into pairs, shuffle the pairs together, then
1958 // shuffle the pairs of pairs together, etc. until the vector has
1959 // been built. This will work only if all of the necessary shuffle masks
1962 // We do this in two phases; first to check the legality of the shuffles,
1963 // and next, assuming that all shuffles are legal, to create the new nodes.
1964 for (int Phase = 0; Phase < 2; ++Phase) {
1965 SmallVector<std::pair<SDValue, SmallVector<int, 16> >, 16> IntermedVals,
1967 for (unsigned i = 0; i < NumElems; ++i) {
1968 SDValue V = Node->getOperand(i);
1969 if (V.getOpcode() == ISD::UNDEF)
1974 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, V);
1975 IntermedVals.push_back(std::make_pair(Vec, SmallVector<int, 16>(1, i)));
1978 while (IntermedVals.size() > 2) {
1979 NewIntermedVals.clear();
1980 for (unsigned i = 0, e = (IntermedVals.size() & ~1u); i < e; i += 2) {
1981 // This vector and the next vector are shuffled together (simply to
1982 // append the one to the other).
1983 SmallVector<int, 16> ShuffleVec(NumElems, -1);
1985 SmallVector<int, 16> FinalIndices;
1986 FinalIndices.reserve(IntermedVals[i].second.size() +
1987 IntermedVals[i+1].second.size());
1990 for (unsigned j = 0, f = IntermedVals[i].second.size(); j != f;
1993 FinalIndices.push_back(IntermedVals[i].second[j]);
1995 for (unsigned j = 0, f = IntermedVals[i+1].second.size(); j != f;
1997 ShuffleVec[k] = NumElems + j;
1998 FinalIndices.push_back(IntermedVals[i+1].second[j]);
2003 Shuffle = DAG.getVectorShuffle(VT, dl, IntermedVals[i].first,
2004 IntermedVals[i+1].first,
2006 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
2008 NewIntermedVals.push_back(
2009 std::make_pair(Shuffle, std::move(FinalIndices)));
2012 // If we had an odd number of defined values, then append the last
2013 // element to the array of new vectors.
2014 if ((IntermedVals.size() & 1) != 0)
2015 NewIntermedVals.push_back(IntermedVals.back());
2017 IntermedVals.swap(NewIntermedVals);
2020 assert(IntermedVals.size() <= 2 && IntermedVals.size() > 0 &&
2021 "Invalid number of intermediate vectors");
2022 SDValue Vec1 = IntermedVals[0].first;
2024 if (IntermedVals.size() > 1)
2025 Vec2 = IntermedVals[1].first;
2027 Vec2 = DAG.getUNDEF(VT);
2029 SmallVector<int, 16> ShuffleVec(NumElems, -1);
2030 for (unsigned i = 0, e = IntermedVals[0].second.size(); i != e; ++i)
2031 ShuffleVec[IntermedVals[0].second[i]] = i;
2032 for (unsigned i = 0, e = IntermedVals[1].second.size(); i != e; ++i)
2033 ShuffleVec[IntermedVals[1].second[i]] = NumElems + i;
2036 Res = DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec.data());
2037 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
2044 /// Expand a BUILD_VECTOR node on targets that don't
2045 /// support the operation, but do support the resultant vector type.
2046 SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
2047 unsigned NumElems = Node->getNumOperands();
2048 SDValue Value1, Value2;
2050 EVT VT = Node->getValueType(0);
2051 EVT OpVT = Node->getOperand(0).getValueType();
2052 EVT EltVT = VT.getVectorElementType();
2054 // If the only non-undef value is the low element, turn this into a
2055 // SCALAR_TO_VECTOR node. If this is { X, X, X, X }, determine X.
2056 bool isOnlyLowElement = true;
2057 bool MoreThanTwoValues = false;
2058 bool isConstant = true;
2059 for (unsigned i = 0; i < NumElems; ++i) {
2060 SDValue V = Node->getOperand(i);
2061 if (V.getOpcode() == ISD::UNDEF)
2064 isOnlyLowElement = false;
2065 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
2068 if (!Value1.getNode()) {
2070 } else if (!Value2.getNode()) {
2073 } else if (V != Value1 && V != Value2) {
2074 MoreThanTwoValues = true;
2078 if (!Value1.getNode())
2079 return DAG.getUNDEF(VT);
2081 if (isOnlyLowElement)
2082 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
2084 // If all elements are constants, create a load from the constant pool.
2086 SmallVector<Constant*, 16> CV;
2087 for (unsigned i = 0, e = NumElems; i != e; ++i) {
2088 if (ConstantFPSDNode *V =
2089 dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
2090 CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
2091 } else if (ConstantSDNode *V =
2092 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
2094 CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
2096 // If OpVT and EltVT don't match, EltVT is not legal and the
2097 // element values have been promoted/truncated earlier. Undo this;
2098 // we don't want a v16i8 to become a v16i32 for example.
2099 const ConstantInt *CI = V->getConstantIntValue();
2100 CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()),
2101 CI->getZExtValue()));
2104 assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
2105 Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext());
2106 CV.push_back(UndefValue::get(OpNTy));
2109 Constant *CP = ConstantVector::get(CV);
2111 DAG.getConstantPool(CP, TLI.getPointerTy(DAG.getDataLayout()));
2112 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
2114 VT, dl, DAG.getEntryNode(), CPIdx,
2115 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2116 false, false, Alignment);
2119 SmallSet<SDValue, 16> DefinedValues;
2120 for (unsigned i = 0; i < NumElems; ++i) {
2121 if (Node->getOperand(i).getOpcode() == ISD::UNDEF)
2123 DefinedValues.insert(Node->getOperand(i));
2126 if (TLI.shouldExpandBuildVectorWithShuffles(VT, DefinedValues.size())) {
2127 if (!MoreThanTwoValues) {
2128 SmallVector<int, 8> ShuffleVec(NumElems, -1);
2129 for (unsigned i = 0; i < NumElems; ++i) {
2130 SDValue V = Node->getOperand(i);
2131 if (V.getOpcode() == ISD::UNDEF)
2133 ShuffleVec[i] = V == Value1 ? 0 : NumElems;
2135 if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) {
2136 // Get the splatted value into the low element of a vector register.
2137 SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1);
2139 if (Value2.getNode())
2140 Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2);
2142 Vec2 = DAG.getUNDEF(VT);
2144 // Return shuffle(LowValVec, undef, <0,0,0,0>)
2145 return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec.data());
2149 if (ExpandBVWithShuffles(Node, DAG, TLI, Res))
2154 // Otherwise, we can't handle this case efficiently.
2155 return ExpandVectorBuildThroughStack(Node);
2158 // Expand a node into a call to a libcall. If the result value
2159 // does not fit into a register, return the lo part and set the hi part to the
2160 // by-reg argument. If it does fit into a single register, return the result
2161 // and leave the Hi part unset.
2162 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
2164 TargetLowering::ArgListTy Args;
2165 TargetLowering::ArgListEntry Entry;
2166 for (const SDValue &Op : Node->op_values()) {
2167 EVT ArgVT = Op.getValueType();
2168 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2171 Entry.isSExt = isSigned;
2172 Entry.isZExt = !isSigned;
2173 Args.push_back(Entry);
2175 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2176 TLI.getPointerTy(DAG.getDataLayout()));
2178 Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
2180 // By default, the input chain to this libcall is the entry node of the
2181 // function. If the libcall is going to be emitted as a tail call then
2182 // TLI.isUsedByReturnOnly will change it to the right chain if the return
2183 // node which is being folded has a non-entry input chain.
2184 SDValue InChain = DAG.getEntryNode();
2186 // isTailCall may be true since the callee does not reference caller stack
2187 // frame. Check if it's in the right position.
2188 SDValue TCChain = InChain;
2189 bool isTailCall = TLI.isInTailCallPosition(DAG, Node, TCChain);
2193 TargetLowering::CallLoweringInfo CLI(DAG);
2194 CLI.setDebugLoc(SDLoc(Node)).setChain(InChain)
2195 .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
2196 .setTailCall(isTailCall).setSExtResult(isSigned).setZExtResult(!isSigned);
2198 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2200 if (!CallInfo.second.getNode())
2201 // It's a tailcall, return the chain (which is the DAG root).
2202 return DAG.getRoot();
2204 return CallInfo.first;
2207 /// Generate a libcall taking the given operands as arguments
2208 /// and returning a result of type RetVT.
2209 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, EVT RetVT,
2210 const SDValue *Ops, unsigned NumOps,
2211 bool isSigned, SDLoc dl) {
2212 TargetLowering::ArgListTy Args;
2213 Args.reserve(NumOps);
2215 TargetLowering::ArgListEntry Entry;
2216 for (unsigned i = 0; i != NumOps; ++i) {
2217 Entry.Node = Ops[i];
2218 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
2219 Entry.isSExt = isSigned;
2220 Entry.isZExt = !isSigned;
2221 Args.push_back(Entry);
2223 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2224 TLI.getPointerTy(DAG.getDataLayout()));
2226 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2228 TargetLowering::CallLoweringInfo CLI(DAG);
2229 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
2230 .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
2231 .setSExtResult(isSigned).setZExtResult(!isSigned);
2233 std::pair<SDValue,SDValue> CallInfo = TLI.LowerCallTo(CLI);
2235 return CallInfo.first;
2238 // Expand a node into a call to a libcall. Similar to
2239 // ExpandLibCall except that the first operand is the in-chain.
2240 std::pair<SDValue, SDValue>
2241 SelectionDAGLegalize::ExpandChainLibCall(RTLIB::Libcall LC,
2244 SDValue InChain = Node->getOperand(0);
2246 TargetLowering::ArgListTy Args;
2247 TargetLowering::ArgListEntry Entry;
2248 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) {
2249 EVT ArgVT = Node->getOperand(i).getValueType();
2250 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2251 Entry.Node = Node->getOperand(i);
2253 Entry.isSExt = isSigned;
2254 Entry.isZExt = !isSigned;
2255 Args.push_back(Entry);
2257 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2258 TLI.getPointerTy(DAG.getDataLayout()));
2260 Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
2262 TargetLowering::CallLoweringInfo CLI(DAG);
2263 CLI.setDebugLoc(SDLoc(Node)).setChain(InChain)
2264 .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
2265 .setSExtResult(isSigned).setZExtResult(!isSigned);
2267 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2272 SDValue SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
2273 RTLIB::Libcall Call_F32,
2274 RTLIB::Libcall Call_F64,
2275 RTLIB::Libcall Call_F80,
2276 RTLIB::Libcall Call_F128,
2277 RTLIB::Libcall Call_PPCF128) {
2279 switch (Node->getSimpleValueType(0).SimpleTy) {
2280 default: llvm_unreachable("Unexpected request for libcall!");
2281 case MVT::f32: LC = Call_F32; break;
2282 case MVT::f64: LC = Call_F64; break;
2283 case MVT::f80: LC = Call_F80; break;
2284 case MVT::f128: LC = Call_F128; break;
2285 case MVT::ppcf128: LC = Call_PPCF128; break;
2287 return ExpandLibCall(LC, Node, false);
2290 SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned,
2291 RTLIB::Libcall Call_I8,
2292 RTLIB::Libcall Call_I16,
2293 RTLIB::Libcall Call_I32,
2294 RTLIB::Libcall Call_I64,
2295 RTLIB::Libcall Call_I128) {
2297 switch (Node->getSimpleValueType(0).SimpleTy) {
2298 default: llvm_unreachable("Unexpected request for libcall!");
2299 case MVT::i8: LC = Call_I8; break;
2300 case MVT::i16: LC = Call_I16; break;
2301 case MVT::i32: LC = Call_I32; break;
2302 case MVT::i64: LC = Call_I64; break;
2303 case MVT::i128: LC = Call_I128; break;
2305 return ExpandLibCall(LC, Node, isSigned);
2308 /// Issue libcalls to __{u}divmod to compute div / rem pairs.
2310 SelectionDAGLegalize::ExpandDivRemLibCall(SDNode *Node,
2311 SmallVectorImpl<SDValue> &Results) {
2312 unsigned Opcode = Node->getOpcode();
2313 bool isSigned = Opcode == ISD::SDIVREM;
2316 switch (Node->getSimpleValueType(0).SimpleTy) {
2317 default: llvm_unreachable("Unexpected request for libcall!");
2318 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2319 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2320 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2321 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2322 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2325 // The input chain to this libcall is the entry node of the function.
2326 // Legalizing the call will automatically add the previous call to the
2328 SDValue InChain = DAG.getEntryNode();
2330 EVT RetVT = Node->getValueType(0);
2331 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2333 TargetLowering::ArgListTy Args;
2334 TargetLowering::ArgListEntry Entry;
2335 for (const SDValue &Op : Node->op_values()) {
2336 EVT ArgVT = Op.getValueType();
2337 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2340 Entry.isSExt = isSigned;
2341 Entry.isZExt = !isSigned;
2342 Args.push_back(Entry);
2345 // Also pass the return address of the remainder.
2346 SDValue FIPtr = DAG.CreateStackTemporary(RetVT);
2348 Entry.Ty = RetTy->getPointerTo();
2349 Entry.isSExt = isSigned;
2350 Entry.isZExt = !isSigned;
2351 Args.push_back(Entry);
2353 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2354 TLI.getPointerTy(DAG.getDataLayout()));
2357 TargetLowering::CallLoweringInfo CLI(DAG);
2358 CLI.setDebugLoc(dl).setChain(InChain)
2359 .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
2360 .setSExtResult(isSigned).setZExtResult(!isSigned);
2362 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2364 // Remainder is loaded back from the stack frame.
2365 SDValue Rem = DAG.getLoad(RetVT, dl, CallInfo.second, FIPtr,
2366 MachinePointerInfo(), false, false, false, 0);
2367 Results.push_back(CallInfo.first);
2368 Results.push_back(Rem);
2371 /// Return true if sincos libcall is available.
2372 static bool isSinCosLibcallAvailable(SDNode *Node, const TargetLowering &TLI) {
2374 switch (Node->getSimpleValueType(0).SimpleTy) {
2375 default: llvm_unreachable("Unexpected request for libcall!");
2376 case MVT::f32: LC = RTLIB::SINCOS_F32; break;
2377 case MVT::f64: LC = RTLIB::SINCOS_F64; break;
2378 case MVT::f80: LC = RTLIB::SINCOS_F80; break;
2379 case MVT::f128: LC = RTLIB::SINCOS_F128; break;
2380 case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break;
2382 return TLI.getLibcallName(LC) != nullptr;
2385 /// Return true if sincos libcall is available and can be used to combine sin
2387 static bool canCombineSinCosLibcall(SDNode *Node, const TargetLowering &TLI,
2388 const TargetMachine &TM) {
2389 if (!isSinCosLibcallAvailable(Node, TLI))
2391 // GNU sin/cos functions set errno while sincos does not. Therefore
2392 // combining sin and cos is only safe if unsafe-fpmath is enabled.
2393 bool isGNU = Triple(TM.getTargetTriple()).getEnvironment() == Triple::GNU;
2394 if (isGNU && !TM.Options.UnsafeFPMath)
2399 /// Only issue sincos libcall if both sin and cos are needed.
2400 static bool useSinCos(SDNode *Node) {
2401 unsigned OtherOpcode = Node->getOpcode() == ISD::FSIN
2402 ? ISD::FCOS : ISD::FSIN;
2404 SDValue Op0 = Node->getOperand(0);
2405 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2406 UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2410 // The other user might have been turned into sincos already.
2411 if (User->getOpcode() == OtherOpcode || User->getOpcode() == ISD::FSINCOS)
2417 /// Issue libcalls to sincos to compute sin / cos pairs.
2419 SelectionDAGLegalize::ExpandSinCosLibCall(SDNode *Node,
2420 SmallVectorImpl<SDValue> &Results) {
2422 switch (Node->getSimpleValueType(0).SimpleTy) {
2423 default: llvm_unreachable("Unexpected request for libcall!");
2424 case MVT::f32: LC = RTLIB::SINCOS_F32; break;
2425 case MVT::f64: LC = RTLIB::SINCOS_F64; break;
2426 case MVT::f80: LC = RTLIB::SINCOS_F80; break;
2427 case MVT::f128: LC = RTLIB::SINCOS_F128; break;
2428 case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break;
2431 // The input chain to this libcall is the entry node of the function.
2432 // Legalizing the call will automatically add the previous call to the
2434 SDValue InChain = DAG.getEntryNode();
2436 EVT RetVT = Node->getValueType(0);
2437 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2439 TargetLowering::ArgListTy Args;
2440 TargetLowering::ArgListEntry Entry;
2442 // Pass the argument.
2443 Entry.Node = Node->getOperand(0);
2445 Entry.isSExt = false;
2446 Entry.isZExt = false;
2447 Args.push_back(Entry);
2449 // Pass the return address of sin.
2450 SDValue SinPtr = DAG.CreateStackTemporary(RetVT);
2451 Entry.Node = SinPtr;
2452 Entry.Ty = RetTy->getPointerTo();
2453 Entry.isSExt = false;
2454 Entry.isZExt = false;
2455 Args.push_back(Entry);
2457 // Also pass the return address of the cos.
2458 SDValue CosPtr = DAG.CreateStackTemporary(RetVT);
2459 Entry.Node = CosPtr;
2460 Entry.Ty = RetTy->getPointerTo();
2461 Entry.isSExt = false;
2462 Entry.isZExt = false;
2463 Args.push_back(Entry);
2465 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2466 TLI.getPointerTy(DAG.getDataLayout()));
2469 TargetLowering::CallLoweringInfo CLI(DAG);
2470 CLI.setDebugLoc(dl).setChain(InChain)
2471 .setCallee(TLI.getLibcallCallingConv(LC),
2472 Type::getVoidTy(*DAG.getContext()), Callee, std::move(Args), 0);
2474 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2476 Results.push_back(DAG.getLoad(RetVT, dl, CallInfo.second, SinPtr,
2477 MachinePointerInfo(), false, false, false, 0));
2478 Results.push_back(DAG.getLoad(RetVT, dl, CallInfo.second, CosPtr,
2479 MachinePointerInfo(), false, false, false, 0));
2482 /// This function is responsible for legalizing a
2483 /// INT_TO_FP operation of the specified operand when the target requests that
2484 /// we expand it. At this point, we know that the result and operand types are
2485 /// legal for the target.
2486 SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
2490 // TODO: Should any fast-math-flags be set for the created nodes?
2492 if (Op0.getValueType() == MVT::i32 && TLI.isTypeLegal(MVT::f64)) {
2493 // simple 32-bit [signed|unsigned] integer to float/double expansion
2495 // Get the stack frame index of a 8 byte buffer.
2496 SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
2498 // word offset constant for Hi/Lo address computation
2499 SDValue WordOff = DAG.getConstant(sizeof(int), dl,
2500 StackSlot.getValueType());
2501 // set up Hi and Lo (into buffer) address based on endian
2502 SDValue Hi = StackSlot;
2503 SDValue Lo = DAG.getNode(ISD::ADD, dl, StackSlot.getValueType(),
2504 StackSlot, WordOff);
2505 if (DAG.getDataLayout().isLittleEndian())
2508 // if signed map to unsigned space
2511 // constant used to invert sign bit (signed to unsigned mapping)
2512 SDValue SignBit = DAG.getConstant(0x80000000u, dl, MVT::i32);
2513 Op0Mapped = DAG.getNode(ISD::XOR, dl, MVT::i32, Op0, SignBit);
2517 // store the lo of the constructed double - based on integer input
2518 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl,
2519 Op0Mapped, Lo, MachinePointerInfo(),
2521 // initial hi portion of constructed double
2522 SDValue InitialHi = DAG.getConstant(0x43300000u, dl, MVT::i32);
2523 // store the hi of the constructed double - biased exponent
2524 SDValue Store2 = DAG.getStore(Store1, dl, InitialHi, Hi,
2525 MachinePointerInfo(),
2527 // load the constructed double
2528 SDValue Load = DAG.getLoad(MVT::f64, dl, Store2, StackSlot,
2529 MachinePointerInfo(), false, false, false, 0);
2530 // FP constant to bias correct the final result
2531 SDValue Bias = DAG.getConstantFP(isSigned ?
2532 BitsToDouble(0x4330000080000000ULL) :
2533 BitsToDouble(0x4330000000000000ULL),
2535 // subtract the bias
2536 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
2539 // handle final rounding
2540 if (DestVT == MVT::f64) {
2543 } else if (DestVT.bitsLT(MVT::f64)) {
2544 Result = DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
2545 DAG.getIntPtrConstant(0, dl));
2546 } else if (DestVT.bitsGT(MVT::f64)) {
2547 Result = DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
2551 assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
2552 // Code below here assumes !isSigned without checking again.
2554 // Implementation of unsigned i64 to f64 following the algorithm in
2555 // __floatundidf in compiler_rt. This implementation has the advantage
2556 // of performing rounding correctly, both in the default rounding mode
2557 // and in all alternate rounding modes.
2558 // TODO: Generalize this for use with other types.
2559 if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f64) {
2561 DAG.getConstant(UINT64_C(0x4330000000000000), dl, MVT::i64);
2562 SDValue TwoP84PlusTwoP52 =
2563 DAG.getConstantFP(BitsToDouble(UINT64_C(0x4530000000100000)), dl,
2566 DAG.getConstant(UINT64_C(0x4530000000000000), dl, MVT::i64);
2568 SDValue Lo = DAG.getZeroExtendInReg(Op0, dl, MVT::i32);
2569 SDValue Hi = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0,
2570 DAG.getConstant(32, dl, MVT::i64));
2571 SDValue LoOr = DAG.getNode(ISD::OR, dl, MVT::i64, Lo, TwoP52);
2572 SDValue HiOr = DAG.getNode(ISD::OR, dl, MVT::i64, Hi, TwoP84);
2573 SDValue LoFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, LoOr);
2574 SDValue HiFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, HiOr);
2575 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, MVT::f64, HiFlt,
2577 return DAG.getNode(ISD::FADD, dl, MVT::f64, LoFlt, HiSub);
2580 // Implementation of unsigned i64 to f32.
2581 // TODO: Generalize this for use with other types.
2582 if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f32) {
2583 // For unsigned conversions, convert them to signed conversions using the
2584 // algorithm from the x86_64 __floatundidf in compiler_rt.
2586 SDValue Fast = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Op0);
2588 SDValue ShiftConst = DAG.getConstant(
2589 1, dl, TLI.getShiftAmountTy(Op0.getValueType(), DAG.getDataLayout()));
2590 SDValue Shr = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0, ShiftConst);
2591 SDValue AndConst = DAG.getConstant(1, dl, MVT::i64);
2592 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0, AndConst);
2593 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And, Shr);
2595 SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Or);
2596 SDValue Slow = DAG.getNode(ISD::FADD, dl, MVT::f32, SignCvt, SignCvt);
2598 // TODO: This really should be implemented using a branch rather than a
2599 // select. We happen to get lucky and machinesink does the right
2600 // thing most of the time. This would be a good candidate for a
2601 //pseudo-op, or, even better, for whole-function isel.
2602 SDValue SignBitTest = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
2603 Op0, DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
2604 return DAG.getSelect(dl, MVT::f32, SignBitTest, Slow, Fast);
2607 // Otherwise, implement the fully general conversion.
2609 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
2610 DAG.getConstant(UINT64_C(0xfffffffffffff800), dl, MVT::i64));
2611 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And,
2612 DAG.getConstant(UINT64_C(0x800), dl, MVT::i64));
2613 SDValue And2 = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
2614 DAG.getConstant(UINT64_C(0x7ff), dl, MVT::i64));
2615 SDValue Ne = DAG.getSetCC(dl, getSetCCResultType(MVT::i64), And2,
2616 DAG.getConstant(UINT64_C(0), dl, MVT::i64),
2618 SDValue Sel = DAG.getSelect(dl, MVT::i64, Ne, Or, Op0);
2619 SDValue Ge = DAG.getSetCC(dl, getSetCCResultType(MVT::i64), Op0,
2620 DAG.getConstant(UINT64_C(0x0020000000000000), dl,
2623 SDValue Sel2 = DAG.getSelect(dl, MVT::i64, Ge, Sel, Op0);
2624 EVT SHVT = TLI.getShiftAmountTy(Sel2.getValueType(), DAG.getDataLayout());
2626 SDValue Sh = DAG.getNode(ISD::SRL, dl, MVT::i64, Sel2,
2627 DAG.getConstant(32, dl, SHVT));
2628 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sh);
2629 SDValue Fcvt = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Trunc);
2631 DAG.getConstantFP(BitsToDouble(UINT64_C(0x41f0000000000000)), dl,
2633 SDValue Fmul = DAG.getNode(ISD::FMUL, dl, MVT::f64, TwoP32, Fcvt);
2634 SDValue Lo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sel2);
2635 SDValue Fcvt2 = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Lo);
2636 SDValue Fadd = DAG.getNode(ISD::FADD, dl, MVT::f64, Fmul, Fcvt2);
2637 return DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Fadd,
2638 DAG.getIntPtrConstant(0, dl));
2641 SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2643 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(Op0.getValueType()),
2645 DAG.getConstant(0, dl, Op0.getValueType()),
2647 SDValue Zero = DAG.getIntPtrConstant(0, dl),
2648 Four = DAG.getIntPtrConstant(4, dl);
2649 SDValue CstOffset = DAG.getSelect(dl, Zero.getValueType(),
2650 SignSet, Four, Zero);
2652 // If the sign bit of the integer is set, the large number will be treated
2653 // as a negative number. To counteract this, the dynamic code adds an
2654 // offset depending on the data type.
2656 switch (Op0.getSimpleValueType().SimpleTy) {
2657 default: llvm_unreachable("Unsupported integer type!");
2658 case MVT::i8 : FF = 0x43800000ULL; break; // 2^8 (as a float)
2659 case MVT::i16: FF = 0x47800000ULL; break; // 2^16 (as a float)
2660 case MVT::i32: FF = 0x4F800000ULL; break; // 2^32 (as a float)
2661 case MVT::i64: FF = 0x5F800000ULL; break; // 2^64 (as a float)
2663 if (DAG.getDataLayout().isLittleEndian())
2665 Constant *FudgeFactor = ConstantInt::get(
2666 Type::getInt64Ty(*DAG.getContext()), FF);
2669 DAG.getConstantPool(FudgeFactor, TLI.getPointerTy(DAG.getDataLayout()));
2670 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
2671 CPIdx = DAG.getNode(ISD::ADD, dl, CPIdx.getValueType(), CPIdx, CstOffset);
2672 Alignment = std::min(Alignment, 4u);
2674 if (DestVT == MVT::f32)
2675 FudgeInReg = DAG.getLoad(
2676 MVT::f32, dl, DAG.getEntryNode(), CPIdx,
2677 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2678 false, false, Alignment);
2680 SDValue Load = DAG.getExtLoad(
2681 ISD::EXTLOAD, dl, DestVT, DAG.getEntryNode(), CPIdx,
2682 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
2683 false, false, false, Alignment);
2684 HandleSDNode Handle(Load);
2685 LegalizeOp(Load.getNode());
2686 FudgeInReg = Handle.getValue();
2689 return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
2692 /// This function is responsible for legalizing a
2693 /// *INT_TO_FP operation of the specified operand when the target requests that
2694 /// we promote it. At this point, we know that the result and operand types are
2695 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
2696 /// operation that takes a larger input.
2697 SDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp,
2701 // First step, figure out the appropriate *INT_TO_FP operation to use.
2702 EVT NewInTy = LegalOp.getValueType();
2704 unsigned OpToUse = 0;
2706 // Scan for the appropriate larger type to use.
2708 NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1);
2709 assert(NewInTy.isInteger() && "Ran out of possibilities!");
2711 // If the target supports SINT_TO_FP of this type, use it.
2712 if (TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, NewInTy)) {
2713 OpToUse = ISD::SINT_TO_FP;
2716 if (isSigned) continue;
2718 // If the target supports UINT_TO_FP of this type, use it.
2719 if (TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, NewInTy)) {
2720 OpToUse = ISD::UINT_TO_FP;
2724 // Otherwise, try a larger type.
2727 // Okay, we found the operation and type to use. Zero extend our input to the
2728 // desired type then run the operation on it.
2729 return DAG.getNode(OpToUse, dl, DestVT,
2730 DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
2731 dl, NewInTy, LegalOp));
2734 /// This function is responsible for legalizing a
2735 /// FP_TO_*INT operation of the specified operand when the target requests that
2736 /// we promote it. At this point, we know that the result and operand types are
2737 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
2738 /// operation that returns a larger result.
2739 SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp,
2743 // First step, figure out the appropriate FP_TO*INT operation to use.
2744 EVT NewOutTy = DestVT;
2746 unsigned OpToUse = 0;
2748 // Scan for the appropriate larger type to use.
2750 NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1);
2751 assert(NewOutTy.isInteger() && "Ran out of possibilities!");
2753 // A larger signed type can hold all unsigned values of the requested type,
2754 // so using FP_TO_SINT is valid
2755 if (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NewOutTy)) {
2756 OpToUse = ISD::FP_TO_SINT;
2760 // However, if the value may be < 0.0, we *must* use some FP_TO_SINT.
2761 if (!isSigned && TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NewOutTy)) {
2762 OpToUse = ISD::FP_TO_UINT;
2766 // Otherwise, try a larger type.
2770 // Okay, we found the operation and type to use.
2771 SDValue Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
2773 // Truncate the result of the extended FP_TO_*INT operation to the desired
2775 return DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
2778 /// Open code the operations for BSWAP of the specified operation.
2779 SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op, SDLoc dl) {
2780 EVT VT = Op.getValueType();
2781 EVT SHVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
2782 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
2783 switch (VT.getSimpleVT().SimpleTy) {
2784 default: llvm_unreachable("Unhandled Expand type in BSWAP!");
2786 Tmp2 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2787 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2788 return DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
2790 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
2791 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2792 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2793 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
2794 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
2795 DAG.getConstant(0xFF0000, dl, VT));
2796 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
2797 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2798 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2799 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2801 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
2802 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
2803 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
2804 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2805 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2806 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
2807 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
2808 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
2809 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7,
2810 DAG.getConstant(255ULL<<48, dl, VT));
2811 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6,
2812 DAG.getConstant(255ULL<<40, dl, VT));
2813 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5,
2814 DAG.getConstant(255ULL<<32, dl, VT));
2815 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
2816 DAG.getConstant(255ULL<<24, dl, VT));
2817 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
2818 DAG.getConstant(255ULL<<16, dl, VT));
2819 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
2820 DAG.getConstant(255ULL<<8 , dl, VT));
2821 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
2822 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
2823 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2824 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2825 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
2826 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2827 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
2831 /// Expand the specified bitcount instruction into operations.
2832 SDValue SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDValue Op,
2835 default: llvm_unreachable("Cannot expand this yet!");
2837 EVT VT = Op.getValueType();
2838 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
2839 unsigned Len = VT.getSizeInBits();
2841 assert(VT.isInteger() && Len <= 128 && Len % 8 == 0 &&
2842 "CTPOP not implemented for this type.");
2844 // This is the "best" algorithm from
2845 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
2847 SDValue Mask55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)),
2849 SDValue Mask33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)),
2851 SDValue Mask0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)),
2853 SDValue Mask01 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)),
2856 // v = v - ((v >> 1) & 0x55555555...)
2857 Op = DAG.getNode(ISD::SUB, dl, VT, Op,
2858 DAG.getNode(ISD::AND, dl, VT,
2859 DAG.getNode(ISD::SRL, dl, VT, Op,
2860 DAG.getConstant(1, dl, ShVT)),
2862 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
2863 Op = DAG.getNode(ISD::ADD, dl, VT,
2864 DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
2865 DAG.getNode(ISD::AND, dl, VT,
2866 DAG.getNode(ISD::SRL, dl, VT, Op,
2867 DAG.getConstant(2, dl, ShVT)),
2869 // v = (v + (v >> 4)) & 0x0F0F0F0F...
2870 Op = DAG.getNode(ISD::AND, dl, VT,
2871 DAG.getNode(ISD::ADD, dl, VT, Op,
2872 DAG.getNode(ISD::SRL, dl, VT, Op,
2873 DAG.getConstant(4, dl, ShVT))),
2875 // v = (v * 0x01010101...) >> (Len - 8)
2876 Op = DAG.getNode(ISD::SRL, dl, VT,
2877 DAG.getNode(ISD::MUL, dl, VT, Op, Mask01),
2878 DAG.getConstant(Len - 8, dl, ShVT));
2882 case ISD::CTLZ_ZERO_UNDEF:
2883 // This trivially expands to CTLZ.
2884 return DAG.getNode(ISD::CTLZ, dl, Op.getValueType(), Op);
2886 // for now, we do this:
2887 // x = x | (x >> 1);
2888 // x = x | (x >> 2);
2890 // x = x | (x >>16);
2891 // x = x | (x >>32); // for 64-bit input
2892 // return popcount(~x);
2894 // Ref: "Hacker's Delight" by Henry Warren
2895 EVT VT = Op.getValueType();
2896 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
2897 unsigned len = VT.getSizeInBits();
2898 for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
2899 SDValue Tmp3 = DAG.getConstant(1ULL << i, dl, ShVT);
2900 Op = DAG.getNode(ISD::OR, dl, VT, Op,
2901 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3));
2903 Op = DAG.getNOT(dl, Op, VT);
2904 return DAG.getNode(ISD::CTPOP, dl, VT, Op);
2906 case ISD::CTTZ_ZERO_UNDEF:
2907 // This trivially expands to CTTZ.
2908 return DAG.getNode(ISD::CTTZ, dl, Op.getValueType(), Op);
2910 // for now, we use: { return popcount(~x & (x - 1)); }
2911 // unless the target has ctlz but not ctpop, in which case we use:
2912 // { return 32 - nlz(~x & (x-1)); }
2913 // Ref: "Hacker's Delight" by Henry Warren
2914 EVT VT = Op.getValueType();
2915 SDValue Tmp3 = DAG.getNode(ISD::AND, dl, VT,
2916 DAG.getNOT(dl, Op, VT),
2917 DAG.getNode(ISD::SUB, dl, VT, Op,
2918 DAG.getConstant(1, dl, VT)));
2919 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
2920 if (!TLI.isOperationLegalOrCustom(ISD::CTPOP, VT) &&
2921 TLI.isOperationLegalOrCustom(ISD::CTLZ, VT))
2922 return DAG.getNode(ISD::SUB, dl, VT,
2923 DAG.getConstant(VT.getSizeInBits(), dl, VT),
2924 DAG.getNode(ISD::CTLZ, dl, VT, Tmp3));
2925 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp3);
2930 bool SelectionDAGLegalize::ExpandNode(SDNode *Node) {
2931 SmallVector<SDValue, 8> Results;
2933 SDValue Tmp1, Tmp2, Tmp3, Tmp4;
2935 switch (Node->getOpcode()) {
2938 case ISD::CTLZ_ZERO_UNDEF:
2940 case ISD::CTTZ_ZERO_UNDEF:
2941 Tmp1 = ExpandBitCount(Node->getOpcode(), Node->getOperand(0), dl);
2942 Results.push_back(Tmp1);
2945 Results.push_back(ExpandBSWAP(Node->getOperand(0), dl));
2947 case ISD::FRAMEADDR:
2948 case ISD::RETURNADDR:
2949 case ISD::FRAME_TO_ARGS_OFFSET:
2950 Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0)));
2952 case ISD::FLT_ROUNDS_:
2953 Results.push_back(DAG.getConstant(1, dl, Node->getValueType(0)));
2955 case ISD::EH_RETURN:
2959 case ISD::EH_SJLJ_LONGJMP:
2960 // If the target didn't expand these, there's nothing to do, so just
2961 // preserve the chain and be done.
2962 Results.push_back(Node->getOperand(0));
2964 case ISD::READCYCLECOUNTER:
2965 // If the target didn't expand this, just return 'zero' and preserve the
2967 Results.append(Node->getNumValues() - 1,
2968 DAG.getConstant(0, dl, Node->getValueType(0)));
2969 Results.push_back(Node->getOperand(0));
2971 case ISD::EH_SJLJ_SETJMP:
2972 // If the target didn't expand this, just return 'zero' and preserve the
2974 Results.push_back(DAG.getConstant(0, dl, MVT::i32));
2975 Results.push_back(Node->getOperand(0));
2977 case ISD::ATOMIC_LOAD: {
2978 // There is no libcall for atomic load; fake it with ATOMIC_CMP_SWAP.
2979 SDValue Zero = DAG.getConstant(0, dl, Node->getValueType(0));
2980 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
2981 SDValue Swap = DAG.getAtomicCmpSwap(
2982 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
2983 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
2984 cast<AtomicSDNode>(Node)->getMemOperand(),
2985 cast<AtomicSDNode>(Node)->getOrdering(),
2986 cast<AtomicSDNode>(Node)->getOrdering(),
2987 cast<AtomicSDNode>(Node)->getSynchScope());
2988 Results.push_back(Swap.getValue(0));
2989 Results.push_back(Swap.getValue(1));
2992 case ISD::ATOMIC_STORE: {
2993 // There is no libcall for atomic store; fake it with ATOMIC_SWAP.
2994 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
2995 cast<AtomicSDNode>(Node)->getMemoryVT(),
2996 Node->getOperand(0),
2997 Node->getOperand(1), Node->getOperand(2),
2998 cast<AtomicSDNode>(Node)->getMemOperand(),
2999 cast<AtomicSDNode>(Node)->getOrdering(),
3000 cast<AtomicSDNode>(Node)->getSynchScope());
3001 Results.push_back(Swap.getValue(1));
3004 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
3005 // Expanding an ATOMIC_CMP_SWAP_WITH_SUCCESS produces an ATOMIC_CMP_SWAP and
3006 // splits out the success value as a comparison. Expanding the resulting
3007 // ATOMIC_CMP_SWAP will produce a libcall.
3008 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
3009 SDValue Res = DAG.getAtomicCmpSwap(
3010 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
3011 Node->getOperand(0), Node->getOperand(1), Node->getOperand(2),
3012 Node->getOperand(3), cast<MemSDNode>(Node)->getMemOperand(),
3013 cast<AtomicSDNode>(Node)->getSuccessOrdering(),
3014 cast<AtomicSDNode>(Node)->getFailureOrdering(),
3015 cast<AtomicSDNode>(Node)->getSynchScope());
3017 SDValue Success = DAG.getSetCC(SDLoc(Node), Node->getValueType(1),
3018 Res, Node->getOperand(2), ISD::SETEQ);
3020 Results.push_back(Res.getValue(0));
3021 Results.push_back(Success);
3022 Results.push_back(Res.getValue(1));
3025 case ISD::DYNAMIC_STACKALLOC:
3026 ExpandDYNAMIC_STACKALLOC(Node, Results);
3028 case ISD::MERGE_VALUES:
3029 for (unsigned i = 0; i < Node->getNumValues(); i++)
3030 Results.push_back(Node->getOperand(i));
3033 EVT VT = Node->getValueType(0);
3035 Results.push_back(DAG.getConstant(0, dl, VT));
3037 assert(VT.isFloatingPoint() && "Unknown value type!");
3038 Results.push_back(DAG.getConstantFP(0, dl, VT));
3044 Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
3045 Node->getValueType(0), dl);
3046 Results.push_back(Tmp1);
3048 case ISD::FP_EXTEND:
3049 Tmp1 = EmitStackConvert(Node->getOperand(0),
3050 Node->getOperand(0).getValueType(),
3051 Node->getValueType(0), dl);
3052 Results.push_back(Tmp1);
3054 case ISD::SIGN_EXTEND_INREG: {
3055 // NOTE: we could fall back on load/store here too for targets without
3056 // SAR. However, it is doubtful that any exist.
3057 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
3058 EVT VT = Node->getValueType(0);
3059 EVT ShiftAmountTy = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
3062 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
3063 ExtraVT.getScalarType().getSizeInBits();
3064 SDValue ShiftCst = DAG.getConstant(BitsDiff, dl, ShiftAmountTy);
3065 Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0),
3066 Node->getOperand(0), ShiftCst);
3067 Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst);
3068 Results.push_back(Tmp1);
3071 case ISD::FP_ROUND_INREG: {
3072 // The only way we can lower this is to turn it into a TRUNCSTORE,
3073 // EXTLOAD pair, targeting a temporary location (a stack slot).
3075 // NOTE: there is a choice here between constantly creating new stack
3076 // slots and always reusing the same one. We currently always create
3077 // new ones, as reuse may inhibit scheduling.
3078 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
3079 Tmp1 = EmitStackConvert(Node->getOperand(0), ExtraVT,
3080 Node->getValueType(0), dl);
3081 Results.push_back(Tmp1);
3084 case ISD::SINT_TO_FP:
3085 case ISD::UINT_TO_FP:
3086 Tmp1 = ExpandLegalINT_TO_FP(Node->getOpcode() == ISD::SINT_TO_FP,
3087 Node->getOperand(0), Node->getValueType(0), dl);
3088 Results.push_back(Tmp1);
3090 case ISD::FP_TO_SINT:
3091 if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG))
3092 Results.push_back(Tmp1);
3094 case ISD::FP_TO_UINT: {
3095 SDValue True, False;
3096 EVT VT = Node->getOperand(0).getValueType();
3097 EVT NVT = Node->getValueType(0);
3098 APFloat apf(DAG.EVTToAPFloatSemantics(VT),
3099 APInt::getNullValue(VT.getSizeInBits()));
3100 APInt x = APInt::getSignBit(NVT.getSizeInBits());
3101 (void)apf.convertFromAPInt(x, false, APFloat::rmNearestTiesToEven);
3102 Tmp1 = DAG.getConstantFP(apf, dl, VT);
3103 Tmp2 = DAG.getSetCC(dl, getSetCCResultType(VT),
3104 Node->getOperand(0),
3106 True = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, Node->getOperand(0));
3107 // TODO: Should any fast-math-flags be set for the FSUB?
3108 False = DAG.getNode(ISD::FP_TO_SINT, dl, NVT,
3109 DAG.getNode(ISD::FSUB, dl, VT,
3110 Node->getOperand(0), Tmp1));
3111 False = DAG.getNode(ISD::XOR, dl, NVT, False,
3112 DAG.getConstant(x, dl, NVT));
3113 Tmp1 = DAG.getSelect(dl, NVT, Tmp2, True, False);
3114 Results.push_back(Tmp1);
3118 Results.push_back(DAG.expandVAArg(Node));
3119 Results.push_back(Results[0].getValue(1));
3122 Results.push_back(DAG.expandVACopy(Node));
3124 case ISD::EXTRACT_VECTOR_ELT:
3125 if (Node->getOperand(0).getValueType().getVectorNumElements() == 1)
3126 // This must be an access of the only element. Return it.
3127 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0),
3128 Node->getOperand(0));
3130 Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0));
3131 Results.push_back(Tmp1);
3133 case ISD::EXTRACT_SUBVECTOR:
3134 Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0)));
3136 case ISD::INSERT_SUBVECTOR:
3137 Results.push_back(ExpandInsertToVectorThroughStack(SDValue(Node, 0)));
3139 case ISD::CONCAT_VECTORS: {
3140 Results.push_back(ExpandVectorBuildThroughStack(Node));
3143 case ISD::SCALAR_TO_VECTOR:
3144 Results.push_back(ExpandSCALAR_TO_VECTOR(Node));
3146 case ISD::INSERT_VECTOR_ELT:
3147 Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0),
3148 Node->getOperand(1),
3149 Node->getOperand(2), dl));
3151 case ISD::VECTOR_SHUFFLE: {
3152 SmallVector<int, 32> NewMask;
3153 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
3155 EVT VT = Node->getValueType(0);
3156 EVT EltVT = VT.getVectorElementType();
3157 SDValue Op0 = Node->getOperand(0);
3158 SDValue Op1 = Node->getOperand(1);
3159 if (!TLI.isTypeLegal(EltVT)) {
3161 EVT NewEltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT);
3163 // BUILD_VECTOR operands are allowed to be wider than the element type.
3164 // But if NewEltVT is smaller that EltVT the BUILD_VECTOR does not accept
3166 if (NewEltVT.bitsLT(EltVT)) {
3168 // Convert shuffle node.
3169 // If original node was v4i64 and the new EltVT is i32,
3170 // cast operands to v8i32 and re-build the mask.
3172 // Calculate new VT, the size of the new VT should be equal to original.
3174 EVT::getVectorVT(*DAG.getContext(), NewEltVT,
3175 VT.getSizeInBits() / NewEltVT.getSizeInBits());
3176 assert(NewVT.bitsEq(VT));
3178 // cast operands to new VT
3179 Op0 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op0);
3180 Op1 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op1);
3182 // Convert the shuffle mask
3183 unsigned int factor =
3184 NewVT.getVectorNumElements()/VT.getVectorNumElements();
3186 // EltVT gets smaller
3189 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
3191 for (unsigned fi = 0; fi < factor; ++fi)
3192 NewMask.push_back(Mask[i]);
3195 for (unsigned fi = 0; fi < factor; ++fi)
3196 NewMask.push_back(Mask[i]*factor+fi);
3204 unsigned NumElems = VT.getVectorNumElements();
3205 SmallVector<SDValue, 16> Ops;
3206 for (unsigned i = 0; i != NumElems; ++i) {
3208 Ops.push_back(DAG.getUNDEF(EltVT));
3211 unsigned Idx = Mask[i];
3213 Ops.push_back(DAG.getNode(
3214 ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
3215 DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))));
3217 Ops.push_back(DAG.getNode(
3218 ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op1,
3219 DAG.getConstant(Idx - NumElems, dl,
3220 TLI.getVectorIdxTy(DAG.getDataLayout()))));
3223 Tmp1 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
3224 // We may have changed the BUILD_VECTOR type. Cast it back to the Node type.
3225 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), Tmp1);
3226 Results.push_back(Tmp1);
3229 case ISD::EXTRACT_ELEMENT: {
3230 EVT OpTy = Node->getOperand(0).getValueType();
3231 if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
3233 Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0),
3234 DAG.getConstant(OpTy.getSizeInBits() / 2, dl,
3235 TLI.getShiftAmountTy(
3236 Node->getOperand(0).getValueType(),
3237 DAG.getDataLayout())));
3238 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
3241 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
3242 Node->getOperand(0));
3244 Results.push_back(Tmp1);
3247 case ISD::STACKSAVE:
3248 // Expand to CopyFromReg if the target set
3249 // StackPointerRegisterToSaveRestore.
3250 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
3251 Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP,
3252 Node->getValueType(0)));
3253 Results.push_back(Results[0].getValue(1));
3255 Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
3256 Results.push_back(Node->getOperand(0));
3259 case ISD::STACKRESTORE:
3260 // Expand to CopyToReg if the target set
3261 // StackPointerRegisterToSaveRestore.
3262 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
3263 Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP,
3264 Node->getOperand(1)));
3266 Results.push_back(Node->getOperand(0));
3269 case ISD::FCOPYSIGN:
3270 Results.push_back(ExpandFCOPYSIGN(Node));
3273 // Expand Y = FNEG(X) -> Y = SUB -0.0, X
3274 Tmp1 = DAG.getConstantFP(-0.0, dl, Node->getValueType(0));
3275 // TODO: If FNEG has fast-math-flags, propagate them to the FSUB.
3276 Tmp1 = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp1,
3277 Node->getOperand(0));
3278 Results.push_back(Tmp1);
3281 Results.push_back(ExpandFABS(Node));
3287 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
3289 switch (Node->getOpcode()) {
3290 default: llvm_unreachable("How did we get here?");
3291 case ISD::SMAX: Pred = ISD::SETGT; break;
3292 case ISD::SMIN: Pred = ISD::SETLT; break;
3293 case ISD::UMAX: Pred = ISD::SETUGT; break;
3294 case ISD::UMIN: Pred = ISD::SETULT; break;
3296 Tmp1 = Node->getOperand(0);
3297 Tmp2 = Node->getOperand(1);
3298 Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp1, Tmp2, Pred);
3299 Results.push_back(Tmp1);
3305 EVT VT = Node->getValueType(0);
3306 // Turn fsin / fcos into ISD::FSINCOS node if there are a pair of fsin /
3307 // fcos which share the same operand and both are used.
3308 if ((TLI.isOperationLegalOrCustom(ISD::FSINCOS, VT) ||
3309 canCombineSinCosLibcall(Node, TLI, TM))
3310 && useSinCos(Node)) {
3311 SDVTList VTs = DAG.getVTList(VT, VT);
3312 Tmp1 = DAG.getNode(ISD::FSINCOS, dl, VTs, Node->getOperand(0));
3313 if (Node->getOpcode() == ISD::FCOS)
3314 Tmp1 = Tmp1.getValue(1);
3315 Results.push_back(Tmp1);
3320 llvm_unreachable("Illegal fmad should never be formed");
3322 case ISD::FP16_TO_FP:
3323 if (Node->getValueType(0) != MVT::f32) {
3324 // We can extend to types bigger than f32 in two steps without changing
3325 // the result. Since "f16 -> f32" is much more commonly available, give
3326 // CodeGen the option of emitting that before resorting to a libcall.
3328 DAG.getNode(ISD::FP16_TO_FP, dl, MVT::f32, Node->getOperand(0));
3330 DAG.getNode(ISD::FP_EXTEND, dl, Node->getValueType(0), Res));
3333 case ISD::FP_TO_FP16:
3334 if (!TLI.useSoftFloat() && TM.Options.UnsafeFPMath) {
3335 SDValue Op = Node->getOperand(0);
3336 MVT SVT = Op.getSimpleValueType();
3337 if ((SVT == MVT::f64 || SVT == MVT::f80) &&
3338 TLI.isOperationLegalOrCustom(ISD::FP_TO_FP16, MVT::f32)) {
3339 // Under fastmath, we can expand this node into a fround followed by
3340 // a float-half conversion.
3341 SDValue FloatVal = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Op,
3342 DAG.getIntPtrConstant(0, dl));
3344 DAG.getNode(ISD::FP_TO_FP16, dl, MVT::i16, FloatVal));
3348 case ISD::ConstantFP: {
3349 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
3350 // Check to see if this FP immediate is already legal.
3351 // If this is a legal constant, turn it into a TargetConstantFP node.
3352 if (!TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0)))
3353 Results.push_back(ExpandConstantFP(CFP, true));
3357 EVT VT = Node->getValueType(0);
3358 if (TLI.isOperationLegalOrCustom(ISD::FADD, VT) &&
3359 TLI.isOperationLegalOrCustom(ISD::FNEG, VT)) {
3360 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(Node)->Flags;
3361 Tmp1 = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(1));
3362 Tmp1 = DAG.getNode(ISD::FADD, dl, VT, Node->getOperand(0), Tmp1, Flags);
3363 Results.push_back(Tmp1);
3368 EVT VT = Node->getValueType(0);
3369 assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
3370 TLI.isOperationLegalOrCustom(ISD::XOR, VT) &&
3371 "Don't know how to expand this subtraction!");
3372 Tmp1 = DAG.getNode(ISD::XOR, dl, VT, Node->getOperand(1),
3373 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
3375 Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp1, DAG.getConstant(1, dl, VT));
3376 Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1));
3381 EVT VT = Node->getValueType(0);
3382 bool isSigned = Node->getOpcode() == ISD::SREM;
3383 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
3384 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3385 Tmp2 = Node->getOperand(0);
3386 Tmp3 = Node->getOperand(1);
3387 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) {
3388 SDVTList VTs = DAG.getVTList(VT, VT);
3389 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Tmp2, Tmp3).getValue(1);
3390 Results.push_back(Tmp1);
3391 } else if (TLI.isOperationLegalOrCustom(DivOpc, VT)) {
3393 Tmp1 = DAG.getNode(DivOpc, dl, VT, Tmp2, Tmp3);
3394 Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Tmp3);
3395 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Tmp2, Tmp1);
3396 Results.push_back(Tmp1);
3402 bool isSigned = Node->getOpcode() == ISD::SDIV;
3403 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3404 EVT VT = Node->getValueType(0);
3405 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) {
3406 SDVTList VTs = DAG.getVTList(VT, VT);
3407 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0),
3408 Node->getOperand(1));
3409 Results.push_back(Tmp1);
3415 unsigned ExpandOpcode = Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI :
3417 EVT VT = Node->getValueType(0);
3418 SDVTList VTs = DAG.getVTList(VT, VT);
3419 assert(TLI.isOperationLegalOrCustom(ExpandOpcode, VT) &&
3420 "If this wasn't legal, it shouldn't have been created!");
3421 Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0),
3422 Node->getOperand(1));
3423 Results.push_back(Tmp1.getValue(1));
3427 EVT VT = Node->getValueType(0);
3428 SDVTList VTs = DAG.getVTList(VT, VT);
3429 // See if multiply or divide can be lowered using two-result operations.
3430 // We just need the low half of the multiply; try both the signed
3431 // and unsigned forms. If the target supports both SMUL_LOHI and
3432 // UMUL_LOHI, form a preference by checking which forms of plain
3433 // MULH it supports.
3434 bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
3435 bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
3436 bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
3437 bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
3438 unsigned OpToUse = 0;
3439 if (HasSMUL_LOHI && !HasMULHS) {
3440 OpToUse = ISD::SMUL_LOHI;
3441 } else if (HasUMUL_LOHI && !HasMULHU) {
3442 OpToUse = ISD::UMUL_LOHI;
3443 } else if (HasSMUL_LOHI) {
3444 OpToUse = ISD::SMUL_LOHI;
3445 } else if (HasUMUL_LOHI) {
3446 OpToUse = ISD::UMUL_LOHI;
3449 Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0),
3450 Node->getOperand(1)));
3455 EVT HalfType = VT.getHalfSizedIntegerVT(*DAG.getContext());
3456 if (TLI.isOperationLegalOrCustom(ISD::ZERO_EXTEND, VT) &&
3457 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND, VT) &&
3458 TLI.isOperationLegalOrCustom(ISD::SHL, VT) &&
3459 TLI.isOperationLegalOrCustom(ISD::OR, VT) &&
3460 TLI.expandMUL(Node, Lo, Hi, HalfType, DAG)) {
3461 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
3462 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Hi);
3464 DAG.getConstant(HalfType.getSizeInBits(), dl,
3465 TLI.getShiftAmountTy(HalfType, DAG.getDataLayout()));
3466 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
3467 Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi));
3473 SDValue LHS = Node->getOperand(0);
3474 SDValue RHS = Node->getOperand(1);
3475 SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
3476 ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3478 Results.push_back(Sum);
3479 EVT ResultType = Node->getValueType(1);
3480 EVT OType = getSetCCResultType(Node->getValueType(0));
3482 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
3484 // LHSSign -> LHS >= 0
3485 // RHSSign -> RHS >= 0
3486 // SumSign -> Sum >= 0
3489 // Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
3491 // Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
3493 SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
3494 SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
3495 SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
3496 Node->getOpcode() == ISD::SADDO ?
3497 ISD::SETEQ : ISD::SETNE);
3499 SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
3500 SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
3502 SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
3503 Results.push_back(DAG.getBoolExtOrTrunc(Cmp, dl, ResultType, ResultType));
3508 SDValue LHS = Node->getOperand(0);
3509 SDValue RHS = Node->getOperand(1);
3510 SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::UADDO ?
3511 ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3513 Results.push_back(Sum);
3515 EVT ResultType = Node->getValueType(1);
3516 EVT SetCCType = getSetCCResultType(Node->getValueType(0));
3518 = Node->getOpcode() == ISD::UADDO ? ISD::SETULT : ISD::SETUGT;
3519 SDValue SetCC = DAG.getSetCC(dl, SetCCType, Sum, LHS, CC);
3521 Results.push_back(DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType));
3526 EVT VT = Node->getValueType(0);
3527 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits() * 2);
3528 SDValue LHS = Node->getOperand(0);
3529 SDValue RHS = Node->getOperand(1);
3532 static const unsigned Ops[2][3] =
3533 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
3534 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
3535 bool isSigned = Node->getOpcode() == ISD::SMULO;
3536 if (TLI.isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
3537 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
3538 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
3539 } else if (TLI.isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
3540 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
3542 TopHalf = BottomHalf.getValue(1);
3543 } else if (TLI.isTypeLegal(WideVT)) {
3544 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
3545 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
3546 Tmp1 = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
3547 BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
3548 DAG.getIntPtrConstant(0, dl));
3549 TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
3550 DAG.getIntPtrConstant(1, dl));
3552 // We can fall back to a libcall with an illegal type for the MUL if we
3553 // have a libcall big enough.
3554 // Also, we can fall back to a division in some cases, but that's a big
3555 // performance hit in the general case.
3556 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3557 if (WideVT == MVT::i16)
3558 LC = RTLIB::MUL_I16;
3559 else if (WideVT == MVT::i32)
3560 LC = RTLIB::MUL_I32;
3561 else if (WideVT == MVT::i64)
3562 LC = RTLIB::MUL_I64;
3563 else if (WideVT == MVT::i128)
3564 LC = RTLIB::MUL_I128;
3565 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!");
3567 // The high part is obtained by SRA'ing all but one of the bits of low
3569 unsigned LoSize = VT.getSizeInBits();
3571 DAG.getNode(ISD::SRA, dl, VT, RHS,
3572 DAG.getConstant(LoSize - 1, dl,
3573 TLI.getPointerTy(DAG.getDataLayout())));
3575 DAG.getNode(ISD::SRA, dl, VT, LHS,
3576 DAG.getConstant(LoSize - 1, dl,
3577 TLI.getPointerTy(DAG.getDataLayout())));
3579 // Here we're passing the 2 arguments explicitly as 4 arguments that are
3580 // pre-lowered to the correct types. This all depends upon WideVT not
3581 // being a legal type for the architecture and thus has to be split to
3583 SDValue Args[] = { LHS, HiLHS, RHS, HiRHS };
3584 SDValue Ret = ExpandLibCall(LC, WideVT, Args, 4, isSigned, dl);
3585 BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Ret,
3586 DAG.getIntPtrConstant(0, dl));
3587 TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Ret,
3588 DAG.getIntPtrConstant(1, dl));
3589 // Ret is a node with an illegal type. Because such things are not
3590 // generally permitted during this phase of legalization, make sure the
3591 // node has no more uses. The above EXTRACT_ELEMENT nodes should have been
3593 assert(Ret->use_empty() &&
3594 "Unexpected uses of illegally type from expanded lib call.");
3598 Tmp1 = DAG.getConstant(
3599 VT.getSizeInBits() - 1, dl,
3600 TLI.getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout()));
3601 Tmp1 = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, Tmp1);
3602 TopHalf = DAG.getSetCC(dl, getSetCCResultType(VT), TopHalf, Tmp1,
3605 TopHalf = DAG.getSetCC(dl, getSetCCResultType(VT), TopHalf,
3606 DAG.getConstant(0, dl, VT), ISD::SETNE);
3608 Results.push_back(BottomHalf);
3609 Results.push_back(TopHalf);
3612 case ISD::BUILD_PAIR: {
3613 EVT PairTy = Node->getValueType(0);
3614 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0));
3615 Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1));
3617 ISD::SHL, dl, PairTy, Tmp2,
3618 DAG.getConstant(PairTy.getSizeInBits() / 2, dl,
3619 TLI.getShiftAmountTy(PairTy, DAG.getDataLayout())));
3620 Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2));
3624 Tmp1 = Node->getOperand(0);
3625 Tmp2 = Node->getOperand(1);
3626 Tmp3 = Node->getOperand(2);
3627 if (Tmp1.getOpcode() == ISD::SETCC) {
3628 Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1),
3630 cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
3632 Tmp1 = DAG.getSelectCC(dl, Tmp1,
3633 DAG.getConstant(0, dl, Tmp1.getValueType()),
3634 Tmp2, Tmp3, ISD::SETNE);
3636 Results.push_back(Tmp1);
3639 SDValue Chain = Node->getOperand(0);
3640 SDValue Table = Node->getOperand(1);
3641 SDValue Index = Node->getOperand(2);
3643 EVT PTy = TLI.getPointerTy(DAG.getDataLayout());
3645 const DataLayout &TD = DAG.getDataLayout();
3646 unsigned EntrySize =
3647 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
3649 Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(), Index,
3650 DAG.getConstant(EntrySize, dl, Index.getValueType()));
3651 SDValue Addr = DAG.getNode(ISD::ADD, dl, Index.getValueType(),
3654 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
3655 SDValue LD = DAG.getExtLoad(
3656 ISD::SEXTLOAD, dl, PTy, Chain, Addr,
3657 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), MemVT,
3658 false, false, false, 0);
3660 if (TM.getRelocationModel() == Reloc::PIC_) {
3661 // For PIC, the sequence is:
3662 // BRIND(load(Jumptable + index) + RelocBase)
3663 // RelocBase can be JumpTable, GOT or some sort of global base.
3664 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr,
3665 TLI.getPICJumpTableRelocBase(Table, DAG));
3667 Tmp1 = DAG.getNode(ISD::BRIND, dl, MVT::Other, LD.getValue(1), Addr);
3668 Results.push_back(Tmp1);
3672 // Expand brcond's setcc into its constituent parts and create a BR_CC
3674 Tmp1 = Node->getOperand(0);
3675 Tmp2 = Node->getOperand(1);
3676 if (Tmp2.getOpcode() == ISD::SETCC) {
3677 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other,
3678 Tmp1, Tmp2.getOperand(2),
3679 Tmp2.getOperand(0), Tmp2.getOperand(1),
3680 Node->getOperand(2));
3682 // We test only the i1 bit. Skip the AND if UNDEF.
3683 Tmp3 = (Tmp2.getOpcode() == ISD::UNDEF) ? Tmp2 :
3684 DAG.getNode(ISD::AND, dl, Tmp2.getValueType(), Tmp2,
3685 DAG.getConstant(1, dl, Tmp2.getValueType()));
3686 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
3687 DAG.getCondCode(ISD::SETNE), Tmp3,
3688 DAG.getConstant(0, dl, Tmp3.getValueType()),
3689 Node->getOperand(2));
3691 Results.push_back(Tmp1);
3694 Tmp1 = Node->getOperand(0);
3695 Tmp2 = Node->getOperand(1);
3696 Tmp3 = Node->getOperand(2);
3697 bool Legalized = LegalizeSetCCCondCode(Node->getValueType(0), Tmp1, Tmp2,
3698 Tmp3, NeedInvert, dl);
3701 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
3702 // condition code, create a new SETCC node.
3704 Tmp1 = DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
3707 // If we expanded the SETCC by inverting the condition code, then wrap
3708 // the existing SETCC in a NOT to restore the intended condition.
3710 Tmp1 = DAG.getLogicalNOT(dl, Tmp1, Tmp1->getValueType(0));
3712 Results.push_back(Tmp1);
3716 // Otherwise, SETCC for the given comparison type must be completely
3717 // illegal; expand it into a SELECT_CC.
3718 EVT VT = Node->getValueType(0);
3720 switch (TLI.getBooleanContents(Tmp1->getValueType(0))) {
3721 case TargetLowering::ZeroOrOneBooleanContent:
3722 case TargetLowering::UndefinedBooleanContent:
3725 case TargetLowering::ZeroOrNegativeOneBooleanContent:
3729 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
3730 DAG.getConstant(TrueValue, dl, VT),
3731 DAG.getConstant(0, dl, VT),
3733 Results.push_back(Tmp1);
3736 case ISD::SELECT_CC: {
3737 Tmp1 = Node->getOperand(0); // LHS
3738 Tmp2 = Node->getOperand(1); // RHS
3739 Tmp3 = Node->getOperand(2); // True
3740 Tmp4 = Node->getOperand(3); // False
3741 EVT VT = Node->getValueType(0);
3742 SDValue CC = Node->getOperand(4);
3743 ISD::CondCode CCOp = cast<CondCodeSDNode>(CC)->get();
3745 if (TLI.isCondCodeLegal(CCOp, Tmp1.getSimpleValueType())) {
3746 // If the condition code is legal, then we need to expand this
3747 // node using SETCC and SELECT.
3748 EVT CmpVT = Tmp1.getValueType();
3749 assert(!TLI.isOperationExpand(ISD::SELECT, VT) &&
3750 "Cannot expand ISD::SELECT_CC when ISD::SELECT also needs to be "
3753 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT);
3754 SDValue Cond = DAG.getNode(ISD::SETCC, dl, CCVT, Tmp1, Tmp2, CC);
3755 Results.push_back(DAG.getSelect(dl, VT, Cond, Tmp3, Tmp4));
3759 // SELECT_CC is legal, so the condition code must not be.
3760 bool Legalized = false;
3761 // Try to legalize by inverting the condition. This is for targets that
3762 // might support an ordered version of a condition, but not the unordered
3763 // version (or vice versa).
3764 ISD::CondCode InvCC = ISD::getSetCCInverse(CCOp,
3765 Tmp1.getValueType().isInteger());
3766 if (TLI.isCondCodeLegal(InvCC, Tmp1.getSimpleValueType())) {
3767 // Use the new condition code and swap true and false
3769 Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp4, Tmp3, InvCC);
3771 // If The inverse is not legal, then try to swap the arguments using
3772 // the inverse condition code.
3773 ISD::CondCode SwapInvCC = ISD::getSetCCSwappedOperands(InvCC);
3774 if (TLI.isCondCodeLegal(SwapInvCC, Tmp1.getSimpleValueType())) {
3775 // The swapped inverse condition is legal, so swap true and false,
3778 Tmp1 = DAG.getSelectCC(dl, Tmp2, Tmp1, Tmp4, Tmp3, SwapInvCC);
3783 Legalized = LegalizeSetCCCondCode(
3784 getSetCCResultType(Tmp1.getValueType()), Tmp1, Tmp2, CC, NeedInvert,
3787 assert(Legalized && "Can't legalize SELECT_CC with legal condition!");
3789 // If we expanded the SETCC by inverting the condition code, then swap
3790 // the True/False operands to match.
3792 std::swap(Tmp3, Tmp4);
3794 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
3795 // condition code, create a new SELECT_CC node.
3797 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0),
3798 Tmp1, Tmp2, Tmp3, Tmp4, CC);
3800 Tmp2 = DAG.getConstant(0, dl, Tmp1.getValueType());
3801 CC = DAG.getCondCode(ISD::SETNE);
3802 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1,
3803 Tmp2, Tmp3, Tmp4, CC);
3806 Results.push_back(Tmp1);
3810 Tmp1 = Node->getOperand(0); // Chain
3811 Tmp2 = Node->getOperand(2); // LHS
3812 Tmp3 = Node->getOperand(3); // RHS
3813 Tmp4 = Node->getOperand(1); // CC
3815 bool Legalized = LegalizeSetCCCondCode(getSetCCResultType(
3816 Tmp2.getValueType()), Tmp2, Tmp3, Tmp4, NeedInvert, dl);
3818 assert(Legalized && "Can't legalize BR_CC with legal condition!");
3820 // If we expanded the SETCC by inverting the condition code, then wrap
3821 // the existing SETCC in a NOT to restore the intended condition.
3823 Tmp4 = DAG.getNOT(dl, Tmp4, Tmp4->getValueType(0));
3825 // If we expanded the SETCC by swapping LHS and RHS, create a new BR_CC
3827 if (Tmp4.getNode()) {
3828 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1,
3829 Tmp4, Tmp2, Tmp3, Node->getOperand(4));
3831 Tmp3 = DAG.getConstant(0, dl, Tmp2.getValueType());
3832 Tmp4 = DAG.getCondCode(ISD::SETNE);
3833 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4,
3834 Tmp2, Tmp3, Node->getOperand(4));
3836 Results.push_back(Tmp1);
3839 case ISD::BUILD_VECTOR:
3840 Results.push_back(ExpandBUILD_VECTOR(Node));
3845 // Scalarize vector SRA/SRL/SHL.
3846 EVT VT = Node->getValueType(0);
3847 assert(VT.isVector() && "Unable to legalize non-vector shift");
3848 assert(TLI.isTypeLegal(VT.getScalarType())&& "Element type must be legal");
3849 unsigned NumElem = VT.getVectorNumElements();
3851 SmallVector<SDValue, 8> Scalars;
3852 for (unsigned Idx = 0; Idx < NumElem; Idx++) {
3853 SDValue Ex = DAG.getNode(
3854 ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(), Node->getOperand(0),
3855 DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
3856 SDValue Sh = DAG.getNode(
3857 ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(), Node->getOperand(1),
3858 DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
3859 Scalars.push_back(DAG.getNode(Node->getOpcode(), dl,
3860 VT.getScalarType(), Ex, Sh));
3863 DAG.getNode(ISD::BUILD_VECTOR, dl, Node->getValueType(0), Scalars);
3864 ReplaceNode(SDValue(Node, 0), Result);
3867 case ISD::GLOBAL_OFFSET_TABLE:
3868 case ISD::GlobalAddress:
3869 case ISD::GlobalTLSAddress:
3870 case ISD::ExternalSymbol:
3871 case ISD::ConstantPool:
3872 case ISD::JumpTable:
3873 case ISD::INTRINSIC_W_CHAIN:
3874 case ISD::INTRINSIC_WO_CHAIN:
3875 case ISD::INTRINSIC_VOID:
3876 // FIXME: Custom lowering for these operations shouldn't return null!
3880 // Replace the original node with the legalized result.
3881 if (Results.empty())
3884 ReplaceNode(Node, Results.data());
3888 void SelectionDAGLegalize::ConvertNodeToLibcall(SDNode *Node) {
3889 SmallVector<SDValue, 8> Results;
3891 SDValue Tmp1, Tmp2, Tmp3, Tmp4;
3892 unsigned Opc = Node->getOpcode();
3894 case ISD::ATOMIC_FENCE: {
3895 // If the target didn't lower this, lower it to '__sync_synchronize()' call
3896 // FIXME: handle "fence singlethread" more efficiently.
3897 TargetLowering::ArgListTy Args;
3899 TargetLowering::CallLoweringInfo CLI(DAG);
3901 .setChain(Node->getOperand(0))
3902 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3903 DAG.getExternalSymbol("__sync_synchronize",
3904 TLI.getPointerTy(DAG.getDataLayout())),
3905 std::move(Args), 0);
3907 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
3909 Results.push_back(CallResult.second);
3912 // By default, atomic intrinsics are marked Legal and lowered. Targets
3913 // which don't support them directly, however, may want libcalls, in which
3914 // case they mark them Expand, and we get here.
3915 case ISD::ATOMIC_SWAP:
3916 case ISD::ATOMIC_LOAD_ADD:
3917 case ISD::ATOMIC_LOAD_SUB:
3918 case ISD::ATOMIC_LOAD_AND:
3919 case ISD::ATOMIC_LOAD_OR:
3920 case ISD::ATOMIC_LOAD_XOR:
3921 case ISD::ATOMIC_LOAD_NAND:
3922 case ISD::ATOMIC_LOAD_MIN:
3923 case ISD::ATOMIC_LOAD_MAX:
3924 case ISD::ATOMIC_LOAD_UMIN:
3925 case ISD::ATOMIC_LOAD_UMAX:
3926 case ISD::ATOMIC_CMP_SWAP: {
3927 MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
3928 RTLIB::Libcall LC = RTLIB::getATOMIC(Opc, VT);
3929 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected atomic op or value type!");
3931 std::pair<SDValue, SDValue> Tmp = ExpandChainLibCall(LC, Node, false);
3932 Results.push_back(Tmp.first);
3933 Results.push_back(Tmp.second);
3937 // If this operation is not supported, lower it to 'abort()' call
3938 TargetLowering::ArgListTy Args;
3939 TargetLowering::CallLoweringInfo CLI(DAG);
3941 .setChain(Node->getOperand(0))
3942 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3943 DAG.getExternalSymbol("abort",
3944 TLI.getPointerTy(DAG.getDataLayout())),
3945 std::move(Args), 0);
3946 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
3948 Results.push_back(CallResult.second);
3952 Results.push_back(ExpandFPLibCall(Node, RTLIB::FMIN_F32, RTLIB::FMIN_F64,
3953 RTLIB::FMIN_F80, RTLIB::FMIN_F128,
3954 RTLIB::FMIN_PPCF128));
3957 Results.push_back(ExpandFPLibCall(Node, RTLIB::FMAX_F32, RTLIB::FMAX_F64,
3958 RTLIB::FMAX_F80, RTLIB::FMAX_F128,
3959 RTLIB::FMAX_PPCF128));
3962 Results.push_back(ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
3963 RTLIB::SQRT_F80, RTLIB::SQRT_F128,
3964 RTLIB::SQRT_PPCF128));
3967 Results.push_back(ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64,
3968 RTLIB::SIN_F80, RTLIB::SIN_F128,
3969 RTLIB::SIN_PPCF128));
3972 Results.push_back(ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64,
3973 RTLIB::COS_F80, RTLIB::COS_F128,
3974 RTLIB::COS_PPCF128));
3977 // Expand into sincos libcall.
3978 ExpandSinCosLibCall(Node, Results);
3981 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64,
3982 RTLIB::LOG_F80, RTLIB::LOG_F128,
3983 RTLIB::LOG_PPCF128));
3986 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
3987 RTLIB::LOG2_F80, RTLIB::LOG2_F128,
3988 RTLIB::LOG2_PPCF128));
3991 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
3992 RTLIB::LOG10_F80, RTLIB::LOG10_F128,
3993 RTLIB::LOG10_PPCF128));
3996 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64,
3997 RTLIB::EXP_F80, RTLIB::EXP_F128,
3998 RTLIB::EXP_PPCF128));
4001 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
4002 RTLIB::EXP2_F80, RTLIB::EXP2_F128,
4003 RTLIB::EXP2_PPCF128));
4006 Results.push_back(ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
4007 RTLIB::TRUNC_F80, RTLIB::TRUNC_F128,
4008 RTLIB::TRUNC_PPCF128));
4011 Results.push_back(ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
4012 RTLIB::FLOOR_F80, RTLIB::FLOOR_F128,
4013 RTLIB::FLOOR_PPCF128));
4016 Results.push_back(ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
4017 RTLIB::CEIL_F80, RTLIB::CEIL_F128,
4018 RTLIB::CEIL_PPCF128));
4021 Results.push_back(ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64,
4022 RTLIB::RINT_F80, RTLIB::RINT_F128,
4023 RTLIB::RINT_PPCF128));
4025 case ISD::FNEARBYINT:
4026 Results.push_back(ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32,
4027 RTLIB::NEARBYINT_F64,
4028 RTLIB::NEARBYINT_F80,
4029 RTLIB::NEARBYINT_F128,
4030 RTLIB::NEARBYINT_PPCF128));
4033 Results.push_back(ExpandFPLibCall(Node, RTLIB::ROUND_F32,
4037 RTLIB::ROUND_PPCF128));
4040 Results.push_back(ExpandFPLibCall(Node, RTLIB::POWI_F32, RTLIB::POWI_F64,
4041 RTLIB::POWI_F80, RTLIB::POWI_F128,
4042 RTLIB::POWI_PPCF128));
4045 Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64,
4046 RTLIB::POW_F80, RTLIB::POW_F128,
4047 RTLIB::POW_PPCF128));
4050 Results.push_back(ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64,
4051 RTLIB::DIV_F80, RTLIB::DIV_F128,
4052 RTLIB::DIV_PPCF128));
4055 Results.push_back(ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64,
4056 RTLIB::REM_F80, RTLIB::REM_F128,
4057 RTLIB::REM_PPCF128));
4060 Results.push_back(ExpandFPLibCall(Node, RTLIB::FMA_F32, RTLIB::FMA_F64,
4061 RTLIB::FMA_F80, RTLIB::FMA_F128,
4062 RTLIB::FMA_PPCF128));
4065 Results.push_back(ExpandFPLibCall(Node, RTLIB::ADD_F32, RTLIB::ADD_F64,
4066 RTLIB::ADD_F80, RTLIB::ADD_F128,
4067 RTLIB::ADD_PPCF128));
4070 Results.push_back(ExpandFPLibCall(Node, RTLIB::MUL_F32, RTLIB::MUL_F64,
4071 RTLIB::MUL_F80, RTLIB::MUL_F128,
4072 RTLIB::MUL_PPCF128));
4074 case ISD::FP16_TO_FP:
4075 if (Node->getValueType(0) == MVT::f32) {
4076 Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false));
4079 case ISD::FP_TO_FP16: {
4081 RTLIB::getFPROUND(Node->getOperand(0).getValueType(), MVT::f16);
4082 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to expand fp_to_fp16");
4083 Results.push_back(ExpandLibCall(LC, Node, false));
4087 Results.push_back(ExpandFPLibCall(Node, RTLIB::SUB_F32, RTLIB::SUB_F64,
4088 RTLIB::SUB_F80, RTLIB::SUB_F128,
4089 RTLIB::SUB_PPCF128));
4092 Results.push_back(ExpandIntLibCall(Node, true,
4094 RTLIB::SREM_I16, RTLIB::SREM_I32,
4095 RTLIB::SREM_I64, RTLIB::SREM_I128));
4098 Results.push_back(ExpandIntLibCall(Node, false,
4100 RTLIB::UREM_I16, RTLIB::UREM_I32,
4101 RTLIB::UREM_I64, RTLIB::UREM_I128));
4104 Results.push_back(ExpandIntLibCall(Node, true,
4106 RTLIB::SDIV_I16, RTLIB::SDIV_I32,
4107 RTLIB::SDIV_I64, RTLIB::SDIV_I128));
4110 Results.push_back(ExpandIntLibCall(Node, false,
4112 RTLIB::UDIV_I16, RTLIB::UDIV_I32,
4113 RTLIB::UDIV_I64, RTLIB::UDIV_I128));
4117 // Expand into divrem libcall
4118 ExpandDivRemLibCall(Node, Results);
4121 Results.push_back(ExpandIntLibCall(Node, false,
4123 RTLIB::MUL_I16, RTLIB::MUL_I32,
4124 RTLIB::MUL_I64, RTLIB::MUL_I128));
4128 // Replace the original node with the legalized result.
4129 if (!Results.empty())
4130 ReplaceNode(Node, Results.data());
4133 // Determine the vector type to use in place of an original scalar element when
4134 // promoting equally sized vectors.
4135 static MVT getPromotedVectorElementType(const TargetLowering &TLI,
4136 MVT EltVT, MVT NewEltVT) {
4137 unsigned OldEltsPerNewElt = EltVT.getSizeInBits() / NewEltVT.getSizeInBits();
4138 MVT MidVT = MVT::getVectorVT(NewEltVT, OldEltsPerNewElt);
4139 assert(TLI.isTypeLegal(MidVT) && "unexpected");
4143 void SelectionDAGLegalize::PromoteNode(SDNode *Node) {
4144 SmallVector<SDValue, 8> Results;
4145 MVT OVT = Node->getSimpleValueType(0);
4146 if (Node->getOpcode() == ISD::UINT_TO_FP ||
4147 Node->getOpcode() == ISD::SINT_TO_FP ||
4148 Node->getOpcode() == ISD::SETCC ||
4149 Node->getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
4150 Node->getOpcode() == ISD::INSERT_VECTOR_ELT) {
4151 OVT = Node->getOperand(0).getSimpleValueType();
4153 if (Node->getOpcode() == ISD::BR_CC)
4154 OVT = Node->getOperand(2).getSimpleValueType();
4155 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
4157 SDValue Tmp1, Tmp2, Tmp3;
4158 switch (Node->getOpcode()) {
4160 case ISD::CTTZ_ZERO_UNDEF:
4162 case ISD::CTLZ_ZERO_UNDEF:
4164 // Zero extend the argument.
4165 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
4166 // Perform the larger operation. For CTPOP and CTTZ_ZERO_UNDEF, this is
4167 // already the correct result.
4168 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4169 if (Node->getOpcode() == ISD::CTTZ) {
4170 // FIXME: This should set a bit in the zero extended value instead.
4171 Tmp2 = DAG.getSetCC(dl, getSetCCResultType(NVT),
4172 Tmp1, DAG.getConstant(NVT.getSizeInBits(), dl, NVT),
4174 Tmp1 = DAG.getSelect(dl, NVT, Tmp2,
4175 DAG.getConstant(OVT.getSizeInBits(), dl, NVT), Tmp1);
4176 } else if (Node->getOpcode() == ISD::CTLZ ||
4177 Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF) {
4178 // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
4179 Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
4180 DAG.getConstant(NVT.getSizeInBits() -
4181 OVT.getSizeInBits(), dl, NVT));
4183 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
4186 unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
4187 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
4188 Tmp1 = DAG.getNode(ISD::BSWAP, dl, NVT, Tmp1);
4190 ISD::SRL, dl, NVT, Tmp1,
4191 DAG.getConstant(DiffBits, dl,
4192 TLI.getShiftAmountTy(NVT, DAG.getDataLayout())));
4193 Results.push_back(Tmp1);
4196 case ISD::FP_TO_UINT:
4197 case ISD::FP_TO_SINT:
4198 Tmp1 = PromoteLegalFP_TO_INT(Node->getOperand(0), Node->getValueType(0),
4199 Node->getOpcode() == ISD::FP_TO_SINT, dl);
4200 Results.push_back(Tmp1);
4202 case ISD::UINT_TO_FP:
4203 case ISD::SINT_TO_FP:
4204 Tmp1 = PromoteLegalINT_TO_FP(Node->getOperand(0), Node->getValueType(0),
4205 Node->getOpcode() == ISD::SINT_TO_FP, dl);
4206 Results.push_back(Tmp1);
4209 SDValue Chain = Node->getOperand(0); // Get the chain.
4210 SDValue Ptr = Node->getOperand(1); // Get the pointer.
4213 if (OVT.isVector()) {
4214 TruncOp = ISD::BITCAST;
4216 assert(OVT.isInteger()
4217 && "VAARG promotion is supported only for vectors or integer types");
4218 TruncOp = ISD::TRUNCATE;
4221 // Perform the larger operation, then convert back
4222 Tmp1 = DAG.getVAArg(NVT, dl, Chain, Ptr, Node->getOperand(2),
4223 Node->getConstantOperandVal(3));
4224 Chain = Tmp1.getValue(1);
4226 Tmp2 = DAG.getNode(TruncOp, dl, OVT, Tmp1);
4228 // Modified the chain result - switch anything that used the old chain to
4230 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Tmp2);
4231 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
4233 UpdatedNodes->insert(Tmp2.getNode());
4234 UpdatedNodes->insert(Chain.getNode());
4242 unsigned ExtOp, TruncOp;
4243 if (OVT.isVector()) {
4244 ExtOp = ISD::BITCAST;
4245 TruncOp = ISD::BITCAST;
4247 assert(OVT.isInteger() && "Cannot promote logic operation");
4248 ExtOp = ISD::ANY_EXTEND;
4249 TruncOp = ISD::TRUNCATE;
4251 // Promote each of the values to the new type.
4252 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4253 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4254 // Perform the larger operation, then convert back
4255 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4256 Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1));
4260 unsigned ExtOp, TruncOp;
4261 if (Node->getValueType(0).isVector() ||
4262 Node->getValueType(0).getSizeInBits() == NVT.getSizeInBits()) {
4263 ExtOp = ISD::BITCAST;
4264 TruncOp = ISD::BITCAST;
4265 } else if (Node->getValueType(0).isInteger()) {
4266 ExtOp = ISD::ANY_EXTEND;
4267 TruncOp = ISD::TRUNCATE;
4269 ExtOp = ISD::FP_EXTEND;
4270 TruncOp = ISD::FP_ROUND;
4272 Tmp1 = Node->getOperand(0);
4273 // Promote each of the values to the new type.
4274 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4275 Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
4276 // Perform the larger operation, then round down.
4277 Tmp1 = DAG.getSelect(dl, NVT, Tmp1, Tmp2, Tmp3);
4278 if (TruncOp != ISD::FP_ROUND)
4279 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1);
4281 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1,
4282 DAG.getIntPtrConstant(0, dl));
4283 Results.push_back(Tmp1);
4286 case ISD::VECTOR_SHUFFLE: {
4287 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
4289 // Cast the two input vectors.
4290 Tmp1 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0));
4291 Tmp2 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(1));
4293 // Convert the shuffle mask to the right # elements.
4294 Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
4295 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OVT, Tmp1);
4296 Results.push_back(Tmp1);
4300 unsigned ExtOp = ISD::FP_EXTEND;
4301 if (NVT.isInteger()) {
4302 ISD::CondCode CCCode =
4303 cast<CondCodeSDNode>(Node->getOperand(2))->get();
4304 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4306 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4307 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4308 Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
4309 Tmp1, Tmp2, Node->getOperand(2)));
4313 unsigned ExtOp = ISD::FP_EXTEND;
4314 if (NVT.isInteger()) {
4315 ISD::CondCode CCCode =
4316 cast<CondCodeSDNode>(Node->getOperand(1))->get();
4317 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4319 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
4320 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(3));
4321 Results.push_back(DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0),
4322 Node->getOperand(0), Node->getOperand(1),
4323 Tmp1, Tmp2, Node->getOperand(4)));
4334 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4335 Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
4336 Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2,
4338 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4339 Tmp3, DAG.getIntPtrConstant(0, dl)));
4343 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4344 Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
4345 Tmp3 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(2));
4347 DAG.getNode(ISD::FP_ROUND, dl, OVT,
4348 DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2, Tmp3),
4349 DAG.getIntPtrConstant(0, dl)));
4352 case ISD::FCOPYSIGN:
4354 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4355 Tmp2 = Node->getOperand(1);
4356 Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4358 // fcopysign doesn't change anything but the sign bit, so
4359 // (fp_round (fcopysign (fpext a), b))
4361 // (fp_round (fpext a))
4362 // which is a no-op. Mark it as a TRUNCating FP_ROUND.
4363 const bool isTrunc = (Node->getOpcode() == ISD::FCOPYSIGN);
4364 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4365 Tmp3, DAG.getIntPtrConstant(isTrunc, dl)));
4371 case ISD::FNEARBYINT:
4384 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4385 Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4386 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4387 Tmp2, DAG.getIntPtrConstant(0, dl)));
4390 case ISD::BUILD_VECTOR: {
4391 MVT EltVT = OVT.getVectorElementType();
4392 MVT NewEltVT = NVT.getVectorElementType();
4394 // Handle bitcasts to a different vector type with the same total bit size
4396 // e.g. v2i64 = build_vector i64:x, i64:y => v4i32
4398 // v4i32 = concat_vectors (v2i32 (bitcast i64:x)), (v2i32 (bitcast i64:y))
4400 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
4401 "Invalid promote type for build_vector");
4402 assert(NewEltVT.bitsLT(EltVT) && "not handled");
4404 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4406 SmallVector<SDValue, 8> NewOps;
4407 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) {
4408 SDValue Op = Node->getOperand(I);
4409 NewOps.push_back(DAG.getNode(ISD::BITCAST, SDLoc(Op), MidVT, Op));
4413 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewOps);
4414 SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat);
4415 Results.push_back(CvtVec);
4418 case ISD::EXTRACT_VECTOR_ELT: {
4419 MVT EltVT = OVT.getVectorElementType();
4420 MVT NewEltVT = NVT.getVectorElementType();
4422 // Handle bitcasts to a different vector type with the same total bit size.
4424 // e.g. v2i64 = extract_vector_elt x:v2i64, y:i32
4426 // v4i32:castx = bitcast x:v2i64
4429 // (v2i32 build_vector (i32 (extract_vector_elt castx, (2 * y))),
4430 // (i32 (extract_vector_elt castx, (2 * y + 1)))
4433 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
4434 "Invalid promote type for extract_vector_elt");
4435 assert(NewEltVT.bitsLT(EltVT) && "not handled");
4437 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4438 unsigned NewEltsPerOldElt = MidVT.getVectorNumElements();
4440 SDValue Idx = Node->getOperand(1);
4441 EVT IdxVT = Idx.getValueType();
4443 SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SL, IdxVT);
4444 SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor);
4446 SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0));
4448 SmallVector<SDValue, 8> NewOps;
4449 for (unsigned I = 0; I < NewEltsPerOldElt; ++I) {
4450 SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT);
4451 SDValue TmpIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset);
4453 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT,
4455 NewOps.push_back(Elt);
4458 SDValue NewVec = DAG.getNode(ISD::BUILD_VECTOR, SL, MidVT, NewOps);
4460 Results.push_back(DAG.getNode(ISD::BITCAST, SL, EltVT, NewVec));
4463 case ISD::INSERT_VECTOR_ELT: {
4464 MVT EltVT = OVT.getVectorElementType();
4465 MVT NewEltVT = NVT.getVectorElementType();
4467 // Handle bitcasts to a different vector type with the same total bit size
4469 // e.g. v2i64 = insert_vector_elt x:v2i64, y:i64, z:i32
4471 // v4i32:castx = bitcast x:v2i64
4472 // v2i32:casty = bitcast y:i64
4475 // (v4i32 insert_vector_elt
4476 // (v4i32 insert_vector_elt v4i32:castx,
4477 // (extract_vector_elt casty, 0), 2 * z),
4478 // (extract_vector_elt casty, 1), (2 * z + 1))
4480 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
4481 "Invalid promote type for insert_vector_elt");
4482 assert(NewEltVT.bitsLT(EltVT) && "not handled");
4484 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4485 unsigned NewEltsPerOldElt = MidVT.getVectorNumElements();
4487 SDValue Val = Node->getOperand(1);
4488 SDValue Idx = Node->getOperand(2);
4489 EVT IdxVT = Idx.getValueType();
4492 SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SDLoc(), IdxVT);
4493 SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor);
4495 SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0));
4496 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val);
4498 SDValue NewVec = CastVec;
4499 for (unsigned I = 0; I < NewEltsPerOldElt; ++I) {
4500 SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT);
4501 SDValue InEltIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset);
4503 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT,
4504 CastVal, IdxOffset);
4506 NewVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, NVT,
4507 NewVec, Elt, InEltIdx);
4510 Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewVec));
4513 case ISD::SCALAR_TO_VECTOR: {
4514 MVT EltVT = OVT.getVectorElementType();
4515 MVT NewEltVT = NVT.getVectorElementType();
4517 // Handle bitcasts to different vector type with the smae total bit size.
4519 // e.g. v2i64 = scalar_to_vector x:i64
4521 // concat_vectors (v2i32 bitcast x:i64), (v2i32 undef)
4524 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4525 SDValue Val = Node->getOperand(0);
4528 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val);
4529 SDValue Undef = DAG.getUNDEF(MidVT);
4531 SmallVector<SDValue, 8> NewElts;
4532 NewElts.push_back(CastVal);
4533 for (unsigned I = 1, NElts = OVT.getVectorNumElements(); I != NElts; ++I)
4534 NewElts.push_back(Undef);
4536 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewElts);
4537 SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat);
4538 Results.push_back(CvtVec);
4543 // Replace the original node with the legalized result.
4544 if (!Results.empty())
4545 ReplaceNode(Node, Results.data());
4548 /// This is the entry point for the file.
4549 void SelectionDAG::Legalize() {
4550 AssignTopologicalOrder();
4552 SmallPtrSet<SDNode *, 16> LegalizedNodes;
4553 SelectionDAGLegalize Legalizer(*this, LegalizedNodes);
4555 // Visit all the nodes. We start in topological order, so that we see
4556 // nodes with their original operands intact. Legalization can produce
4557 // new nodes which may themselves need to be legalized. Iterate until all
4558 // nodes have been legalized.
4560 bool AnyLegalized = false;
4561 for (auto NI = allnodes_end(); NI != allnodes_begin();) {
4565 if (N->use_empty() && N != getRoot().getNode()) {
4571 if (LegalizedNodes.insert(N).second) {
4572 AnyLegalized = true;
4573 Legalizer.LegalizeOp(N);
4575 if (N->use_empty() && N != getRoot().getNode()) {
4586 // Remove dead nodes now.
4590 bool SelectionDAG::LegalizeOp(SDNode *N,
4591 SmallSetVector<SDNode *, 16> &UpdatedNodes) {
4592 SmallPtrSet<SDNode *, 16> LegalizedNodes;
4593 SelectionDAGLegalize Legalizer(*this, LegalizedNodes, &UpdatedNodes);
4595 // Directly insert the node in question, and legalize it. This will recurse
4596 // as needed through operands.
4597 LegalizedNodes.insert(N);
4598 Legalizer.LegalizeOp(N);
4600 return LegalizedNodes.count(N);