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/ADT/SetVector.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/SmallSet.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineJumpTableInfo.h"
21 #include "llvm/CodeGen/SelectionDAG.h"
22 #include "llvm/CodeGen/SelectionDAGNodes.h"
23 #include "llvm/IR/CallingConv.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DebugInfo.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetFrameLowering.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetSubtargetInfo.h"
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, SDValue Idx,
98 SDValue ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, SDValue Idx,
101 /// Return a vector shuffle operation which
102 /// performs the same shuffe in terms of order or result bytes, but on a type
103 /// whose vector element type is narrower than the original shuffle type.
104 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
105 SDValue ShuffleWithNarrowerEltType(EVT NVT, EVT VT, const SDLoc &dl,
106 SDValue N1, SDValue N2,
107 ArrayRef<int> Mask) const;
109 bool LegalizeSetCCCondCode(EVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC,
110 bool &NeedInvert, const 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, const 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,
133 SDValue ExpandBUILD_VECTOR(SDNode *Node);
134 SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
135 void ExpandDYNAMIC_STACKALLOC(SDNode *Node,
136 SmallVectorImpl<SDValue> &Results);
137 void getSignAsIntValue(FloatSignAsInt &State, const SDLoc &DL,
138 SDValue Value) const;
139 SDValue modifySignAsInt(const FloatSignAsInt &State, const SDLoc &DL,
140 SDValue NewIntValue) const;
141 SDValue ExpandFCOPYSIGN(SDNode *Node) const;
142 SDValue ExpandFABS(SDNode *Node) const;
143 SDValue ExpandLegalINT_TO_FP(bool isSigned, SDValue LegalOp, EVT DestVT,
145 SDValue PromoteLegalINT_TO_FP(SDValue LegalOp, EVT DestVT, bool isSigned,
147 SDValue PromoteLegalFP_TO_INT(SDValue LegalOp, EVT DestVT, bool isSigned,
150 SDValue ExpandBITREVERSE(SDValue Op, const SDLoc &dl);
151 SDValue ExpandBSWAP(SDValue Op, const SDLoc &dl);
152 SDValue ExpandBitCount(unsigned Opc, SDValue Op, const SDLoc &dl);
154 SDValue ExpandExtractFromVectorThroughStack(SDValue Op);
155 SDValue ExpandInsertToVectorThroughStack(SDValue Op);
156 SDValue ExpandVectorBuildThroughStack(SDNode* Node);
158 SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP);
159 SDValue ExpandConstant(ConstantSDNode *CP);
161 // if ExpandNode returns false, LegalizeOp falls back to ConvertNodeToLibcall
162 bool ExpandNode(SDNode *Node);
163 void ConvertNodeToLibcall(SDNode *Node);
164 void PromoteNode(SDNode *Node);
167 // Node replacement helpers
168 void ReplacedNode(SDNode *N) {
169 LegalizedNodes.erase(N);
171 UpdatedNodes->insert(N);
173 void ReplaceNode(SDNode *Old, SDNode *New) {
174 DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
175 dbgs() << " with: "; New->dump(&DAG));
177 assert(Old->getNumValues() == New->getNumValues() &&
178 "Replacing one node with another that produces a different number "
180 DAG.ReplaceAllUsesWith(Old, New);
182 UpdatedNodes->insert(New);
185 void ReplaceNode(SDValue Old, SDValue New) {
186 DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
187 dbgs() << " with: "; New->dump(&DAG));
189 DAG.ReplaceAllUsesWith(Old, New);
191 UpdatedNodes->insert(New.getNode());
192 ReplacedNode(Old.getNode());
194 void ReplaceNode(SDNode *Old, const SDValue *New) {
195 DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG));
197 DAG.ReplaceAllUsesWith(Old, New);
198 for (unsigned i = 0, e = Old->getNumValues(); i != e; ++i) {
199 DEBUG(dbgs() << (i == 0 ? " with: "
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>
214 SDValue SelectionDAGLegalize::ShuffleWithNarrowerEltType(
215 EVT NVT, EVT VT, const SDLoc &dl, SDValue N1, SDValue N2,
216 ArrayRef<int> Mask) const {
217 unsigned NumMaskElts = VT.getVectorNumElements();
218 unsigned NumDestElts = NVT.getVectorNumElements();
219 unsigned NumEltsGrowth = NumDestElts / NumMaskElts;
221 assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
223 if (NumEltsGrowth == 1)
224 return DAG.getVectorShuffle(NVT, dl, N1, N2, Mask);
226 SmallVector<int, 8> NewMask;
227 for (unsigned i = 0; i != NumMaskElts; ++i) {
229 for (unsigned j = 0; j != NumEltsGrowth; ++j) {
231 NewMask.push_back(-1);
233 NewMask.push_back(Idx * NumEltsGrowth + j);
236 assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?");
237 assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?");
238 return DAG.getVectorShuffle(NVT, dl, N1, N2, NewMask);
241 /// Expands the ConstantFP node to an integer constant or
242 /// a load from the constant pool.
244 SelectionDAGLegalize::ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP) {
248 // If a FP immediate is precise when represented as a float and if the
249 // target can do an extending load from float to double, we put it into
250 // the constant pool as a float, even if it's is statically typed as a
251 // double. This shrinks FP constants and canonicalizes them for targets where
252 // an FP extending load is the same cost as a normal load (such as on the x87
253 // fp stack or PPC FP unit).
254 EVT VT = CFP->getValueType(0);
255 ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
257 assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion");
258 return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(), dl,
259 (VT == MVT::f64) ? MVT::i64 : MVT::i32);
262 APFloat APF = CFP->getValueAPF();
266 // We don't want to shrink SNaNs. Converting the SNaN back to its real type
267 // can cause it to be changed into a QNaN on some platforms (e.g. on SystemZ).
268 if (!APF.isSignaling()) {
269 while (SVT != MVT::f32 && SVT != MVT::f16) {
270 SVT = (MVT::SimpleValueType)(SVT.getSimpleVT().SimpleTy - 1);
271 if (ConstantFPSDNode::isValueValidForType(SVT, APF) &&
272 // Only do this if the target has a native EXTLOAD instruction from
274 TLI.isLoadExtLegal(ISD::EXTLOAD, OrigVT, SVT) &&
275 TLI.ShouldShrinkFPConstant(OrigVT)) {
276 Type *SType = SVT.getTypeForEVT(*DAG.getContext());
277 LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
285 DAG.getConstantPool(LLVMC, TLI.getPointerTy(DAG.getDataLayout()));
286 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
288 SDValue Result = DAG.getExtLoad(
289 ISD::EXTLOAD, dl, OrigVT, DAG.getEntryNode(), CPIdx,
290 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), VT,
294 SDValue Result = DAG.getLoad(
295 OrigVT, dl, DAG.getEntryNode(), CPIdx,
296 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Alignment);
300 /// Expands the Constant node to a load from the constant pool.
301 SDValue SelectionDAGLegalize::ExpandConstant(ConstantSDNode *CP) {
303 EVT VT = CP->getValueType(0);
304 SDValue CPIdx = DAG.getConstantPool(CP->getConstantIntValue(),
305 TLI.getPointerTy(DAG.getDataLayout()));
306 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
307 SDValue Result = DAG.getLoad(
308 VT, dl, DAG.getEntryNode(), CPIdx,
309 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Alignment);
313 /// Some target cannot handle a variable insertion index for the
314 /// INSERT_VECTOR_ELT instruction. In this case, it
315 /// is necessary to spill the vector being inserted into to memory, perform
316 /// the insert there, and then read the result back.
317 SDValue SelectionDAGLegalize::PerformInsertVectorEltInMemory(SDValue Vec,
325 // If the target doesn't support this, we have to spill the input vector
326 // to a temporary stack slot, update the element, then reload it. This is
327 // badness. We could also load the value into a vector register (either
328 // with a "move to register" or "extload into register" instruction, then
329 // permute it into place, if the idx is a constant and if the idx is
330 // supported by the target.
331 EVT VT = Tmp1.getValueType();
332 EVT EltVT = VT.getVectorElementType();
333 SDValue StackPtr = DAG.CreateStackTemporary(VT);
335 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
338 SDValue Ch = DAG.getStore(
339 DAG.getEntryNode(), dl, Tmp1, StackPtr,
340 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI));
342 SDValue StackPtr2 = TLI.getVectorElementPointer(DAG, StackPtr, VT, Tmp3);
344 // Store the scalar value.
345 Ch = DAG.getTruncStore(Ch, dl, Tmp2, StackPtr2, MachinePointerInfo(), EltVT);
346 // Load the updated vector.
347 return DAG.getLoad(VT, dl, Ch, StackPtr, MachinePointerInfo::getFixedStack(
348 DAG.getMachineFunction(), SPFI));
351 SDValue SelectionDAGLegalize::ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val,
354 if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) {
355 // SCALAR_TO_VECTOR requires that the type of the value being inserted
356 // match the element type of the vector being created, except for
357 // integers in which case the inserted value can be over width.
358 EVT EltVT = Vec.getValueType().getVectorElementType();
359 if (Val.getValueType() == EltVT ||
360 (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) {
361 SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
362 Vec.getValueType(), Val);
364 unsigned NumElts = Vec.getValueType().getVectorNumElements();
365 // We generate a shuffle of InVec and ScVec, so the shuffle mask
366 // should be 0,1,2,3,4,5... with the appropriate element replaced with
368 SmallVector<int, 8> ShufOps;
369 for (unsigned i = 0; i != NumElts; ++i)
370 ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts);
372 return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec, ShufOps);
375 return PerformInsertVectorEltInMemory(Vec, Val, Idx, dl);
378 SDValue SelectionDAGLegalize::OptimizeFloatStore(StoreSDNode* ST) {
379 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
380 // FIXME: We shouldn't do this for TargetConstantFP's.
381 // FIXME: move this to the DAG Combiner! Note that we can't regress due
382 // to phase ordering between legalized code and the dag combiner. This
383 // probably means that we need to integrate dag combiner and legalizer
385 // We generally can't do this one for long doubles.
386 SDValue Chain = ST->getChain();
387 SDValue Ptr = ST->getBasePtr();
388 unsigned Alignment = ST->getAlignment();
389 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
390 AAMDNodes AAInfo = ST->getAAInfo();
392 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
393 if (CFP->getValueType(0) == MVT::f32 &&
394 TLI.isTypeLegal(MVT::i32)) {
395 SDValue Con = DAG.getConstant(CFP->getValueAPF().
396 bitcastToAPInt().zextOrTrunc(32),
397 SDLoc(CFP), MVT::i32);
398 return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(), Alignment,
402 if (CFP->getValueType(0) == MVT::f64) {
403 // If this target supports 64-bit registers, do a single 64-bit store.
404 if (TLI.isTypeLegal(MVT::i64)) {
405 SDValue Con = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
406 zextOrTrunc(64), SDLoc(CFP), MVT::i64);
407 return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(),
408 Alignment, MMOFlags, AAInfo);
411 if (TLI.isTypeLegal(MVT::i32) && !ST->isVolatile()) {
412 // Otherwise, if the target supports 32-bit registers, use 2 32-bit
413 // stores. If the target supports neither 32- nor 64-bits, this
414 // xform is certainly not worth it.
415 const APInt &IntVal = CFP->getValueAPF().bitcastToAPInt();
416 SDValue Lo = DAG.getConstant(IntVal.trunc(32), dl, MVT::i32);
417 SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), dl, MVT::i32);
418 if (DAG.getDataLayout().isBigEndian())
421 Lo = DAG.getStore(Chain, dl, Lo, Ptr, ST->getPointerInfo(), Alignment,
423 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
424 DAG.getConstant(4, dl, Ptr.getValueType()));
425 Hi = DAG.getStore(Chain, dl, Hi, Ptr,
426 ST->getPointerInfo().getWithOffset(4),
427 MinAlign(Alignment, 4U), MMOFlags, AAInfo);
429 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
433 return SDValue(nullptr, 0);
436 void SelectionDAGLegalize::LegalizeStoreOps(SDNode *Node) {
437 StoreSDNode *ST = cast<StoreSDNode>(Node);
438 SDValue Chain = ST->getChain();
439 SDValue Ptr = ST->getBasePtr();
442 unsigned Alignment = ST->getAlignment();
443 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
444 AAMDNodes AAInfo = ST->getAAInfo();
446 if (!ST->isTruncatingStore()) {
447 if (SDNode *OptStore = OptimizeFloatStore(ST).getNode()) {
448 ReplaceNode(ST, OptStore);
453 SDValue Value = ST->getValue();
454 MVT VT = Value.getSimpleValueType();
455 switch (TLI.getOperationAction(ISD::STORE, VT)) {
456 default: llvm_unreachable("This action is not supported yet!");
457 case TargetLowering::Legal: {
458 // If this is an unaligned store and the target doesn't support it,
460 EVT MemVT = ST->getMemoryVT();
461 unsigned AS = ST->getAddressSpace();
462 unsigned Align = ST->getAlignment();
463 const DataLayout &DL = DAG.getDataLayout();
464 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Align)) {
465 SDValue Result = TLI.expandUnalignedStore(ST, DAG);
466 ReplaceNode(SDValue(ST, 0), Result);
470 case TargetLowering::Custom: {
471 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
472 if (Res && Res != SDValue(Node, 0))
473 ReplaceNode(SDValue(Node, 0), Res);
476 case TargetLowering::Promote: {
477 MVT NVT = TLI.getTypeToPromoteTo(ISD::STORE, VT);
478 assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
479 "Can only promote stores to same size type");
480 Value = DAG.getNode(ISD::BITCAST, dl, NVT, Value);
482 DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
483 Alignment, MMOFlags, AAInfo);
484 ReplaceNode(SDValue(Node, 0), Result);
491 SDValue Value = ST->getValue();
493 EVT StVT = ST->getMemoryVT();
494 unsigned StWidth = StVT.getSizeInBits();
495 auto &DL = DAG.getDataLayout();
497 if (StWidth != StVT.getStoreSizeInBits()) {
498 // Promote to a byte-sized store with upper bits zero if not
499 // storing an integral number of bytes. For example, promote
500 // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
501 EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
502 StVT.getStoreSizeInBits());
503 Value = DAG.getZeroExtendInReg(Value, dl, StVT);
505 DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), NVT,
506 Alignment, MMOFlags, AAInfo);
507 ReplaceNode(SDValue(Node, 0), Result);
508 } else if (StWidth & (StWidth - 1)) {
509 // If not storing a power-of-2 number of bits, expand as two stores.
510 assert(!StVT.isVector() && "Unsupported truncstore!");
511 unsigned RoundWidth = 1 << Log2_32(StWidth);
512 assert(RoundWidth < StWidth);
513 unsigned ExtraWidth = StWidth - RoundWidth;
514 assert(ExtraWidth < RoundWidth);
515 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
516 "Store size not an integral number of bytes!");
517 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
518 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
520 unsigned IncrementSize;
522 if (DL.isLittleEndian()) {
523 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
524 // Store the bottom RoundWidth bits.
525 Lo = DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
526 RoundVT, Alignment, MMOFlags, AAInfo);
528 // Store the remaining ExtraWidth bits.
529 IncrementSize = RoundWidth / 8;
530 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
531 DAG.getConstant(IncrementSize, dl,
532 Ptr.getValueType()));
534 ISD::SRL, dl, Value.getValueType(), Value,
535 DAG.getConstant(RoundWidth, dl,
536 TLI.getShiftAmountTy(Value.getValueType(), DL)));
537 Hi = DAG.getTruncStore(
539 ST->getPointerInfo().getWithOffset(IncrementSize), ExtraVT,
540 MinAlign(Alignment, IncrementSize), MMOFlags, AAInfo);
542 // Big endian - avoid unaligned stores.
543 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
544 // Store the top RoundWidth bits.
546 ISD::SRL, dl, Value.getValueType(), Value,
547 DAG.getConstant(ExtraWidth, dl,
548 TLI.getShiftAmountTy(Value.getValueType(), DL)));
549 Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr, ST->getPointerInfo(),
550 RoundVT, Alignment, MMOFlags, AAInfo);
552 // Store the remaining ExtraWidth bits.
553 IncrementSize = RoundWidth / 8;
554 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
555 DAG.getConstant(IncrementSize, dl,
556 Ptr.getValueType()));
557 Lo = DAG.getTruncStore(
558 Chain, dl, Value, Ptr,
559 ST->getPointerInfo().getWithOffset(IncrementSize), ExtraVT,
560 MinAlign(Alignment, IncrementSize), MMOFlags, AAInfo);
563 // The order of the stores doesn't matter.
564 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
565 ReplaceNode(SDValue(Node, 0), Result);
567 switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) {
568 default: llvm_unreachable("This action is not supported yet!");
569 case TargetLowering::Legal: {
570 EVT MemVT = ST->getMemoryVT();
571 unsigned AS = ST->getAddressSpace();
572 unsigned Align = ST->getAlignment();
573 // If this is an unaligned store and the target doesn't support it,
575 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Align)) {
576 SDValue Result = TLI.expandUnalignedStore(ST, DAG);
577 ReplaceNode(SDValue(ST, 0), Result);
581 case TargetLowering::Custom: {
582 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
583 if (Res && Res != SDValue(Node, 0))
584 ReplaceNode(SDValue(Node, 0), Res);
587 case TargetLowering::Expand:
588 assert(!StVT.isVector() &&
589 "Vector Stores are handled in LegalizeVectorOps");
591 // TRUNCSTORE:i16 i32 -> STORE i16
592 assert(TLI.isTypeLegal(StVT) &&
593 "Do not know how to expand this store!");
594 Value = DAG.getNode(ISD::TRUNCATE, dl, StVT, Value);
596 DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
597 Alignment, MMOFlags, AAInfo);
598 ReplaceNode(SDValue(Node, 0), Result);
605 void SelectionDAGLegalize::LegalizeLoadOps(SDNode *Node) {
606 LoadSDNode *LD = cast<LoadSDNode>(Node);
607 SDValue Chain = LD->getChain(); // The chain.
608 SDValue Ptr = LD->getBasePtr(); // The base pointer.
609 SDValue Value; // The value returned by the load op.
612 ISD::LoadExtType ExtType = LD->getExtensionType();
613 if (ExtType == ISD::NON_EXTLOAD) {
614 MVT VT = Node->getSimpleValueType(0);
615 SDValue RVal = SDValue(Node, 0);
616 SDValue RChain = SDValue(Node, 1);
618 switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
619 default: llvm_unreachable("This action is not supported yet!");
620 case TargetLowering::Legal: {
621 EVT MemVT = LD->getMemoryVT();
622 unsigned AS = LD->getAddressSpace();
623 unsigned Align = LD->getAlignment();
624 const DataLayout &DL = DAG.getDataLayout();
625 // If this is an unaligned load and the target doesn't support it,
627 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Align)) {
628 std::tie(RVal, RChain) = TLI.expandUnalignedLoad(LD, DAG);
632 case TargetLowering::Custom: {
633 if (SDValue Res = TLI.LowerOperation(RVal, DAG)) {
635 RChain = Res.getValue(1);
639 case TargetLowering::Promote: {
640 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
641 assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
642 "Can only promote loads to same size type");
644 SDValue Res = DAG.getLoad(NVT, dl, Chain, Ptr, LD->getMemOperand());
645 RVal = DAG.getNode(ISD::BITCAST, dl, VT, Res);
646 RChain = Res.getValue(1);
650 if (RChain.getNode() != Node) {
651 assert(RVal.getNode() != Node && "Load must be completely replaced");
652 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), RVal);
653 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), RChain);
655 UpdatedNodes->insert(RVal.getNode());
656 UpdatedNodes->insert(RChain.getNode());
663 EVT SrcVT = LD->getMemoryVT();
664 unsigned SrcWidth = SrcVT.getSizeInBits();
665 unsigned Alignment = LD->getAlignment();
666 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
667 AAMDNodes AAInfo = LD->getAAInfo();
669 if (SrcWidth != SrcVT.getStoreSizeInBits() &&
670 // Some targets pretend to have an i1 loading operation, and actually
671 // load an i8. This trick is correct for ZEXTLOAD because the top 7
672 // bits are guaranteed to be zero; it helps the optimizers understand
673 // that these bits are zero. It is also useful for EXTLOAD, since it
674 // tells the optimizers that those bits are undefined. It would be
675 // nice to have an effective generic way of getting these benefits...
676 // Until such a way is found, don't insist on promoting i1 here.
678 TLI.getLoadExtAction(ExtType, Node->getValueType(0), MVT::i1) ==
679 TargetLowering::Promote)) {
680 // Promote to a byte-sized load if not loading an integral number of
681 // bytes. For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
682 unsigned NewWidth = SrcVT.getStoreSizeInBits();
683 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), NewWidth);
686 // The extra bits are guaranteed to be zero, since we stored them that
687 // way. A zext load from NVT thus automatically gives zext from SrcVT.
689 ISD::LoadExtType NewExtType =
690 ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
693 DAG.getExtLoad(NewExtType, dl, Node->getValueType(0), Chain, Ptr,
694 LD->getPointerInfo(), NVT, Alignment, MMOFlags, AAInfo);
696 Ch = Result.getValue(1); // The chain.
698 if (ExtType == ISD::SEXTLOAD)
699 // Having the top bits zero doesn't help when sign extending.
700 Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
701 Result.getValueType(),
702 Result, DAG.getValueType(SrcVT));
703 else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
704 // All the top bits are guaranteed to be zero - inform the optimizers.
705 Result = DAG.getNode(ISD::AssertZext, dl,
706 Result.getValueType(), Result,
707 DAG.getValueType(SrcVT));
711 } else if (SrcWidth & (SrcWidth - 1)) {
712 // If not loading a power-of-2 number of bits, expand as two loads.
713 assert(!SrcVT.isVector() && "Unsupported extload!");
714 unsigned RoundWidth = 1 << Log2_32(SrcWidth);
715 assert(RoundWidth < SrcWidth);
716 unsigned ExtraWidth = SrcWidth - RoundWidth;
717 assert(ExtraWidth < RoundWidth);
718 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
719 "Load size not an integral number of bytes!");
720 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
721 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
723 unsigned IncrementSize;
724 auto &DL = DAG.getDataLayout();
726 if (DL.isLittleEndian()) {
727 // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
728 // Load the bottom RoundWidth bits.
729 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0), Chain, Ptr,
730 LD->getPointerInfo(), RoundVT, Alignment, MMOFlags,
733 // Load the remaining ExtraWidth bits.
734 IncrementSize = RoundWidth / 8;
735 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
736 DAG.getConstant(IncrementSize, dl,
737 Ptr.getValueType()));
738 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
739 LD->getPointerInfo().getWithOffset(IncrementSize),
740 ExtraVT, MinAlign(Alignment, IncrementSize), MMOFlags,
743 // Build a factor node to remember that this load is independent of
745 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
748 // Move the top bits to the right place.
750 ISD::SHL, dl, Hi.getValueType(), Hi,
751 DAG.getConstant(RoundWidth, dl,
752 TLI.getShiftAmountTy(Hi.getValueType(), DL)));
754 // Join the hi and lo parts.
755 Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
757 // Big endian - avoid unaligned loads.
758 // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
759 // Load the top RoundWidth bits.
760 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
761 LD->getPointerInfo(), RoundVT, Alignment, MMOFlags,
764 // Load the remaining ExtraWidth bits.
765 IncrementSize = RoundWidth / 8;
766 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
767 DAG.getConstant(IncrementSize, dl,
768 Ptr.getValueType()));
769 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0), Chain, Ptr,
770 LD->getPointerInfo().getWithOffset(IncrementSize),
771 ExtraVT, MinAlign(Alignment, IncrementSize), MMOFlags,
774 // Build a factor node to remember that this load is independent of
776 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
779 // Move the top bits to the right place.
781 ISD::SHL, dl, Hi.getValueType(), Hi,
782 DAG.getConstant(ExtraWidth, dl,
783 TLI.getShiftAmountTy(Hi.getValueType(), DL)));
785 // Join the hi and lo parts.
786 Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
791 bool isCustom = false;
792 switch (TLI.getLoadExtAction(ExtType, Node->getValueType(0),
793 SrcVT.getSimpleVT())) {
794 default: llvm_unreachable("This action is not supported yet!");
795 case TargetLowering::Custom:
798 case TargetLowering::Legal: {
799 Value = SDValue(Node, 0);
800 Chain = SDValue(Node, 1);
803 if (SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG)) {
805 Chain = Res.getValue(1);
808 // If this is an unaligned load and the target doesn't support it,
810 EVT MemVT = LD->getMemoryVT();
811 unsigned AS = LD->getAddressSpace();
812 unsigned Align = LD->getAlignment();
813 const DataLayout &DL = DAG.getDataLayout();
814 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Align)) {
815 std::tie(Value, Chain) = TLI.expandUnalignedLoad(LD, DAG);
820 case TargetLowering::Expand:
821 EVT DestVT = Node->getValueType(0);
822 if (!TLI.isLoadExtLegal(ISD::EXTLOAD, DestVT, SrcVT)) {
823 // If the source type is not legal, see if there is a legal extload to
824 // an intermediate type that we can then extend further.
825 EVT LoadVT = TLI.getRegisterType(SrcVT.getSimpleVT());
826 if (TLI.isTypeLegal(SrcVT) || // Same as SrcVT == LoadVT?
827 TLI.isLoadExtLegal(ExtType, LoadVT, SrcVT)) {
828 // If we are loading a legal type, this is a non-extload followed by a
830 ISD::LoadExtType MidExtType =
831 (LoadVT == SrcVT) ? ISD::NON_EXTLOAD : ExtType;
833 SDValue Load = DAG.getExtLoad(MidExtType, dl, LoadVT, Chain, Ptr,
834 SrcVT, LD->getMemOperand());
836 ISD::getExtForLoadExtType(SrcVT.isFloatingPoint(), ExtType);
837 Value = DAG.getNode(ExtendOp, dl, Node->getValueType(0), Load);
838 Chain = Load.getValue(1);
842 // Handle the special case of fp16 extloads. EXTLOAD doesn't have the
843 // normal undefined upper bits behavior to allow using an in-reg extend
844 // with the illegal FP type, so load as an integer and do the
845 // from-integer conversion.
846 if (SrcVT.getScalarType() == MVT::f16) {
847 EVT ISrcVT = SrcVT.changeTypeToInteger();
848 EVT IDestVT = DestVT.changeTypeToInteger();
849 EVT LoadVT = TLI.getRegisterType(IDestVT.getSimpleVT());
851 SDValue Result = DAG.getExtLoad(ISD::ZEXTLOAD, dl, LoadVT,
853 LD->getMemOperand());
854 Value = DAG.getNode(ISD::FP16_TO_FP, dl, DestVT, Result);
855 Chain = Result.getValue(1);
860 assert(!SrcVT.isVector() &&
861 "Vector Loads are handled in LegalizeVectorOps");
863 // FIXME: This does not work for vectors on most targets. Sign-
864 // and zero-extend operations are currently folded into extending
865 // loads, whether they are legal or not, and then we end up here
866 // without any support for legalizing them.
867 assert(ExtType != ISD::EXTLOAD &&
868 "EXTLOAD should always be supported!");
869 // Turn the unsupported load into an EXTLOAD followed by an
870 // explicit zero/sign extend inreg.
871 SDValue Result = DAG.getExtLoad(ISD::EXTLOAD, dl,
872 Node->getValueType(0),
874 LD->getMemOperand());
876 if (ExtType == ISD::SEXTLOAD)
877 ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
878 Result.getValueType(),
879 Result, DAG.getValueType(SrcVT));
881 ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT.getScalarType());
883 Chain = Result.getValue(1);
888 // Since loads produce two values, make sure to remember that we legalized
890 if (Chain.getNode() != Node) {
891 assert(Value.getNode() != Node && "Load must be completely replaced");
892 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Value);
893 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
895 UpdatedNodes->insert(Value.getNode());
896 UpdatedNodes->insert(Chain.getNode());
902 /// Return a legal replacement for the given operation, with all legal operands.
903 void SelectionDAGLegalize::LegalizeOp(SDNode *Node) {
904 DEBUG(dbgs() << "\nLegalizing: "; Node->dump(&DAG));
906 if (Node->getOpcode() == ISD::TargetConstant) // Allow illegal target nodes.
910 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
911 assert((TLI.getTypeAction(*DAG.getContext(), Node->getValueType(i)) ==
912 TargetLowering::TypeLegal ||
913 TLI.isTypeLegal(Node->getValueType(i))) &&
914 "Unexpected illegal type!");
916 for (const SDValue &Op : Node->op_values())
917 assert((TLI.getTypeAction(*DAG.getContext(), Op.getValueType()) ==
918 TargetLowering::TypeLegal ||
919 TLI.isTypeLegal(Op.getValueType()) ||
920 Op.getOpcode() == ISD::TargetConstant) &&
921 "Unexpected illegal type!");
924 // Figure out the correct action; the way to query this varies by opcode
925 TargetLowering::LegalizeAction Action = TargetLowering::Legal;
926 bool SimpleFinishLegalizing = true;
927 switch (Node->getOpcode()) {
928 case ISD::INTRINSIC_W_CHAIN:
929 case ISD::INTRINSIC_WO_CHAIN:
930 case ISD::INTRINSIC_VOID:
932 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
934 case ISD::GET_DYNAMIC_AREA_OFFSET:
935 Action = TLI.getOperationAction(Node->getOpcode(),
936 Node->getValueType(0));
939 Action = TLI.getOperationAction(Node->getOpcode(),
940 Node->getValueType(0));
941 if (Action != TargetLowering::Promote)
942 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
944 case ISD::FP_TO_FP16:
945 case ISD::SINT_TO_FP:
946 case ISD::UINT_TO_FP:
947 case ISD::EXTRACT_VECTOR_ELT:
948 Action = TLI.getOperationAction(Node->getOpcode(),
949 Node->getOperand(0).getValueType());
951 case ISD::FP_ROUND_INREG:
952 case ISD::SIGN_EXTEND_INREG: {
953 EVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT();
954 Action = TLI.getOperationAction(Node->getOpcode(), InnerType);
957 case ISD::ATOMIC_STORE: {
958 Action = TLI.getOperationAction(Node->getOpcode(),
959 Node->getOperand(2).getValueType());
965 unsigned CCOperand = Node->getOpcode() == ISD::SELECT_CC ? 4 :
966 Node->getOpcode() == ISD::SETCC ? 2 :
967 Node->getOpcode() == ISD::SETCCE ? 3 : 1;
968 unsigned CompareOperand = Node->getOpcode() == ISD::BR_CC ? 2 : 0;
969 MVT OpVT = Node->getOperand(CompareOperand).getSimpleValueType();
970 ISD::CondCode CCCode =
971 cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get();
972 Action = TLI.getCondCodeAction(CCCode, OpVT);
973 if (Action == TargetLowering::Legal) {
974 if (Node->getOpcode() == ISD::SELECT_CC)
975 Action = TLI.getOperationAction(Node->getOpcode(),
976 Node->getValueType(0));
978 Action = TLI.getOperationAction(Node->getOpcode(), OpVT);
984 // FIXME: Model these properly. LOAD and STORE are complicated, and
985 // STORE expects the unlegalized operand in some cases.
986 SimpleFinishLegalizing = false;
988 case ISD::CALLSEQ_START:
989 case ISD::CALLSEQ_END:
990 // FIXME: This shouldn't be necessary. These nodes have special properties
991 // dealing with the recursive nature of legalization. Removing this
992 // special case should be done as part of making LegalizeDAG non-recursive.
993 SimpleFinishLegalizing = false;
995 case ISD::EXTRACT_ELEMENT:
996 case ISD::FLT_ROUNDS_:
998 case ISD::MERGE_VALUES:
1000 case ISD::FRAME_TO_ARGS_OFFSET:
1001 case ISD::EH_DWARF_CFA:
1002 case ISD::EH_SJLJ_SETJMP:
1003 case ISD::EH_SJLJ_LONGJMP:
1004 case ISD::EH_SJLJ_SETUP_DISPATCH:
1005 // These operations lie about being legal: when they claim to be legal,
1006 // they should actually be expanded.
1007 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1008 if (Action == TargetLowering::Legal)
1009 Action = TargetLowering::Expand;
1011 case ISD::INIT_TRAMPOLINE:
1012 case ISD::ADJUST_TRAMPOLINE:
1013 case ISD::FRAMEADDR:
1014 case ISD::RETURNADDR:
1015 case ISD::ADDROFRETURNADDR:
1016 // These operations lie about being legal: when they claim to be legal,
1017 // they should actually be custom-lowered.
1018 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1019 if (Action == TargetLowering::Legal)
1020 Action = TargetLowering::Custom;
1022 case ISD::READCYCLECOUNTER:
1023 // READCYCLECOUNTER returns an i64, even if type legalization might have
1024 // expanded that to several smaller types.
1025 Action = TLI.getOperationAction(Node->getOpcode(), MVT::i64);
1027 case ISD::READ_REGISTER:
1028 case ISD::WRITE_REGISTER:
1029 // Named register is legal in the DAG, but blocked by register name
1030 // selection if not implemented by target (to chose the correct register)
1031 // They'll be converted to Copy(To/From)Reg.
1032 Action = TargetLowering::Legal;
1034 case ISD::DEBUGTRAP:
1035 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1036 if (Action == TargetLowering::Expand) {
1037 // replace ISD::DEBUGTRAP with ISD::TRAP
1039 NewVal = DAG.getNode(ISD::TRAP, SDLoc(Node), Node->getVTList(),
1040 Node->getOperand(0));
1041 ReplaceNode(Node, NewVal.getNode());
1042 LegalizeOp(NewVal.getNode());
1048 if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
1049 Action = TargetLowering::Legal;
1051 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1056 if (SimpleFinishLegalizing) {
1057 SDNode *NewNode = Node;
1058 switch (Node->getOpcode()) {
1065 // Legalizing shifts/rotates requires adjusting the shift amount
1066 // to the appropriate width.
1067 SDValue Op0 = Node->getOperand(0);
1068 SDValue Op1 = Node->getOperand(1);
1069 if (!Op1.getValueType().isVector()) {
1070 SDValue SAO = DAG.getShiftAmountOperand(Op0.getValueType(), Op1);
1071 // The getShiftAmountOperand() may create a new operand node or
1072 // return the existing one. If new operand is created we need
1073 // to update the parent node.
1074 // Do not try to legalize SAO here! It will be automatically legalized
1075 // in the next round.
1077 NewNode = DAG.UpdateNodeOperands(Node, Op0, SAO);
1081 case ISD::SRL_PARTS:
1082 case ISD::SRA_PARTS:
1083 case ISD::SHL_PARTS: {
1084 // Legalizing shifts/rotates requires adjusting the shift amount
1085 // to the appropriate width.
1086 SDValue Op0 = Node->getOperand(0);
1087 SDValue Op1 = Node->getOperand(1);
1088 SDValue Op2 = Node->getOperand(2);
1089 if (!Op2.getValueType().isVector()) {
1090 SDValue SAO = DAG.getShiftAmountOperand(Op0.getValueType(), Op2);
1091 // The getShiftAmountOperand() may create a new operand node or
1092 // return the existing one. If new operand is created we need
1093 // to update the parent node.
1095 NewNode = DAG.UpdateNodeOperands(Node, Op0, Op1, SAO);
1101 if (NewNode != Node) {
1102 ReplaceNode(Node, NewNode);
1106 case TargetLowering::Legal:
1108 case TargetLowering::Custom: {
1109 // FIXME: The handling for custom lowering with multiple results is
1111 if (SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG)) {
1112 if (!(Res.getNode() != Node || Res.getResNo() != 0))
1115 if (Node->getNumValues() == 1) {
1116 // We can just directly replace this node with the lowered value.
1117 ReplaceNode(SDValue(Node, 0), Res);
1121 SmallVector<SDValue, 8> ResultVals;
1122 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
1123 ResultVals.push_back(Res.getValue(i));
1124 ReplaceNode(Node, ResultVals.data());
1129 case TargetLowering::Expand:
1130 if (ExpandNode(Node))
1133 case TargetLowering::LibCall:
1134 ConvertNodeToLibcall(Node);
1136 case TargetLowering::Promote:
1142 switch (Node->getOpcode()) {
1149 llvm_unreachable("Do not know how to legalize this operator!");
1151 case ISD::CALLSEQ_START:
1152 case ISD::CALLSEQ_END:
1155 return LegalizeLoadOps(Node);
1158 return LegalizeStoreOps(Node);
1163 SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
1164 SDValue Vec = Op.getOperand(0);
1165 SDValue Idx = Op.getOperand(1);
1168 // Before we generate a new store to a temporary stack slot, see if there is
1169 // already one that we can use. There often is because when we scalarize
1170 // vector operations (using SelectionDAG::UnrollVectorOp for example) a whole
1171 // series of EXTRACT_VECTOR_ELT nodes are generated, one for each element in
1172 // the vector. If all are expanded here, we don't want one store per vector
1175 // Caches for hasPredecessorHelper
1176 SmallPtrSet<const SDNode *, 32> Visited;
1177 SmallVector<const SDNode *, 16> Worklist;
1178 Worklist.push_back(Idx.getNode());
1179 SDValue StackPtr, Ch;
1180 for (SDNode::use_iterator UI = Vec.getNode()->use_begin(),
1181 UE = Vec.getNode()->use_end(); UI != UE; ++UI) {
1183 if (StoreSDNode *ST = dyn_cast<StoreSDNode>(User)) {
1184 if (ST->isIndexed() || ST->isTruncatingStore() ||
1185 ST->getValue() != Vec)
1188 // Make sure that nothing else could have stored into the destination of
1190 if (!ST->getChain().reachesChainWithoutSideEffects(DAG.getEntryNode()))
1193 // If the index is dependent on the store we will introduce a cycle when
1194 // creating the load (the load uses the index, and by replacing the chain
1195 // we will make the index dependent on the load). Also, the store might be
1196 // dependent on the extractelement and introduce a cycle when creating
1198 if (SDNode::hasPredecessorHelper(ST, Visited, Worklist) ||
1199 ST->hasPredecessor(Op.getNode()))
1202 StackPtr = ST->getBasePtr();
1203 Ch = SDValue(ST, 0);
1208 EVT VecVT = Vec.getValueType();
1210 if (!Ch.getNode()) {
1211 // Store the value to a temporary stack slot, then LOAD the returned part.
1212 StackPtr = DAG.CreateStackTemporary(VecVT);
1213 Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr,
1214 MachinePointerInfo());
1217 StackPtr = TLI.getVectorElementPointer(DAG, StackPtr, VecVT, Idx);
1221 if (Op.getValueType().isVector())
1223 DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, MachinePointerInfo());
1225 NewLoad = DAG.getExtLoad(ISD::EXTLOAD, dl, Op.getValueType(), Ch, StackPtr,
1226 MachinePointerInfo(),
1227 VecVT.getVectorElementType());
1229 // Replace the chain going out of the store, by the one out of the load.
1230 DAG.ReplaceAllUsesOfValueWith(Ch, SDValue(NewLoad.getNode(), 1));
1232 // We introduced a cycle though, so update the loads operands, making sure
1233 // to use the original store's chain as an incoming chain.
1234 SmallVector<SDValue, 6> NewLoadOperands(NewLoad->op_begin(),
1236 NewLoadOperands[0] = Ch;
1238 SDValue(DAG.UpdateNodeOperands(NewLoad.getNode(), NewLoadOperands), 0);
1242 SDValue SelectionDAGLegalize::ExpandInsertToVectorThroughStack(SDValue Op) {
1243 assert(Op.getValueType().isVector() && "Non-vector insert subvector!");
1245 SDValue Vec = Op.getOperand(0);
1246 SDValue Part = Op.getOperand(1);
1247 SDValue Idx = Op.getOperand(2);
1250 // Store the value to a temporary stack slot, then LOAD the returned part.
1251 EVT VecVT = Vec.getValueType();
1252 SDValue StackPtr = DAG.CreateStackTemporary(VecVT);
1253 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
1254 MachinePointerInfo PtrInfo =
1255 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
1257 // First store the whole vector.
1258 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, PtrInfo);
1260 // Then store the inserted part.
1261 SDValue SubStackPtr = TLI.getVectorElementPointer(DAG, StackPtr, VecVT, Idx);
1263 // Store the subvector.
1264 Ch = DAG.getStore(Ch, dl, Part, SubStackPtr, MachinePointerInfo());
1266 // Finally, load the updated vector.
1267 return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, PtrInfo);
1270 SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) {
1271 // We can't handle this case efficiently. Allocate a sufficiently
1272 // aligned object on the stack, store each element into it, then load
1273 // the result as a vector.
1274 // Create the stack frame object.
1275 EVT VT = Node->getValueType(0);
1276 EVT EltVT = VT.getVectorElementType();
1278 SDValue FIPtr = DAG.CreateStackTemporary(VT);
1279 int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
1280 MachinePointerInfo PtrInfo =
1281 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
1283 // Emit a store of each element to the stack slot.
1284 SmallVector<SDValue, 8> Stores;
1285 unsigned TypeByteSize = EltVT.getSizeInBits() / 8;
1286 // Store (in the right endianness) the elements to memory.
1287 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1288 // Ignore undef elements.
1289 if (Node->getOperand(i).isUndef()) continue;
1291 unsigned Offset = TypeByteSize*i;
1293 SDValue Idx = DAG.getConstant(Offset, dl, FIPtr.getValueType());
1294 Idx = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, Idx);
1296 // If the destination vector element type is narrower than the source
1297 // element type, only store the bits necessary.
1298 if (EltVT.bitsLT(Node->getOperand(i).getValueType().getScalarType())) {
1299 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
1300 Node->getOperand(i), Idx,
1301 PtrInfo.getWithOffset(Offset), EltVT));
1303 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, Node->getOperand(i),
1304 Idx, PtrInfo.getWithOffset(Offset)));
1308 if (!Stores.empty()) // Not all undef elements?
1309 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
1311 StoreChain = DAG.getEntryNode();
1313 // Result is a load from the stack slot.
1314 return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo);
1318 /// Keeps track of state when getting the sign of a floating-point value as an
1320 struct FloatSignAsInt {
1325 MachinePointerInfo IntPointerInfo;
1326 MachinePointerInfo FloatPointerInfo;
1333 /// Bitcast a floating-point value to an integer value. Only bitcast the part
1334 /// containing the sign bit if the target has no integer value capable of
1335 /// holding all bits of the floating-point value.
1336 void SelectionDAGLegalize::getSignAsIntValue(FloatSignAsInt &State,
1338 SDValue Value) const {
1339 EVT FloatVT = Value.getValueType();
1340 unsigned NumBits = FloatVT.getSizeInBits();
1341 State.FloatVT = FloatVT;
1342 EVT IVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
1343 // Convert to an integer of the same size.
1344 if (TLI.isTypeLegal(IVT)) {
1345 State.IntValue = DAG.getNode(ISD::BITCAST, DL, IVT, Value);
1346 State.SignMask = APInt::getSignMask(NumBits);
1347 State.SignBit = NumBits - 1;
1351 auto &DataLayout = DAG.getDataLayout();
1352 // Store the float to memory, then load the sign part out as an integer.
1353 MVT LoadTy = TLI.getRegisterType(*DAG.getContext(), MVT::i8);
1354 // First create a temporary that is aligned for both the load and store.
1355 SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy);
1356 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
1357 // Then store the float to it.
1358 State.FloatPtr = StackPtr;
1359 MachineFunction &MF = DAG.getMachineFunction();
1360 State.FloatPointerInfo = MachinePointerInfo::getFixedStack(MF, FI);
1361 State.Chain = DAG.getStore(DAG.getEntryNode(), DL, Value, State.FloatPtr,
1362 State.FloatPointerInfo);
1365 if (DataLayout.isBigEndian()) {
1366 assert(FloatVT.isByteSized() && "Unsupported floating point type!");
1367 // Load out a legal integer with the same sign bit as the float.
1369 State.IntPointerInfo = State.FloatPointerInfo;
1371 // Advance the pointer so that the loaded byte will contain the sign bit.
1372 unsigned ByteOffset = (FloatVT.getSizeInBits() / 8) - 1;
1373 IntPtr = DAG.getNode(ISD::ADD, DL, StackPtr.getValueType(), StackPtr,
1374 DAG.getConstant(ByteOffset, DL, StackPtr.getValueType()));
1375 State.IntPointerInfo = MachinePointerInfo::getFixedStack(MF, FI,
1379 State.IntPtr = IntPtr;
1380 State.IntValue = DAG.getExtLoad(ISD::EXTLOAD, DL, LoadTy, State.Chain, IntPtr,
1381 State.IntPointerInfo, MVT::i8);
1382 State.SignMask = APInt::getOneBitSet(LoadTy.getSizeInBits(), 7);
1386 /// Replace the integer value produced by getSignAsIntValue() with a new value
1387 /// and cast the result back to a floating-point type.
1388 SDValue SelectionDAGLegalize::modifySignAsInt(const FloatSignAsInt &State,
1390 SDValue NewIntValue) const {
1392 return DAG.getNode(ISD::BITCAST, DL, State.FloatVT, NewIntValue);
1394 // Override the part containing the sign bit in the value stored on the stack.
1395 SDValue Chain = DAG.getTruncStore(State.Chain, DL, NewIntValue, State.IntPtr,
1396 State.IntPointerInfo, MVT::i8);
1397 return DAG.getLoad(State.FloatVT, DL, Chain, State.FloatPtr,
1398 State.FloatPointerInfo);
1401 SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode *Node) const {
1403 SDValue Mag = Node->getOperand(0);
1404 SDValue Sign = Node->getOperand(1);
1406 // Get sign bit into an integer value.
1407 FloatSignAsInt SignAsInt;
1408 getSignAsIntValue(SignAsInt, DL, Sign);
1410 EVT IntVT = SignAsInt.IntValue.getValueType();
1411 SDValue SignMask = DAG.getConstant(SignAsInt.SignMask, DL, IntVT);
1412 SDValue SignBit = DAG.getNode(ISD::AND, DL, IntVT, SignAsInt.IntValue,
1415 // If FABS is legal transform FCOPYSIGN(x, y) => sign(x) ? -FABS(x) : FABS(X)
1416 EVT FloatVT = Mag.getValueType();
1417 if (TLI.isOperationLegalOrCustom(ISD::FABS, FloatVT) &&
1418 TLI.isOperationLegalOrCustom(ISD::FNEG, FloatVT)) {
1419 SDValue AbsValue = DAG.getNode(ISD::FABS, DL, FloatVT, Mag);
1420 SDValue NegValue = DAG.getNode(ISD::FNEG, DL, FloatVT, AbsValue);
1421 SDValue Cond = DAG.getSetCC(DL, getSetCCResultType(IntVT), SignBit,
1422 DAG.getConstant(0, DL, IntVT), ISD::SETNE);
1423 return DAG.getSelect(DL, FloatVT, Cond, NegValue, AbsValue);
1426 // Transform Mag value to integer, and clear the sign bit.
1427 FloatSignAsInt MagAsInt;
1428 getSignAsIntValue(MagAsInt, DL, Mag);
1429 EVT MagVT = MagAsInt.IntValue.getValueType();
1430 SDValue ClearSignMask = DAG.getConstant(~MagAsInt.SignMask, DL, MagVT);
1431 SDValue ClearedSign = DAG.getNode(ISD::AND, DL, MagVT, MagAsInt.IntValue,
1434 // Get the signbit at the right position for MagAsInt.
1435 int ShiftAmount = SignAsInt.SignBit - MagAsInt.SignBit;
1436 if (SignBit.getValueSizeInBits() > ClearedSign.getValueSizeInBits()) {
1437 if (ShiftAmount > 0) {
1438 SDValue ShiftCnst = DAG.getConstant(ShiftAmount, DL, IntVT);
1439 SignBit = DAG.getNode(ISD::SRL, DL, IntVT, SignBit, ShiftCnst);
1440 } else if (ShiftAmount < 0) {
1441 SDValue ShiftCnst = DAG.getConstant(-ShiftAmount, DL, IntVT);
1442 SignBit = DAG.getNode(ISD::SHL, DL, IntVT, SignBit, ShiftCnst);
1444 SignBit = DAG.getNode(ISD::TRUNCATE, DL, MagVT, SignBit);
1445 } else if (SignBit.getValueSizeInBits() < ClearedSign.getValueSizeInBits()) {
1446 SignBit = DAG.getNode(ISD::ZERO_EXTEND, DL, MagVT, SignBit);
1447 if (ShiftAmount > 0) {
1448 SDValue ShiftCnst = DAG.getConstant(ShiftAmount, DL, MagVT);
1449 SignBit = DAG.getNode(ISD::SRL, DL, MagVT, SignBit, ShiftCnst);
1450 } else if (ShiftAmount < 0) {
1451 SDValue ShiftCnst = DAG.getConstant(-ShiftAmount, DL, MagVT);
1452 SignBit = DAG.getNode(ISD::SHL, DL, MagVT, SignBit, ShiftCnst);
1456 // Store the part with the modified sign and convert back to float.
1457 SDValue CopiedSign = DAG.getNode(ISD::OR, DL, MagVT, ClearedSign, SignBit);
1458 return modifySignAsInt(MagAsInt, DL, CopiedSign);
1461 SDValue SelectionDAGLegalize::ExpandFABS(SDNode *Node) const {
1463 SDValue Value = Node->getOperand(0);
1465 // Transform FABS(x) => FCOPYSIGN(x, 0.0) if FCOPYSIGN is legal.
1466 EVT FloatVT = Value.getValueType();
1467 if (TLI.isOperationLegalOrCustom(ISD::FCOPYSIGN, FloatVT)) {
1468 SDValue Zero = DAG.getConstantFP(0.0, DL, FloatVT);
1469 return DAG.getNode(ISD::FCOPYSIGN, DL, FloatVT, Value, Zero);
1472 // Transform value to integer, clear the sign bit and transform back.
1473 FloatSignAsInt ValueAsInt;
1474 getSignAsIntValue(ValueAsInt, DL, Value);
1475 EVT IntVT = ValueAsInt.IntValue.getValueType();
1476 SDValue ClearSignMask = DAG.getConstant(~ValueAsInt.SignMask, DL, IntVT);
1477 SDValue ClearedSign = DAG.getNode(ISD::AND, DL, IntVT, ValueAsInt.IntValue,
1479 return modifySignAsInt(ValueAsInt, DL, ClearedSign);
1482 void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node,
1483 SmallVectorImpl<SDValue> &Results) {
1484 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1485 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1486 " not tell us which reg is the stack pointer!");
1488 EVT VT = Node->getValueType(0);
1489 SDValue Tmp1 = SDValue(Node, 0);
1490 SDValue Tmp2 = SDValue(Node, 1);
1491 SDValue Tmp3 = Node->getOperand(2);
1492 SDValue Chain = Tmp1.getOperand(0);
1494 // Chain the dynamic stack allocation so that it doesn't modify the stack
1495 // pointer when other instructions are using the stack.
1496 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true), dl);
1498 SDValue Size = Tmp2.getOperand(1);
1499 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
1500 Chain = SP.getValue(1);
1501 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
1502 unsigned StackAlign =
1503 DAG.getSubtarget().getFrameLowering()->getStackAlignment();
1504 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
1505 if (Align > StackAlign)
1506 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
1507 DAG.getConstant(-(uint64_t)Align, dl, VT));
1508 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
1510 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
1511 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
1513 Results.push_back(Tmp1);
1514 Results.push_back(Tmp2);
1517 /// Legalize a SETCC with given LHS and RHS and condition code CC on the current
1520 /// If the SETCC has been legalized using AND / OR, then the legalized node
1521 /// will be stored in LHS. RHS and CC will be set to SDValue(). NeedInvert
1522 /// will be set to false.
1524 /// If the SETCC has been legalized by using getSetCCSwappedOperands(),
1525 /// then the values of LHS and RHS will be swapped, CC will be set to the
1526 /// new condition, and NeedInvert will be set to false.
1528 /// If the SETCC has been legalized using the inverse condcode, then LHS and
1529 /// RHS will be unchanged, CC will set to the inverted condcode, and NeedInvert
1530 /// will be set to true. The caller must invert the result of the SETCC with
1531 /// SelectionDAG::getLogicalNOT() or take equivalent action to swap the effect
1532 /// of a true/false result.
1534 /// \returns true if the SetCC has been legalized, false if it hasn't.
1535 bool SelectionDAGLegalize::LegalizeSetCCCondCode(EVT VT, SDValue &LHS,
1536 SDValue &RHS, SDValue &CC,
1539 MVT OpVT = LHS.getSimpleValueType();
1540 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
1542 switch (TLI.getCondCodeAction(CCCode, OpVT)) {
1543 default: llvm_unreachable("Unknown condition code action!");
1544 case TargetLowering::Legal:
1547 case TargetLowering::Expand: {
1548 ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode);
1549 if (TLI.isCondCodeLegal(InvCC, OpVT)) {
1550 std::swap(LHS, RHS);
1551 CC = DAG.getCondCode(InvCC);
1554 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
1557 default: llvm_unreachable("Don't know how to expand this condition!");
1559 assert(TLI.getCondCodeAction(ISD::SETOEQ, OpVT)
1560 == TargetLowering::Legal
1561 && "If SETO is expanded, SETOEQ must be legal!");
1562 CC1 = ISD::SETOEQ; CC2 = ISD::SETOEQ; Opc = ISD::AND; break;
1564 assert(TLI.getCondCodeAction(ISD::SETUNE, OpVT)
1565 == TargetLowering::Legal
1566 && "If SETUO is expanded, SETUNE must be legal!");
1567 CC1 = ISD::SETUNE; CC2 = ISD::SETUNE; Opc = ISD::OR; break;
1580 // If we are floating point, assign and break, otherwise fall through.
1581 if (!OpVT.isInteger()) {
1582 // We can use the 4th bit to tell if we are the unordered
1583 // or ordered version of the opcode.
1584 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
1585 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
1586 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
1589 // Fallthrough if we are unsigned integer.
1595 // We only support using the inverted operation, which is computed above
1596 // and not a different manner of supporting expanding these cases.
1597 llvm_unreachable("Don't know how to expand this condition!");
1600 // Try inverting the result of the inverse condition.
1601 InvCC = CCCode == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ;
1602 if (TLI.isCondCodeLegal(InvCC, OpVT)) {
1603 CC = DAG.getCondCode(InvCC);
1607 // If inverting the condition didn't work then we have no means to expand
1609 llvm_unreachable("Don't know how to expand this condition!");
1612 SDValue SetCC1, SetCC2;
1613 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
1614 // If we aren't the ordered or unorder operation,
1615 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
1616 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1);
1617 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2);
1619 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
1620 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1);
1621 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2);
1623 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
1632 /// Emit a store/load combination to the stack. This stores
1633 /// SrcOp to a stack slot of type SlotVT, truncating it if needed. It then does
1634 /// a load from the stack slot to DestVT, extending it if needed.
1635 /// The resultant code need not be legal.
1636 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp, EVT SlotVT,
1637 EVT DestVT, const SDLoc &dl) {
1638 // Create the stack frame object.
1639 unsigned SrcAlign = DAG.getDataLayout().getPrefTypeAlignment(
1640 SrcOp.getValueType().getTypeForEVT(*DAG.getContext()));
1641 SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign);
1643 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
1644 int SPFI = StackPtrFI->getIndex();
1645 MachinePointerInfo PtrInfo =
1646 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
1648 unsigned SrcSize = SrcOp.getValueSizeInBits();
1649 unsigned SlotSize = SlotVT.getSizeInBits();
1650 unsigned DestSize = DestVT.getSizeInBits();
1651 Type *DestType = DestVT.getTypeForEVT(*DAG.getContext());
1652 unsigned DestAlign = DAG.getDataLayout().getPrefTypeAlignment(DestType);
1654 // Emit a store to the stack slot. Use a truncstore if the input value is
1655 // later than DestVT.
1658 if (SrcSize > SlotSize)
1659 Store = DAG.getTruncStore(DAG.getEntryNode(), dl, SrcOp, FIPtr, PtrInfo,
1662 assert(SrcSize == SlotSize && "Invalid store");
1664 DAG.getStore(DAG.getEntryNode(), dl, SrcOp, FIPtr, PtrInfo, SrcAlign);
1667 // Result is a load from the stack slot.
1668 if (SlotSize == DestSize)
1669 return DAG.getLoad(DestVT, dl, Store, FIPtr, PtrInfo, DestAlign);
1671 assert(SlotSize < DestSize && "Unknown extension!");
1672 return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr, PtrInfo, SlotVT,
1676 SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
1678 // Create a vector sized/aligned stack slot, store the value to element #0,
1679 // then load the whole vector back out.
1680 SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
1682 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
1683 int SPFI = StackPtrFI->getIndex();
1685 SDValue Ch = DAG.getTruncStore(
1686 DAG.getEntryNode(), dl, Node->getOperand(0), StackPtr,
1687 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI),
1688 Node->getValueType(0).getVectorElementType());
1690 Node->getValueType(0), dl, Ch, StackPtr,
1691 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI));
1695 ExpandBVWithShuffles(SDNode *Node, SelectionDAG &DAG,
1696 const TargetLowering &TLI, SDValue &Res) {
1697 unsigned NumElems = Node->getNumOperands();
1699 EVT VT = Node->getValueType(0);
1701 // Try to group the scalars into pairs, shuffle the pairs together, then
1702 // shuffle the pairs of pairs together, etc. until the vector has
1703 // been built. This will work only if all of the necessary shuffle masks
1706 // We do this in two phases; first to check the legality of the shuffles,
1707 // and next, assuming that all shuffles are legal, to create the new nodes.
1708 for (int Phase = 0; Phase < 2; ++Phase) {
1709 SmallVector<std::pair<SDValue, SmallVector<int, 16> >, 16> IntermedVals,
1711 for (unsigned i = 0; i < NumElems; ++i) {
1712 SDValue V = Node->getOperand(i);
1718 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, V);
1719 IntermedVals.push_back(std::make_pair(Vec, SmallVector<int, 16>(1, i)));
1722 while (IntermedVals.size() > 2) {
1723 NewIntermedVals.clear();
1724 for (unsigned i = 0, e = (IntermedVals.size() & ~1u); i < e; i += 2) {
1725 // This vector and the next vector are shuffled together (simply to
1726 // append the one to the other).
1727 SmallVector<int, 16> ShuffleVec(NumElems, -1);
1729 SmallVector<int, 16> FinalIndices;
1730 FinalIndices.reserve(IntermedVals[i].second.size() +
1731 IntermedVals[i+1].second.size());
1734 for (unsigned j = 0, f = IntermedVals[i].second.size(); j != f;
1737 FinalIndices.push_back(IntermedVals[i].second[j]);
1739 for (unsigned j = 0, f = IntermedVals[i+1].second.size(); j != f;
1741 ShuffleVec[k] = NumElems + j;
1742 FinalIndices.push_back(IntermedVals[i+1].second[j]);
1747 Shuffle = DAG.getVectorShuffle(VT, dl, IntermedVals[i].first,
1748 IntermedVals[i+1].first,
1750 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
1752 NewIntermedVals.push_back(
1753 std::make_pair(Shuffle, std::move(FinalIndices)));
1756 // If we had an odd number of defined values, then append the last
1757 // element to the array of new vectors.
1758 if ((IntermedVals.size() & 1) != 0)
1759 NewIntermedVals.push_back(IntermedVals.back());
1761 IntermedVals.swap(NewIntermedVals);
1764 assert(IntermedVals.size() <= 2 && IntermedVals.size() > 0 &&
1765 "Invalid number of intermediate vectors");
1766 SDValue Vec1 = IntermedVals[0].first;
1768 if (IntermedVals.size() > 1)
1769 Vec2 = IntermedVals[1].first;
1771 Vec2 = DAG.getUNDEF(VT);
1773 SmallVector<int, 16> ShuffleVec(NumElems, -1);
1774 for (unsigned i = 0, e = IntermedVals[0].second.size(); i != e; ++i)
1775 ShuffleVec[IntermedVals[0].second[i]] = i;
1776 for (unsigned i = 0, e = IntermedVals[1].second.size(); i != e; ++i)
1777 ShuffleVec[IntermedVals[1].second[i]] = NumElems + i;
1780 Res = DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec);
1781 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
1788 /// Expand a BUILD_VECTOR node on targets that don't
1789 /// support the operation, but do support the resultant vector type.
1790 SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
1791 unsigned NumElems = Node->getNumOperands();
1792 SDValue Value1, Value2;
1794 EVT VT = Node->getValueType(0);
1795 EVT OpVT = Node->getOperand(0).getValueType();
1796 EVT EltVT = VT.getVectorElementType();
1798 // If the only non-undef value is the low element, turn this into a
1799 // SCALAR_TO_VECTOR node. If this is { X, X, X, X }, determine X.
1800 bool isOnlyLowElement = true;
1801 bool MoreThanTwoValues = false;
1802 bool isConstant = true;
1803 for (unsigned i = 0; i < NumElems; ++i) {
1804 SDValue V = Node->getOperand(i);
1808 isOnlyLowElement = false;
1809 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
1812 if (!Value1.getNode()) {
1814 } else if (!Value2.getNode()) {
1817 } else if (V != Value1 && V != Value2) {
1818 MoreThanTwoValues = true;
1822 if (!Value1.getNode())
1823 return DAG.getUNDEF(VT);
1825 if (isOnlyLowElement)
1826 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
1828 // If all elements are constants, create a load from the constant pool.
1830 SmallVector<Constant*, 16> CV;
1831 for (unsigned i = 0, e = NumElems; i != e; ++i) {
1832 if (ConstantFPSDNode *V =
1833 dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
1834 CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
1835 } else if (ConstantSDNode *V =
1836 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
1838 CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
1840 // If OpVT and EltVT don't match, EltVT is not legal and the
1841 // element values have been promoted/truncated earlier. Undo this;
1842 // we don't want a v16i8 to become a v16i32 for example.
1843 const ConstantInt *CI = V->getConstantIntValue();
1844 CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()),
1845 CI->getZExtValue()));
1848 assert(Node->getOperand(i).isUndef());
1849 Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext());
1850 CV.push_back(UndefValue::get(OpNTy));
1853 Constant *CP = ConstantVector::get(CV);
1855 DAG.getConstantPool(CP, TLI.getPointerTy(DAG.getDataLayout()));
1856 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
1858 VT, dl, DAG.getEntryNode(), CPIdx,
1859 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
1863 SmallSet<SDValue, 16> DefinedValues;
1864 for (unsigned i = 0; i < NumElems; ++i) {
1865 if (Node->getOperand(i).isUndef())
1867 DefinedValues.insert(Node->getOperand(i));
1870 if (TLI.shouldExpandBuildVectorWithShuffles(VT, DefinedValues.size())) {
1871 if (!MoreThanTwoValues) {
1872 SmallVector<int, 8> ShuffleVec(NumElems, -1);
1873 for (unsigned i = 0; i < NumElems; ++i) {
1874 SDValue V = Node->getOperand(i);
1877 ShuffleVec[i] = V == Value1 ? 0 : NumElems;
1879 if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) {
1880 // Get the splatted value into the low element of a vector register.
1881 SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1);
1883 if (Value2.getNode())
1884 Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2);
1886 Vec2 = DAG.getUNDEF(VT);
1888 // Return shuffle(LowValVec, undef, <0,0,0,0>)
1889 return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec);
1893 if (ExpandBVWithShuffles(Node, DAG, TLI, Res))
1898 // Otherwise, we can't handle this case efficiently.
1899 return ExpandVectorBuildThroughStack(Node);
1902 // Expand a node into a call to a libcall. If the result value
1903 // does not fit into a register, return the lo part and set the hi part to the
1904 // by-reg argument. If it does fit into a single register, return the result
1905 // and leave the Hi part unset.
1906 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
1908 TargetLowering::ArgListTy Args;
1909 TargetLowering::ArgListEntry Entry;
1910 for (const SDValue &Op : Node->op_values()) {
1911 EVT ArgVT = Op.getValueType();
1912 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1915 Entry.IsSExt = isSigned;
1916 Entry.IsZExt = !isSigned;
1917 Args.push_back(Entry);
1919 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
1920 TLI.getPointerTy(DAG.getDataLayout()));
1922 Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
1924 // By default, the input chain to this libcall is the entry node of the
1925 // function. If the libcall is going to be emitted as a tail call then
1926 // TLI.isUsedByReturnOnly will change it to the right chain if the return
1927 // node which is being folded has a non-entry input chain.
1928 SDValue InChain = DAG.getEntryNode();
1930 // isTailCall may be true since the callee does not reference caller stack
1931 // frame. Check if it's in the right position and that the return types match.
1932 SDValue TCChain = InChain;
1933 const Function *F = DAG.getMachineFunction().getFunction();
1935 TLI.isInTailCallPosition(DAG, Node, TCChain) &&
1936 (RetTy == F->getReturnType() || F->getReturnType()->isVoidTy());
1940 TargetLowering::CallLoweringInfo CLI(DAG);
1941 CLI.setDebugLoc(SDLoc(Node))
1943 .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee,
1945 .setTailCall(isTailCall)
1946 .setSExtResult(isSigned)
1947 .setZExtResult(!isSigned);
1949 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
1951 if (!CallInfo.second.getNode())
1952 // It's a tailcall, return the chain (which is the DAG root).
1953 return DAG.getRoot();
1955 return CallInfo.first;
1958 /// Generate a libcall taking the given operands as arguments
1959 /// and returning a result of type RetVT.
1960 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, EVT RetVT,
1961 const SDValue *Ops, unsigned NumOps,
1962 bool isSigned, const SDLoc &dl) {
1963 TargetLowering::ArgListTy Args;
1964 Args.reserve(NumOps);
1966 TargetLowering::ArgListEntry Entry;
1967 for (unsigned i = 0; i != NumOps; ++i) {
1968 Entry.Node = Ops[i];
1969 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
1970 Entry.IsSExt = isSigned;
1971 Entry.IsZExt = !isSigned;
1972 Args.push_back(Entry);
1974 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
1975 TLI.getPointerTy(DAG.getDataLayout()));
1977 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
1979 TargetLowering::CallLoweringInfo CLI(DAG);
1981 .setChain(DAG.getEntryNode())
1982 .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee,
1984 .setSExtResult(isSigned)
1985 .setZExtResult(!isSigned);
1987 std::pair<SDValue,SDValue> CallInfo = TLI.LowerCallTo(CLI);
1989 return CallInfo.first;
1992 // Expand a node into a call to a libcall. Similar to
1993 // ExpandLibCall except that the first operand is the in-chain.
1994 std::pair<SDValue, SDValue>
1995 SelectionDAGLegalize::ExpandChainLibCall(RTLIB::Libcall LC,
1998 SDValue InChain = Node->getOperand(0);
2000 TargetLowering::ArgListTy Args;
2001 TargetLowering::ArgListEntry Entry;
2002 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) {
2003 EVT ArgVT = Node->getOperand(i).getValueType();
2004 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2005 Entry.Node = Node->getOperand(i);
2007 Entry.IsSExt = isSigned;
2008 Entry.IsZExt = !isSigned;
2009 Args.push_back(Entry);
2011 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2012 TLI.getPointerTy(DAG.getDataLayout()));
2014 Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
2016 TargetLowering::CallLoweringInfo CLI(DAG);
2017 CLI.setDebugLoc(SDLoc(Node))
2019 .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee,
2021 .setSExtResult(isSigned)
2022 .setZExtResult(!isSigned);
2024 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2029 SDValue SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
2030 RTLIB::Libcall Call_F32,
2031 RTLIB::Libcall Call_F64,
2032 RTLIB::Libcall Call_F80,
2033 RTLIB::Libcall Call_F128,
2034 RTLIB::Libcall Call_PPCF128) {
2036 switch (Node->getSimpleValueType(0).SimpleTy) {
2037 default: llvm_unreachable("Unexpected request for libcall!");
2038 case MVT::f32: LC = Call_F32; break;
2039 case MVT::f64: LC = Call_F64; break;
2040 case MVT::f80: LC = Call_F80; break;
2041 case MVT::f128: LC = Call_F128; break;
2042 case MVT::ppcf128: LC = Call_PPCF128; break;
2044 return ExpandLibCall(LC, Node, false);
2047 SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned,
2048 RTLIB::Libcall Call_I8,
2049 RTLIB::Libcall Call_I16,
2050 RTLIB::Libcall Call_I32,
2051 RTLIB::Libcall Call_I64,
2052 RTLIB::Libcall Call_I128) {
2054 switch (Node->getSimpleValueType(0).SimpleTy) {
2055 default: llvm_unreachable("Unexpected request for libcall!");
2056 case MVT::i8: LC = Call_I8; break;
2057 case MVT::i16: LC = Call_I16; break;
2058 case MVT::i32: LC = Call_I32; break;
2059 case MVT::i64: LC = Call_I64; break;
2060 case MVT::i128: LC = Call_I128; break;
2062 return ExpandLibCall(LC, Node, isSigned);
2065 /// Issue libcalls to __{u}divmod to compute div / rem pairs.
2067 SelectionDAGLegalize::ExpandDivRemLibCall(SDNode *Node,
2068 SmallVectorImpl<SDValue> &Results) {
2069 unsigned Opcode = Node->getOpcode();
2070 bool isSigned = Opcode == ISD::SDIVREM;
2073 switch (Node->getSimpleValueType(0).SimpleTy) {
2074 default: llvm_unreachable("Unexpected request for libcall!");
2075 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2076 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2077 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2078 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2079 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2082 // The input chain to this libcall is the entry node of the function.
2083 // Legalizing the call will automatically add the previous call to the
2085 SDValue InChain = DAG.getEntryNode();
2087 EVT RetVT = Node->getValueType(0);
2088 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2090 TargetLowering::ArgListTy Args;
2091 TargetLowering::ArgListEntry Entry;
2092 for (const SDValue &Op : Node->op_values()) {
2093 EVT ArgVT = Op.getValueType();
2094 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2097 Entry.IsSExt = isSigned;
2098 Entry.IsZExt = !isSigned;
2099 Args.push_back(Entry);
2102 // Also pass the return address of the remainder.
2103 SDValue FIPtr = DAG.CreateStackTemporary(RetVT);
2105 Entry.Ty = RetTy->getPointerTo();
2106 Entry.IsSExt = isSigned;
2107 Entry.IsZExt = !isSigned;
2108 Args.push_back(Entry);
2110 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2111 TLI.getPointerTy(DAG.getDataLayout()));
2114 TargetLowering::CallLoweringInfo CLI(DAG);
2117 .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee,
2119 .setSExtResult(isSigned)
2120 .setZExtResult(!isSigned);
2122 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2124 // Remainder is loaded back from the stack frame.
2126 DAG.getLoad(RetVT, dl, CallInfo.second, FIPtr, MachinePointerInfo());
2127 Results.push_back(CallInfo.first);
2128 Results.push_back(Rem);
2131 /// Return true if sincos libcall is available.
2132 static bool isSinCosLibcallAvailable(SDNode *Node, const TargetLowering &TLI) {
2134 switch (Node->getSimpleValueType(0).SimpleTy) {
2135 default: llvm_unreachable("Unexpected request for libcall!");
2136 case MVT::f32: LC = RTLIB::SINCOS_F32; break;
2137 case MVT::f64: LC = RTLIB::SINCOS_F64; break;
2138 case MVT::f80: LC = RTLIB::SINCOS_F80; break;
2139 case MVT::f128: LC = RTLIB::SINCOS_F128; break;
2140 case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break;
2142 return TLI.getLibcallName(LC) != nullptr;
2145 /// Return true if sincos libcall is available and can be used to combine sin
2147 static bool canCombineSinCosLibcall(SDNode *Node, const TargetLowering &TLI,
2148 const TargetMachine &TM) {
2149 if (!isSinCosLibcallAvailable(Node, TLI))
2151 // GNU sin/cos functions set errno while sincos does not. Therefore
2152 // combining sin and cos is only safe if unsafe-fpmath is enabled.
2153 if (TM.getTargetTriple().isGNUEnvironment() && !TM.Options.UnsafeFPMath)
2158 /// Only issue sincos libcall if both sin and cos are needed.
2159 static bool useSinCos(SDNode *Node) {
2160 unsigned OtherOpcode = Node->getOpcode() == ISD::FSIN
2161 ? ISD::FCOS : ISD::FSIN;
2163 SDValue Op0 = Node->getOperand(0);
2164 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2165 UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2169 // The other user might have been turned into sincos already.
2170 if (User->getOpcode() == OtherOpcode || User->getOpcode() == ISD::FSINCOS)
2176 /// Issue libcalls to sincos to compute sin / cos pairs.
2178 SelectionDAGLegalize::ExpandSinCosLibCall(SDNode *Node,
2179 SmallVectorImpl<SDValue> &Results) {
2181 switch (Node->getSimpleValueType(0).SimpleTy) {
2182 default: llvm_unreachable("Unexpected request for libcall!");
2183 case MVT::f32: LC = RTLIB::SINCOS_F32; break;
2184 case MVT::f64: LC = RTLIB::SINCOS_F64; break;
2185 case MVT::f80: LC = RTLIB::SINCOS_F80; break;
2186 case MVT::f128: LC = RTLIB::SINCOS_F128; break;
2187 case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break;
2190 // The input chain to this libcall is the entry node of the function.
2191 // Legalizing the call will automatically add the previous call to the
2193 SDValue InChain = DAG.getEntryNode();
2195 EVT RetVT = Node->getValueType(0);
2196 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2198 TargetLowering::ArgListTy Args;
2199 TargetLowering::ArgListEntry Entry;
2201 // Pass the argument.
2202 Entry.Node = Node->getOperand(0);
2204 Entry.IsSExt = false;
2205 Entry.IsZExt = false;
2206 Args.push_back(Entry);
2208 // Pass the return address of sin.
2209 SDValue SinPtr = DAG.CreateStackTemporary(RetVT);
2210 Entry.Node = SinPtr;
2211 Entry.Ty = RetTy->getPointerTo();
2212 Entry.IsSExt = false;
2213 Entry.IsZExt = false;
2214 Args.push_back(Entry);
2216 // Also pass the return address of the cos.
2217 SDValue CosPtr = DAG.CreateStackTemporary(RetVT);
2218 Entry.Node = CosPtr;
2219 Entry.Ty = RetTy->getPointerTo();
2220 Entry.IsSExt = false;
2221 Entry.IsZExt = false;
2222 Args.push_back(Entry);
2224 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2225 TLI.getPointerTy(DAG.getDataLayout()));
2228 TargetLowering::CallLoweringInfo CLI(DAG);
2229 CLI.setDebugLoc(dl).setChain(InChain).setLibCallee(
2230 TLI.getLibcallCallingConv(LC), Type::getVoidTy(*DAG.getContext()), Callee,
2233 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2236 DAG.getLoad(RetVT, dl, CallInfo.second, SinPtr, MachinePointerInfo()));
2238 DAG.getLoad(RetVT, dl, CallInfo.second, CosPtr, MachinePointerInfo()));
2241 /// This function is responsible for legalizing a
2242 /// INT_TO_FP operation of the specified operand when the target requests that
2243 /// we expand it. At this point, we know that the result and operand types are
2244 /// legal for the target.
2245 SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned, SDValue Op0,
2248 // TODO: Should any fast-math-flags be set for the created nodes?
2250 if (Op0.getValueType() == MVT::i32 && TLI.isTypeLegal(MVT::f64)) {
2251 // simple 32-bit [signed|unsigned] integer to float/double expansion
2253 // Get the stack frame index of a 8 byte buffer.
2254 SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
2256 // word offset constant for Hi/Lo address computation
2257 SDValue WordOff = DAG.getConstant(sizeof(int), dl,
2258 StackSlot.getValueType());
2259 // set up Hi and Lo (into buffer) address based on endian
2260 SDValue Hi = StackSlot;
2261 SDValue Lo = DAG.getNode(ISD::ADD, dl, StackSlot.getValueType(),
2262 StackSlot, WordOff);
2263 if (DAG.getDataLayout().isLittleEndian())
2266 // if signed map to unsigned space
2269 // constant used to invert sign bit (signed to unsigned mapping)
2270 SDValue SignBit = DAG.getConstant(0x80000000u, dl, MVT::i32);
2271 Op0Mapped = DAG.getNode(ISD::XOR, dl, MVT::i32, Op0, SignBit);
2275 // store the lo of the constructed double - based on integer input
2276 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op0Mapped, Lo,
2277 MachinePointerInfo());
2278 // initial hi portion of constructed double
2279 SDValue InitialHi = DAG.getConstant(0x43300000u, dl, MVT::i32);
2280 // store the hi of the constructed double - biased exponent
2282 DAG.getStore(Store1, dl, InitialHi, Hi, MachinePointerInfo());
2283 // load the constructed double
2285 DAG.getLoad(MVT::f64, dl, Store2, StackSlot, MachinePointerInfo());
2286 // FP constant to bias correct the final result
2287 SDValue Bias = DAG.getConstantFP(isSigned ?
2288 BitsToDouble(0x4330000080000000ULL) :
2289 BitsToDouble(0x4330000000000000ULL),
2291 // subtract the bias
2292 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
2295 // handle final rounding
2296 if (DestVT == MVT::f64) {
2299 } else if (DestVT.bitsLT(MVT::f64)) {
2300 Result = DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
2301 DAG.getIntPtrConstant(0, dl));
2302 } else if (DestVT.bitsGT(MVT::f64)) {
2303 Result = DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
2307 assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
2308 // Code below here assumes !isSigned without checking again.
2310 // Implementation of unsigned i64 to f64 following the algorithm in
2311 // __floatundidf in compiler_rt. This implementation has the advantage
2312 // of performing rounding correctly, both in the default rounding mode
2313 // and in all alternate rounding modes.
2314 // TODO: Generalize this for use with other types.
2315 if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f64) {
2317 DAG.getConstant(UINT64_C(0x4330000000000000), dl, MVT::i64);
2318 SDValue TwoP84PlusTwoP52 =
2319 DAG.getConstantFP(BitsToDouble(UINT64_C(0x4530000000100000)), dl,
2322 DAG.getConstant(UINT64_C(0x4530000000000000), dl, MVT::i64);
2324 SDValue Lo = DAG.getZeroExtendInReg(Op0, dl, MVT::i32);
2325 SDValue Hi = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0,
2326 DAG.getConstant(32, dl, MVT::i64));
2327 SDValue LoOr = DAG.getNode(ISD::OR, dl, MVT::i64, Lo, TwoP52);
2328 SDValue HiOr = DAG.getNode(ISD::OR, dl, MVT::i64, Hi, TwoP84);
2329 SDValue LoFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, LoOr);
2330 SDValue HiFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, HiOr);
2331 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, MVT::f64, HiFlt,
2333 return DAG.getNode(ISD::FADD, dl, MVT::f64, LoFlt, HiSub);
2336 // Implementation of unsigned i64 to f32.
2337 // TODO: Generalize this for use with other types.
2338 if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f32) {
2339 // For unsigned conversions, convert them to signed conversions using the
2340 // algorithm from the x86_64 __floatundidf in compiler_rt.
2342 SDValue Fast = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Op0);
2344 SDValue ShiftConst = DAG.getConstant(
2345 1, dl, TLI.getShiftAmountTy(Op0.getValueType(), DAG.getDataLayout()));
2346 SDValue Shr = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0, ShiftConst);
2347 SDValue AndConst = DAG.getConstant(1, dl, MVT::i64);
2348 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0, AndConst);
2349 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And, Shr);
2351 SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Or);
2352 SDValue Slow = DAG.getNode(ISD::FADD, dl, MVT::f32, SignCvt, SignCvt);
2354 // TODO: This really should be implemented using a branch rather than a
2355 // select. We happen to get lucky and machinesink does the right
2356 // thing most of the time. This would be a good candidate for a
2357 //pseudo-op, or, even better, for whole-function isel.
2358 SDValue SignBitTest = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
2359 Op0, DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
2360 return DAG.getSelect(dl, MVT::f32, SignBitTest, Slow, Fast);
2363 // Otherwise, implement the fully general conversion.
2365 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
2366 DAG.getConstant(UINT64_C(0xfffffffffffff800), dl, MVT::i64));
2367 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And,
2368 DAG.getConstant(UINT64_C(0x800), dl, MVT::i64));
2369 SDValue And2 = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
2370 DAG.getConstant(UINT64_C(0x7ff), dl, MVT::i64));
2371 SDValue Ne = DAG.getSetCC(dl, getSetCCResultType(MVT::i64), And2,
2372 DAG.getConstant(UINT64_C(0), dl, MVT::i64),
2374 SDValue Sel = DAG.getSelect(dl, MVT::i64, Ne, Or, Op0);
2375 SDValue Ge = DAG.getSetCC(dl, getSetCCResultType(MVT::i64), Op0,
2376 DAG.getConstant(UINT64_C(0x0020000000000000), dl,
2379 SDValue Sel2 = DAG.getSelect(dl, MVT::i64, Ge, Sel, Op0);
2380 EVT SHVT = TLI.getShiftAmountTy(Sel2.getValueType(), DAG.getDataLayout());
2382 SDValue Sh = DAG.getNode(ISD::SRL, dl, MVT::i64, Sel2,
2383 DAG.getConstant(32, dl, SHVT));
2384 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sh);
2385 SDValue Fcvt = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Trunc);
2387 DAG.getConstantFP(BitsToDouble(UINT64_C(0x41f0000000000000)), dl,
2389 SDValue Fmul = DAG.getNode(ISD::FMUL, dl, MVT::f64, TwoP32, Fcvt);
2390 SDValue Lo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sel2);
2391 SDValue Fcvt2 = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Lo);
2392 SDValue Fadd = DAG.getNode(ISD::FADD, dl, MVT::f64, Fmul, Fcvt2);
2393 return DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Fadd,
2394 DAG.getIntPtrConstant(0, dl));
2397 SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2399 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(Op0.getValueType()),
2401 DAG.getConstant(0, dl, Op0.getValueType()),
2403 SDValue Zero = DAG.getIntPtrConstant(0, dl),
2404 Four = DAG.getIntPtrConstant(4, dl);
2405 SDValue CstOffset = DAG.getSelect(dl, Zero.getValueType(),
2406 SignSet, Four, Zero);
2408 // If the sign bit of the integer is set, the large number will be treated
2409 // as a negative number. To counteract this, the dynamic code adds an
2410 // offset depending on the data type.
2412 switch (Op0.getSimpleValueType().SimpleTy) {
2413 default: llvm_unreachable("Unsupported integer type!");
2414 case MVT::i8 : FF = 0x43800000ULL; break; // 2^8 (as a float)
2415 case MVT::i16: FF = 0x47800000ULL; break; // 2^16 (as a float)
2416 case MVT::i32: FF = 0x4F800000ULL; break; // 2^32 (as a float)
2417 case MVT::i64: FF = 0x5F800000ULL; break; // 2^64 (as a float)
2419 if (DAG.getDataLayout().isLittleEndian())
2421 Constant *FudgeFactor = ConstantInt::get(
2422 Type::getInt64Ty(*DAG.getContext()), FF);
2425 DAG.getConstantPool(FudgeFactor, TLI.getPointerTy(DAG.getDataLayout()));
2426 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
2427 CPIdx = DAG.getNode(ISD::ADD, dl, CPIdx.getValueType(), CPIdx, CstOffset);
2428 Alignment = std::min(Alignment, 4u);
2430 if (DestVT == MVT::f32)
2431 FudgeInReg = DAG.getLoad(
2432 MVT::f32, dl, DAG.getEntryNode(), CPIdx,
2433 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2436 SDValue Load = DAG.getExtLoad(
2437 ISD::EXTLOAD, dl, DestVT, DAG.getEntryNode(), CPIdx,
2438 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
2440 HandleSDNode Handle(Load);
2441 LegalizeOp(Load.getNode());
2442 FudgeInReg = Handle.getValue();
2445 return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
2448 /// This function is responsible for legalizing a
2449 /// *INT_TO_FP operation of the specified operand when the target requests that
2450 /// we promote it. At this point, we know that the result and operand types are
2451 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
2452 /// operation that takes a larger input.
2453 SDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp, EVT DestVT,
2456 // First step, figure out the appropriate *INT_TO_FP operation to use.
2457 EVT NewInTy = LegalOp.getValueType();
2459 unsigned OpToUse = 0;
2461 // Scan for the appropriate larger type to use.
2463 NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1);
2464 assert(NewInTy.isInteger() && "Ran out of possibilities!");
2466 // If the target supports SINT_TO_FP of this type, use it.
2467 if (TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, NewInTy)) {
2468 OpToUse = ISD::SINT_TO_FP;
2471 if (isSigned) continue;
2473 // If the target supports UINT_TO_FP of this type, use it.
2474 if (TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, NewInTy)) {
2475 OpToUse = ISD::UINT_TO_FP;
2479 // Otherwise, try a larger type.
2482 // Okay, we found the operation and type to use. Zero extend our input to the
2483 // desired type then run the operation on it.
2484 return DAG.getNode(OpToUse, dl, DestVT,
2485 DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
2486 dl, NewInTy, LegalOp));
2489 /// This function is responsible for legalizing a
2490 /// FP_TO_*INT operation of the specified operand when the target requests that
2491 /// we promote it. At this point, we know that the result and operand types are
2492 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
2493 /// operation that returns a larger result.
2494 SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp, EVT DestVT,
2497 // First step, figure out the appropriate FP_TO*INT operation to use.
2498 EVT NewOutTy = DestVT;
2500 unsigned OpToUse = 0;
2502 // Scan for the appropriate larger type to use.
2504 NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1);
2505 assert(NewOutTy.isInteger() && "Ran out of possibilities!");
2507 // A larger signed type can hold all unsigned values of the requested type,
2508 // so using FP_TO_SINT is valid
2509 if (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NewOutTy)) {
2510 OpToUse = ISD::FP_TO_SINT;
2514 // However, if the value may be < 0.0, we *must* use some FP_TO_SINT.
2515 if (!isSigned && TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NewOutTy)) {
2516 OpToUse = ISD::FP_TO_UINT;
2520 // Otherwise, try a larger type.
2524 // Okay, we found the operation and type to use.
2525 SDValue Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
2527 // Truncate the result of the extended FP_TO_*INT operation to the desired
2529 return DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
2532 /// Legalize a BITREVERSE scalar/vector operation as a series of mask + shifts.
2533 SDValue SelectionDAGLegalize::ExpandBITREVERSE(SDValue Op, const SDLoc &dl) {
2534 EVT VT = Op.getValueType();
2535 EVT SHVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
2536 unsigned Sz = VT.getScalarSizeInBits();
2538 SDValue Tmp, Tmp2, Tmp3;
2540 // If we can, perform BSWAP first and then the mask+swap the i4, then i2
2541 // and finally the i1 pairs.
2542 // TODO: We can easily support i4/i2 legal types if any target ever does.
2543 if (Sz >= 8 && isPowerOf2_32(Sz)) {
2544 // Create the masks - repeating the pattern every byte.
2545 APInt MaskHi4(Sz, 0), MaskHi2(Sz, 0), MaskHi1(Sz, 0);
2546 APInt MaskLo4(Sz, 0), MaskLo2(Sz, 0), MaskLo1(Sz, 0);
2547 for (unsigned J = 0; J != Sz; J += 8) {
2548 MaskHi4 = MaskHi4 | (0xF0ull << J);
2549 MaskLo4 = MaskLo4 | (0x0Full << J);
2550 MaskHi2 = MaskHi2 | (0xCCull << J);
2551 MaskLo2 = MaskLo2 | (0x33ull << J);
2552 MaskHi1 = MaskHi1 | (0xAAull << J);
2553 MaskLo1 = MaskLo1 | (0x55ull << J);
2556 // BSWAP if the type is wider than a single byte.
2557 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op);
2559 // swap i4: ((V & 0xF0) >> 4) | ((V & 0x0F) << 4)
2560 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi4, dl, VT));
2561 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo4, dl, VT));
2562 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(4, dl, VT));
2563 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, VT));
2564 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
2566 // swap i2: ((V & 0xCC) >> 2) | ((V & 0x33) << 2)
2567 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi2, dl, VT));
2568 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo2, dl, VT));
2569 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(2, dl, VT));
2570 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, VT));
2571 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
2573 // swap i1: ((V & 0xAA) >> 1) | ((V & 0x55) << 1)
2574 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi1, dl, VT));
2575 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo1, dl, VT));
2576 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(1, dl, VT));
2577 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, VT));
2578 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
2582 Tmp = DAG.getConstant(0, dl, VT);
2583 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) {
2586 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT));
2589 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT));
2592 Shift = Shift.shl(J);
2593 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT));
2594 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2);
2600 /// Open code the operations for BSWAP of the specified operation.
2601 SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op, const SDLoc &dl) {
2602 EVT VT = Op.getValueType();
2603 EVT SHVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
2604 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
2605 switch (VT.getSimpleVT().getScalarType().SimpleTy) {
2606 default: llvm_unreachable("Unhandled Expand type in BSWAP!");
2608 Tmp2 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2609 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2610 return DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
2612 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
2613 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2614 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2615 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
2616 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
2617 DAG.getConstant(0xFF0000, dl, VT));
2618 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
2619 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2620 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2621 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2623 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
2624 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
2625 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
2626 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2627 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2628 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
2629 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
2630 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
2631 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7,
2632 DAG.getConstant(255ULL<<48, dl, VT));
2633 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6,
2634 DAG.getConstant(255ULL<<40, dl, VT));
2635 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5,
2636 DAG.getConstant(255ULL<<32, dl, VT));
2637 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
2638 DAG.getConstant(255ULL<<24, dl, VT));
2639 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
2640 DAG.getConstant(255ULL<<16, dl, VT));
2641 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
2642 DAG.getConstant(255ULL<<8 , dl, VT));
2643 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
2644 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
2645 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2646 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2647 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
2648 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2649 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
2653 /// Expand the specified bitcount instruction into operations.
2654 SDValue SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDValue Op,
2657 default: llvm_unreachable("Cannot expand this yet!");
2659 EVT VT = Op.getValueType();
2660 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
2661 unsigned Len = VT.getSizeInBits();
2663 assert(VT.isInteger() && Len <= 128 && Len % 8 == 0 &&
2664 "CTPOP not implemented for this type.");
2666 // This is the "best" algorithm from
2667 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
2669 SDValue Mask55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)),
2671 SDValue Mask33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)),
2673 SDValue Mask0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)),
2675 SDValue Mask01 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)),
2678 // v = v - ((v >> 1) & 0x55555555...)
2679 Op = DAG.getNode(ISD::SUB, dl, VT, Op,
2680 DAG.getNode(ISD::AND, dl, VT,
2681 DAG.getNode(ISD::SRL, dl, VT, Op,
2682 DAG.getConstant(1, dl, ShVT)),
2684 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
2685 Op = DAG.getNode(ISD::ADD, dl, VT,
2686 DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
2687 DAG.getNode(ISD::AND, dl, VT,
2688 DAG.getNode(ISD::SRL, dl, VT, Op,
2689 DAG.getConstant(2, dl, ShVT)),
2691 // v = (v + (v >> 4)) & 0x0F0F0F0F...
2692 Op = DAG.getNode(ISD::AND, dl, VT,
2693 DAG.getNode(ISD::ADD, dl, VT, Op,
2694 DAG.getNode(ISD::SRL, dl, VT, Op,
2695 DAG.getConstant(4, dl, ShVT))),
2697 // v = (v * 0x01010101...) >> (Len - 8)
2698 Op = DAG.getNode(ISD::SRL, dl, VT,
2699 DAG.getNode(ISD::MUL, dl, VT, Op, Mask01),
2700 DAG.getConstant(Len - 8, dl, ShVT));
2704 case ISD::CTLZ_ZERO_UNDEF:
2705 // This trivially expands to CTLZ.
2706 return DAG.getNode(ISD::CTLZ, dl, Op.getValueType(), Op);
2708 EVT VT = Op.getValueType();
2709 unsigned len = VT.getSizeInBits();
2711 if (TLI.isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) {
2712 EVT SetCCVT = getSetCCResultType(VT);
2713 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op);
2714 SDValue Zero = DAG.getConstant(0, dl, VT);
2715 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
2716 return DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero,
2717 DAG.getConstant(len, dl, VT), CTLZ);
2720 // for now, we do this:
2721 // x = x | (x >> 1);
2722 // x = x | (x >> 2);
2724 // x = x | (x >>16);
2725 // x = x | (x >>32); // for 64-bit input
2726 // return popcount(~x);
2728 // Ref: "Hacker's Delight" by Henry Warren
2729 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
2730 for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
2731 SDValue Tmp3 = DAG.getConstant(1ULL << i, dl, ShVT);
2732 Op = DAG.getNode(ISD::OR, dl, VT, Op,
2733 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3));
2735 Op = DAG.getNOT(dl, Op, VT);
2736 return DAG.getNode(ISD::CTPOP, dl, VT, Op);
2738 case ISD::CTTZ_ZERO_UNDEF:
2739 // This trivially expands to CTTZ.
2740 return DAG.getNode(ISD::CTTZ, dl, Op.getValueType(), Op);
2742 // for now, we use: { return popcount(~x & (x - 1)); }
2743 // unless the target has ctlz but not ctpop, in which case we use:
2744 // { return 32 - nlz(~x & (x-1)); }
2745 // Ref: "Hacker's Delight" by Henry Warren
2746 EVT VT = Op.getValueType();
2747 SDValue Tmp3 = DAG.getNode(ISD::AND, dl, VT,
2748 DAG.getNOT(dl, Op, VT),
2749 DAG.getNode(ISD::SUB, dl, VT, Op,
2750 DAG.getConstant(1, dl, VT)));
2751 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
2752 if (!TLI.isOperationLegalOrCustom(ISD::CTPOP, VT) &&
2753 TLI.isOperationLegalOrCustom(ISD::CTLZ, VT))
2754 return DAG.getNode(ISD::SUB, dl, VT,
2755 DAG.getConstant(VT.getSizeInBits(), dl, VT),
2756 DAG.getNode(ISD::CTLZ, dl, VT, Tmp3));
2757 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp3);
2762 bool SelectionDAGLegalize::ExpandNode(SDNode *Node) {
2763 SmallVector<SDValue, 8> Results;
2765 SDValue Tmp1, Tmp2, Tmp3, Tmp4;
2767 switch (Node->getOpcode()) {
2770 case ISD::CTLZ_ZERO_UNDEF:
2772 case ISD::CTTZ_ZERO_UNDEF:
2773 Tmp1 = ExpandBitCount(Node->getOpcode(), Node->getOperand(0), dl);
2774 Results.push_back(Tmp1);
2776 case ISD::BITREVERSE:
2777 Results.push_back(ExpandBITREVERSE(Node->getOperand(0), dl));
2780 Results.push_back(ExpandBSWAP(Node->getOperand(0), dl));
2782 case ISD::FRAMEADDR:
2783 case ISD::RETURNADDR:
2784 case ISD::FRAME_TO_ARGS_OFFSET:
2785 Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0)));
2787 case ISD::EH_DWARF_CFA: {
2788 SDValue CfaArg = DAG.getSExtOrTrunc(Node->getOperand(0), dl,
2789 TLI.getPointerTy(DAG.getDataLayout()));
2790 SDValue Offset = DAG.getNode(ISD::ADD, dl,
2791 CfaArg.getValueType(),
2792 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
2793 CfaArg.getValueType()),
2795 SDValue FA = DAG.getNode(
2796 ISD::FRAMEADDR, dl, TLI.getPointerTy(DAG.getDataLayout()),
2797 DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())));
2798 Results.push_back(DAG.getNode(ISD::ADD, dl, FA.getValueType(),
2802 case ISD::FLT_ROUNDS_:
2803 Results.push_back(DAG.getConstant(1, dl, Node->getValueType(0)));
2805 case ISD::EH_RETURN:
2809 case ISD::EH_SJLJ_LONGJMP:
2810 // If the target didn't expand these, there's nothing to do, so just
2811 // preserve the chain and be done.
2812 Results.push_back(Node->getOperand(0));
2814 case ISD::READCYCLECOUNTER:
2815 // If the target didn't expand this, just return 'zero' and preserve the
2817 Results.append(Node->getNumValues() - 1,
2818 DAG.getConstant(0, dl, Node->getValueType(0)));
2819 Results.push_back(Node->getOperand(0));
2821 case ISD::EH_SJLJ_SETJMP:
2822 // If the target didn't expand this, just return 'zero' and preserve the
2824 Results.push_back(DAG.getConstant(0, dl, MVT::i32));
2825 Results.push_back(Node->getOperand(0));
2827 case ISD::ATOMIC_LOAD: {
2828 // There is no libcall for atomic load; fake it with ATOMIC_CMP_SWAP.
2829 SDValue Zero = DAG.getConstant(0, dl, Node->getValueType(0));
2830 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
2831 SDValue Swap = DAG.getAtomicCmpSwap(
2832 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
2833 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
2834 cast<AtomicSDNode>(Node)->getMemOperand());
2835 Results.push_back(Swap.getValue(0));
2836 Results.push_back(Swap.getValue(1));
2839 case ISD::ATOMIC_STORE: {
2840 // There is no libcall for atomic store; fake it with ATOMIC_SWAP.
2841 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
2842 cast<AtomicSDNode>(Node)->getMemoryVT(),
2843 Node->getOperand(0),
2844 Node->getOperand(1), Node->getOperand(2),
2845 cast<AtomicSDNode>(Node)->getMemOperand());
2846 Results.push_back(Swap.getValue(1));
2849 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
2850 // Expanding an ATOMIC_CMP_SWAP_WITH_SUCCESS produces an ATOMIC_CMP_SWAP and
2851 // splits out the success value as a comparison. Expanding the resulting
2852 // ATOMIC_CMP_SWAP will produce a libcall.
2853 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
2854 SDValue Res = DAG.getAtomicCmpSwap(
2855 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
2856 Node->getOperand(0), Node->getOperand(1), Node->getOperand(2),
2857 Node->getOperand(3), cast<MemSDNode>(Node)->getMemOperand());
2859 SDValue ExtRes = Res;
2861 SDValue RHS = Node->getOperand(1);
2863 EVT AtomicType = cast<AtomicSDNode>(Node)->getMemoryVT();
2864 EVT OuterType = Node->getValueType(0);
2865 switch (TLI.getExtendForAtomicOps()) {
2866 case ISD::SIGN_EXTEND:
2867 LHS = DAG.getNode(ISD::AssertSext, dl, OuterType, Res,
2868 DAG.getValueType(AtomicType));
2869 RHS = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, OuterType,
2870 Node->getOperand(2), DAG.getValueType(AtomicType));
2873 case ISD::ZERO_EXTEND:
2874 LHS = DAG.getNode(ISD::AssertZext, dl, OuterType, Res,
2875 DAG.getValueType(AtomicType));
2876 RHS = DAG.getNode(ISD::ZERO_EXTEND, dl, OuterType, Node->getOperand(2));
2879 case ISD::ANY_EXTEND:
2880 LHS = DAG.getZeroExtendInReg(Res, dl, AtomicType);
2881 RHS = DAG.getNode(ISD::ZERO_EXTEND, dl, OuterType, Node->getOperand(2));
2884 llvm_unreachable("Invalid atomic op extension");
2888 DAG.getSetCC(dl, Node->getValueType(1), LHS, RHS, ISD::SETEQ);
2890 Results.push_back(ExtRes.getValue(0));
2891 Results.push_back(Success);
2892 Results.push_back(Res.getValue(1));
2895 case ISD::DYNAMIC_STACKALLOC:
2896 ExpandDYNAMIC_STACKALLOC(Node, Results);
2898 case ISD::MERGE_VALUES:
2899 for (unsigned i = 0; i < Node->getNumValues(); i++)
2900 Results.push_back(Node->getOperand(i));
2903 EVT VT = Node->getValueType(0);
2905 Results.push_back(DAG.getConstant(0, dl, VT));
2907 assert(VT.isFloatingPoint() && "Unknown value type!");
2908 Results.push_back(DAG.getConstantFP(0, dl, VT));
2914 Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
2915 Node->getValueType(0), dl);
2916 Results.push_back(Tmp1);
2918 case ISD::FP_EXTEND:
2919 Tmp1 = EmitStackConvert(Node->getOperand(0),
2920 Node->getOperand(0).getValueType(),
2921 Node->getValueType(0), dl);
2922 Results.push_back(Tmp1);
2924 case ISD::SIGN_EXTEND_INREG: {
2925 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2926 EVT VT = Node->getValueType(0);
2928 // An in-register sign-extend of a boolean is a negation:
2929 // 'true' (1) sign-extended is -1.
2930 // 'false' (0) sign-extended is 0.
2931 // However, we must mask the high bits of the source operand because the
2932 // SIGN_EXTEND_INREG does not guarantee that the high bits are already zero.
2934 // TODO: Do this for vectors too?
2935 if (ExtraVT.getSizeInBits() == 1) {
2936 SDValue One = DAG.getConstant(1, dl, VT);
2937 SDValue And = DAG.getNode(ISD::AND, dl, VT, Node->getOperand(0), One);
2938 SDValue Zero = DAG.getConstant(0, dl, VT);
2939 SDValue Neg = DAG.getNode(ISD::SUB, dl, VT, Zero, And);
2940 Results.push_back(Neg);
2944 // NOTE: we could fall back on load/store here too for targets without
2945 // SRA. However, it is doubtful that any exist.
2946 EVT ShiftAmountTy = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
2949 unsigned BitsDiff = VT.getScalarSizeInBits() -
2950 ExtraVT.getScalarSizeInBits();
2951 SDValue ShiftCst = DAG.getConstant(BitsDiff, dl, ShiftAmountTy);
2952 Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0),
2953 Node->getOperand(0), ShiftCst);
2954 Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst);
2955 Results.push_back(Tmp1);
2958 case ISD::FP_ROUND_INREG: {
2959 // The only way we can lower this is to turn it into a TRUNCSTORE,
2960 // EXTLOAD pair, targeting a temporary location (a stack slot).
2962 // NOTE: there is a choice here between constantly creating new stack
2963 // slots and always reusing the same one. We currently always create
2964 // new ones, as reuse may inhibit scheduling.
2965 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2966 Tmp1 = EmitStackConvert(Node->getOperand(0), ExtraVT,
2967 Node->getValueType(0), dl);
2968 Results.push_back(Tmp1);
2971 case ISD::SINT_TO_FP:
2972 case ISD::UINT_TO_FP:
2973 Tmp1 = ExpandLegalINT_TO_FP(Node->getOpcode() == ISD::SINT_TO_FP,
2974 Node->getOperand(0), Node->getValueType(0), dl);
2975 Results.push_back(Tmp1);
2977 case ISD::FP_TO_SINT:
2978 if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG))
2979 Results.push_back(Tmp1);
2981 case ISD::FP_TO_UINT: {
2982 SDValue True, False;
2983 EVT VT = Node->getOperand(0).getValueType();
2984 EVT NVT = Node->getValueType(0);
2985 APFloat apf(DAG.EVTToAPFloatSemantics(VT),
2986 APInt::getNullValue(VT.getSizeInBits()));
2987 APInt x = APInt::getSignMask(NVT.getSizeInBits());
2988 (void)apf.convertFromAPInt(x, false, APFloat::rmNearestTiesToEven);
2989 Tmp1 = DAG.getConstantFP(apf, dl, VT);
2990 Tmp2 = DAG.getSetCC(dl, getSetCCResultType(VT),
2991 Node->getOperand(0),
2993 True = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, Node->getOperand(0));
2994 // TODO: Should any fast-math-flags be set for the FSUB?
2995 False = DAG.getNode(ISD::FP_TO_SINT, dl, NVT,
2996 DAG.getNode(ISD::FSUB, dl, VT,
2997 Node->getOperand(0), Tmp1));
2998 False = DAG.getNode(ISD::XOR, dl, NVT, False,
2999 DAG.getConstant(x, dl, NVT));
3000 Tmp1 = DAG.getSelect(dl, NVT, Tmp2, True, False);
3001 Results.push_back(Tmp1);
3005 Results.push_back(DAG.expandVAArg(Node));
3006 Results.push_back(Results[0].getValue(1));
3009 Results.push_back(DAG.expandVACopy(Node));
3011 case ISD::EXTRACT_VECTOR_ELT:
3012 if (Node->getOperand(0).getValueType().getVectorNumElements() == 1)
3013 // This must be an access of the only element. Return it.
3014 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0),
3015 Node->getOperand(0));
3017 Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0));
3018 Results.push_back(Tmp1);
3020 case ISD::EXTRACT_SUBVECTOR:
3021 Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0)));
3023 case ISD::INSERT_SUBVECTOR:
3024 Results.push_back(ExpandInsertToVectorThroughStack(SDValue(Node, 0)));
3026 case ISD::CONCAT_VECTORS: {
3027 Results.push_back(ExpandVectorBuildThroughStack(Node));
3030 case ISD::SCALAR_TO_VECTOR:
3031 Results.push_back(ExpandSCALAR_TO_VECTOR(Node));
3033 case ISD::INSERT_VECTOR_ELT:
3034 Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0),
3035 Node->getOperand(1),
3036 Node->getOperand(2), dl));
3038 case ISD::VECTOR_SHUFFLE: {
3039 SmallVector<int, 32> NewMask;
3040 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
3042 EVT VT = Node->getValueType(0);
3043 EVT EltVT = VT.getVectorElementType();
3044 SDValue Op0 = Node->getOperand(0);
3045 SDValue Op1 = Node->getOperand(1);
3046 if (!TLI.isTypeLegal(EltVT)) {
3048 EVT NewEltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT);
3050 // BUILD_VECTOR operands are allowed to be wider than the element type.
3051 // But if NewEltVT is smaller that EltVT the BUILD_VECTOR does not accept
3053 if (NewEltVT.bitsLT(EltVT)) {
3055 // Convert shuffle node.
3056 // If original node was v4i64 and the new EltVT is i32,
3057 // cast operands to v8i32 and re-build the mask.
3059 // Calculate new VT, the size of the new VT should be equal to original.
3061 EVT::getVectorVT(*DAG.getContext(), NewEltVT,
3062 VT.getSizeInBits() / NewEltVT.getSizeInBits());
3063 assert(NewVT.bitsEq(VT));
3065 // cast operands to new VT
3066 Op0 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op0);
3067 Op1 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op1);
3069 // Convert the shuffle mask
3070 unsigned int factor =
3071 NewVT.getVectorNumElements()/VT.getVectorNumElements();
3073 // EltVT gets smaller
3076 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
3078 for (unsigned fi = 0; fi < factor; ++fi)
3079 NewMask.push_back(Mask[i]);
3082 for (unsigned fi = 0; fi < factor; ++fi)
3083 NewMask.push_back(Mask[i]*factor+fi);
3091 unsigned NumElems = VT.getVectorNumElements();
3092 SmallVector<SDValue, 16> Ops;
3093 for (unsigned i = 0; i != NumElems; ++i) {
3095 Ops.push_back(DAG.getUNDEF(EltVT));
3098 unsigned Idx = Mask[i];
3100 Ops.push_back(DAG.getNode(
3101 ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
3102 DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))));
3104 Ops.push_back(DAG.getNode(
3105 ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op1,
3106 DAG.getConstant(Idx - NumElems, dl,
3107 TLI.getVectorIdxTy(DAG.getDataLayout()))));
3110 Tmp1 = DAG.getBuildVector(VT, dl, Ops);
3111 // We may have changed the BUILD_VECTOR type. Cast it back to the Node type.
3112 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), Tmp1);
3113 Results.push_back(Tmp1);
3116 case ISD::EXTRACT_ELEMENT: {
3117 EVT OpTy = Node->getOperand(0).getValueType();
3118 if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
3120 Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0),
3121 DAG.getConstant(OpTy.getSizeInBits() / 2, dl,
3122 TLI.getShiftAmountTy(
3123 Node->getOperand(0).getValueType(),
3124 DAG.getDataLayout())));
3125 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
3128 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
3129 Node->getOperand(0));
3131 Results.push_back(Tmp1);
3134 case ISD::STACKSAVE:
3135 // Expand to CopyFromReg if the target set
3136 // StackPointerRegisterToSaveRestore.
3137 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
3138 Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP,
3139 Node->getValueType(0)));
3140 Results.push_back(Results[0].getValue(1));
3142 Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
3143 Results.push_back(Node->getOperand(0));
3146 case ISD::STACKRESTORE:
3147 // Expand to CopyToReg if the target set
3148 // StackPointerRegisterToSaveRestore.
3149 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
3150 Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP,
3151 Node->getOperand(1)));
3153 Results.push_back(Node->getOperand(0));
3156 case ISD::GET_DYNAMIC_AREA_OFFSET:
3157 Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0)));
3158 Results.push_back(Results[0].getValue(0));
3160 case ISD::FCOPYSIGN:
3161 Results.push_back(ExpandFCOPYSIGN(Node));
3164 // Expand Y = FNEG(X) -> Y = SUB -0.0, X
3165 Tmp1 = DAG.getConstantFP(-0.0, dl, Node->getValueType(0));
3166 // TODO: If FNEG has fast-math-flags, propagate them to the FSUB.
3167 Tmp1 = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp1,
3168 Node->getOperand(0));
3169 Results.push_back(Tmp1);
3172 Results.push_back(ExpandFABS(Node));
3178 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
3180 switch (Node->getOpcode()) {
3181 default: llvm_unreachable("How did we get here?");
3182 case ISD::SMAX: Pred = ISD::SETGT; break;
3183 case ISD::SMIN: Pred = ISD::SETLT; break;
3184 case ISD::UMAX: Pred = ISD::SETUGT; break;
3185 case ISD::UMIN: Pred = ISD::SETULT; break;
3187 Tmp1 = Node->getOperand(0);
3188 Tmp2 = Node->getOperand(1);
3189 Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp1, Tmp2, Pred);
3190 Results.push_back(Tmp1);
3196 EVT VT = Node->getValueType(0);
3197 // Turn fsin / fcos into ISD::FSINCOS node if there are a pair of fsin /
3198 // fcos which share the same operand and both are used.
3199 if ((TLI.isOperationLegalOrCustom(ISD::FSINCOS, VT) ||
3200 canCombineSinCosLibcall(Node, TLI, TM))
3201 && useSinCos(Node)) {
3202 SDVTList VTs = DAG.getVTList(VT, VT);
3203 Tmp1 = DAG.getNode(ISD::FSINCOS, dl, VTs, Node->getOperand(0));
3204 if (Node->getOpcode() == ISD::FCOS)
3205 Tmp1 = Tmp1.getValue(1);
3206 Results.push_back(Tmp1);
3211 llvm_unreachable("Illegal fmad should never be formed");
3213 case ISD::FP16_TO_FP:
3214 if (Node->getValueType(0) != MVT::f32) {
3215 // We can extend to types bigger than f32 in two steps without changing
3216 // the result. Since "f16 -> f32" is much more commonly available, give
3217 // CodeGen the option of emitting that before resorting to a libcall.
3219 DAG.getNode(ISD::FP16_TO_FP, dl, MVT::f32, Node->getOperand(0));
3221 DAG.getNode(ISD::FP_EXTEND, dl, Node->getValueType(0), Res));
3224 case ISD::FP_TO_FP16:
3225 if (!TLI.useSoftFloat() && TM.Options.UnsafeFPMath) {
3226 SDValue Op = Node->getOperand(0);
3227 MVT SVT = Op.getSimpleValueType();
3228 if ((SVT == MVT::f64 || SVT == MVT::f80) &&
3229 TLI.isOperationLegalOrCustom(ISD::FP_TO_FP16, MVT::f32)) {
3230 // Under fastmath, we can expand this node into a fround followed by
3231 // a float-half conversion.
3232 SDValue FloatVal = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Op,
3233 DAG.getIntPtrConstant(0, dl));
3235 DAG.getNode(ISD::FP_TO_FP16, dl, Node->getValueType(0), FloatVal));
3239 case ISD::ConstantFP: {
3240 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
3241 // Check to see if this FP immediate is already legal.
3242 // If this is a legal constant, turn it into a TargetConstantFP node.
3243 if (!TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0)))
3244 Results.push_back(ExpandConstantFP(CFP, true));
3247 case ISD::Constant: {
3248 ConstantSDNode *CP = cast<ConstantSDNode>(Node);
3249 Results.push_back(ExpandConstant(CP));
3253 EVT VT = Node->getValueType(0);
3254 if (TLI.isOperationLegalOrCustom(ISD::FADD, VT) &&
3255 TLI.isOperationLegalOrCustom(ISD::FNEG, VT)) {
3256 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(Node)->Flags;
3257 Tmp1 = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(1));
3258 Tmp1 = DAG.getNode(ISD::FADD, dl, VT, Node->getOperand(0), Tmp1, Flags);
3259 Results.push_back(Tmp1);
3264 EVT VT = Node->getValueType(0);
3265 assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
3266 TLI.isOperationLegalOrCustom(ISD::XOR, VT) &&
3267 "Don't know how to expand this subtraction!");
3268 Tmp1 = DAG.getNode(ISD::XOR, dl, VT, Node->getOperand(1),
3269 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
3271 Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp1, DAG.getConstant(1, dl, VT));
3272 Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1));
3277 EVT VT = Node->getValueType(0);
3278 bool isSigned = Node->getOpcode() == ISD::SREM;
3279 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
3280 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3281 Tmp2 = Node->getOperand(0);
3282 Tmp3 = Node->getOperand(1);
3283 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) {
3284 SDVTList VTs = DAG.getVTList(VT, VT);
3285 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Tmp2, Tmp3).getValue(1);
3286 Results.push_back(Tmp1);
3287 } else if (TLI.isOperationLegalOrCustom(DivOpc, VT)) {
3289 Tmp1 = DAG.getNode(DivOpc, dl, VT, Tmp2, Tmp3);
3290 Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Tmp3);
3291 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Tmp2, Tmp1);
3292 Results.push_back(Tmp1);
3298 bool isSigned = Node->getOpcode() == ISD::SDIV;
3299 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3300 EVT VT = Node->getValueType(0);
3301 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) {
3302 SDVTList VTs = DAG.getVTList(VT, VT);
3303 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0),
3304 Node->getOperand(1));
3305 Results.push_back(Tmp1);
3311 unsigned ExpandOpcode =
3312 Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI : ISD::SMUL_LOHI;
3313 EVT VT = Node->getValueType(0);
3314 SDVTList VTs = DAG.getVTList(VT, VT);
3316 Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0),
3317 Node->getOperand(1));
3318 Results.push_back(Tmp1.getValue(1));
3321 case ISD::UMUL_LOHI:
3322 case ISD::SMUL_LOHI: {
3323 SDValue LHS = Node->getOperand(0);
3324 SDValue RHS = Node->getOperand(1);
3325 MVT VT = LHS.getSimpleValueType();
3326 unsigned MULHOpcode =
3327 Node->getOpcode() == ISD::UMUL_LOHI ? ISD::MULHU : ISD::MULHS;
3329 if (TLI.isOperationLegalOrCustom(MULHOpcode, VT)) {
3330 Results.push_back(DAG.getNode(ISD::MUL, dl, VT, LHS, RHS));
3331 Results.push_back(DAG.getNode(MULHOpcode, dl, VT, LHS, RHS));
3335 SmallVector<SDValue, 4> Halves;
3336 EVT HalfType = EVT(VT).getHalfSizedIntegerVT(*DAG.getContext());
3337 assert(TLI.isTypeLegal(HalfType));
3338 if (TLI.expandMUL_LOHI(Node->getOpcode(), VT, Node, LHS, RHS, Halves,
3340 TargetLowering::MulExpansionKind::Always)) {
3341 for (unsigned i = 0; i < 2; ++i) {
3342 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Halves[2 * i]);
3343 SDValue Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Halves[2 * i + 1]);
3344 SDValue Shift = DAG.getConstant(
3345 HalfType.getScalarSizeInBits(), dl,
3346 TLI.getShiftAmountTy(HalfType, DAG.getDataLayout()));
3347 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
3348 Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi));
3355 EVT VT = Node->getValueType(0);
3356 SDVTList VTs = DAG.getVTList(VT, VT);
3357 // See if multiply or divide can be lowered using two-result operations.
3358 // We just need the low half of the multiply; try both the signed
3359 // and unsigned forms. If the target supports both SMUL_LOHI and
3360 // UMUL_LOHI, form a preference by checking which forms of plain
3361 // MULH it supports.
3362 bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
3363 bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
3364 bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
3365 bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
3366 unsigned OpToUse = 0;
3367 if (HasSMUL_LOHI && !HasMULHS) {
3368 OpToUse = ISD::SMUL_LOHI;
3369 } else if (HasUMUL_LOHI && !HasMULHU) {
3370 OpToUse = ISD::UMUL_LOHI;
3371 } else if (HasSMUL_LOHI) {
3372 OpToUse = ISD::SMUL_LOHI;
3373 } else if (HasUMUL_LOHI) {
3374 OpToUse = ISD::UMUL_LOHI;
3377 Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0),
3378 Node->getOperand(1)));
3383 EVT HalfType = VT.getHalfSizedIntegerVT(*DAG.getContext());
3384 if (TLI.isOperationLegalOrCustom(ISD::ZERO_EXTEND, VT) &&
3385 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND, VT) &&
3386 TLI.isOperationLegalOrCustom(ISD::SHL, VT) &&
3387 TLI.isOperationLegalOrCustom(ISD::OR, VT) &&
3388 TLI.expandMUL(Node, Lo, Hi, HalfType, DAG,
3389 TargetLowering::MulExpansionKind::OnlyLegalOrCustom)) {
3390 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
3391 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Hi);
3393 DAG.getConstant(HalfType.getSizeInBits(), dl,
3394 TLI.getShiftAmountTy(HalfType, DAG.getDataLayout()));
3395 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
3396 Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi));
3402 SDValue LHS = Node->getOperand(0);
3403 SDValue RHS = Node->getOperand(1);
3404 SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
3405 ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3407 Results.push_back(Sum);
3408 EVT ResultType = Node->getValueType(1);
3409 EVT OType = getSetCCResultType(Node->getValueType(0));
3411 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
3413 // LHSSign -> LHS >= 0
3414 // RHSSign -> RHS >= 0
3415 // SumSign -> Sum >= 0
3418 // Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
3420 // Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
3422 SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
3423 SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
3424 SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
3425 Node->getOpcode() == ISD::SADDO ?
3426 ISD::SETEQ : ISD::SETNE);
3428 SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
3429 SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
3431 SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
3432 Results.push_back(DAG.getBoolExtOrTrunc(Cmp, dl, ResultType, ResultType));
3437 SDValue LHS = Node->getOperand(0);
3438 SDValue RHS = Node->getOperand(1);
3439 SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::UADDO ?
3440 ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3442 Results.push_back(Sum);
3444 EVT ResultType = Node->getValueType(1);
3445 EVT SetCCType = getSetCCResultType(Node->getValueType(0));
3447 = Node->getOpcode() == ISD::UADDO ? ISD::SETULT : ISD::SETUGT;
3448 SDValue SetCC = DAG.getSetCC(dl, SetCCType, Sum, LHS, CC);
3450 Results.push_back(DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType));
3455 EVT VT = Node->getValueType(0);
3456 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits() * 2);
3457 SDValue LHS = Node->getOperand(0);
3458 SDValue RHS = Node->getOperand(1);
3461 static const unsigned Ops[2][3] =
3462 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
3463 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
3464 bool isSigned = Node->getOpcode() == ISD::SMULO;
3465 if (TLI.isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
3466 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
3467 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
3468 } else if (TLI.isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
3469 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
3471 TopHalf = BottomHalf.getValue(1);
3472 } else if (TLI.isTypeLegal(WideVT)) {
3473 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
3474 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
3475 Tmp1 = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
3476 BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
3477 DAG.getIntPtrConstant(0, dl));
3478 TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
3479 DAG.getIntPtrConstant(1, dl));
3481 // We can fall back to a libcall with an illegal type for the MUL if we
3482 // have a libcall big enough.
3483 // Also, we can fall back to a division in some cases, but that's a big
3484 // performance hit in the general case.
3485 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3486 if (WideVT == MVT::i16)
3487 LC = RTLIB::MUL_I16;
3488 else if (WideVT == MVT::i32)
3489 LC = RTLIB::MUL_I32;
3490 else if (WideVT == MVT::i64)
3491 LC = RTLIB::MUL_I64;
3492 else if (WideVT == MVT::i128)
3493 LC = RTLIB::MUL_I128;
3494 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!");
3496 // The high part is obtained by SRA'ing all but one of the bits of low
3498 unsigned LoSize = VT.getSizeInBits();
3500 DAG.getNode(ISD::SRA, dl, VT, RHS,
3501 DAG.getConstant(LoSize - 1, dl,
3502 TLI.getPointerTy(DAG.getDataLayout())));
3504 DAG.getNode(ISD::SRA, dl, VT, LHS,
3505 DAG.getConstant(LoSize - 1, dl,
3506 TLI.getPointerTy(DAG.getDataLayout())));
3508 // Here we're passing the 2 arguments explicitly as 4 arguments that are
3509 // pre-lowered to the correct types. This all depends upon WideVT not
3510 // being a legal type for the architecture and thus has to be split to
3513 if(DAG.getDataLayout().isLittleEndian()) {
3514 // Halves of WideVT are packed into registers in different order
3515 // depending on platform endianness. This is usually handled by
3516 // the C calling convention, but we can't defer to it in
3518 SDValue Args[] = { LHS, HiLHS, RHS, HiRHS };
3519 Ret = ExpandLibCall(LC, WideVT, Args, 4, isSigned, dl);
3521 SDValue Args[] = { HiLHS, LHS, HiRHS, RHS };
3522 Ret = ExpandLibCall(LC, WideVT, Args, 4, isSigned, dl);
3524 BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Ret,
3525 DAG.getIntPtrConstant(0, dl));
3526 TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Ret,
3527 DAG.getIntPtrConstant(1, dl));
3528 // Ret is a node with an illegal type. Because such things are not
3529 // generally permitted during this phase of legalization, make sure the
3530 // node has no more uses. The above EXTRACT_ELEMENT nodes should have been
3532 assert(Ret->use_empty() &&
3533 "Unexpected uses of illegally type from expanded lib call.");
3537 Tmp1 = DAG.getConstant(
3538 VT.getSizeInBits() - 1, dl,
3539 TLI.getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout()));
3540 Tmp1 = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, Tmp1);
3541 TopHalf = DAG.getSetCC(dl, getSetCCResultType(VT), TopHalf, Tmp1,
3544 TopHalf = DAG.getSetCC(dl, getSetCCResultType(VT), TopHalf,
3545 DAG.getConstant(0, dl, VT), ISD::SETNE);
3548 // Truncate the result if SetCC returns a larger type than needed.
3549 EVT RType = Node->getValueType(1);
3550 if (RType.getSizeInBits() < TopHalf.getValueSizeInBits())
3551 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, RType, TopHalf);
3553 assert(RType.getSizeInBits() == TopHalf.getValueSizeInBits() &&
3554 "Unexpected result type for S/UMULO legalization");
3556 Results.push_back(BottomHalf);
3557 Results.push_back(TopHalf);
3560 case ISD::BUILD_PAIR: {
3561 EVT PairTy = Node->getValueType(0);
3562 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0));
3563 Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1));
3565 ISD::SHL, dl, PairTy, Tmp2,
3566 DAG.getConstant(PairTy.getSizeInBits() / 2, dl,
3567 TLI.getShiftAmountTy(PairTy, DAG.getDataLayout())));
3568 Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2));
3572 Tmp1 = Node->getOperand(0);
3573 Tmp2 = Node->getOperand(1);
3574 Tmp3 = Node->getOperand(2);
3575 if (Tmp1.getOpcode() == ISD::SETCC) {
3576 Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1),
3578 cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
3580 Tmp1 = DAG.getSelectCC(dl, Tmp1,
3581 DAG.getConstant(0, dl, Tmp1.getValueType()),
3582 Tmp2, Tmp3, ISD::SETNE);
3584 Results.push_back(Tmp1);
3587 SDValue Chain = Node->getOperand(0);
3588 SDValue Table = Node->getOperand(1);
3589 SDValue Index = Node->getOperand(2);
3591 const DataLayout &TD = DAG.getDataLayout();
3592 EVT PTy = TLI.getPointerTy(TD);
3594 unsigned EntrySize =
3595 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
3597 Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(), Index,
3598 DAG.getConstant(EntrySize, dl, Index.getValueType()));
3599 SDValue Addr = DAG.getNode(ISD::ADD, dl, Index.getValueType(),
3602 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
3603 SDValue LD = DAG.getExtLoad(
3604 ISD::SEXTLOAD, dl, PTy, Chain, Addr,
3605 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), MemVT);
3607 if (TLI.isJumpTableRelative()) {
3608 // For PIC, the sequence is:
3609 // BRIND(load(Jumptable + index) + RelocBase)
3610 // RelocBase can be JumpTable, GOT or some sort of global base.
3611 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr,
3612 TLI.getPICJumpTableRelocBase(Table, DAG));
3614 Tmp1 = DAG.getNode(ISD::BRIND, dl, MVT::Other, LD.getValue(1), Addr);
3615 Results.push_back(Tmp1);
3619 // Expand brcond's setcc into its constituent parts and create a BR_CC
3621 Tmp1 = Node->getOperand(0);
3622 Tmp2 = Node->getOperand(1);
3623 if (Tmp2.getOpcode() == ISD::SETCC) {
3624 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other,
3625 Tmp1, Tmp2.getOperand(2),
3626 Tmp2.getOperand(0), Tmp2.getOperand(1),
3627 Node->getOperand(2));
3629 // We test only the i1 bit. Skip the AND if UNDEF.
3630 Tmp3 = (Tmp2.isUndef()) ? Tmp2 :
3631 DAG.getNode(ISD::AND, dl, Tmp2.getValueType(), Tmp2,
3632 DAG.getConstant(1, dl, Tmp2.getValueType()));
3633 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
3634 DAG.getCondCode(ISD::SETNE), Tmp3,
3635 DAG.getConstant(0, dl, Tmp3.getValueType()),
3636 Node->getOperand(2));
3638 Results.push_back(Tmp1);
3641 Tmp1 = Node->getOperand(0);
3642 Tmp2 = Node->getOperand(1);
3643 Tmp3 = Node->getOperand(2);
3644 bool Legalized = LegalizeSetCCCondCode(Node->getValueType(0), Tmp1, Tmp2,
3645 Tmp3, NeedInvert, dl);
3648 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
3649 // condition code, create a new SETCC node.
3651 Tmp1 = DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
3654 // If we expanded the SETCC by inverting the condition code, then wrap
3655 // the existing SETCC in a NOT to restore the intended condition.
3657 Tmp1 = DAG.getLogicalNOT(dl, Tmp1, Tmp1->getValueType(0));
3659 Results.push_back(Tmp1);
3663 // Otherwise, SETCC for the given comparison type must be completely
3664 // illegal; expand it into a SELECT_CC.
3665 EVT VT = Node->getValueType(0);
3667 switch (TLI.getBooleanContents(Tmp1->getValueType(0))) {
3668 case TargetLowering::ZeroOrOneBooleanContent:
3669 case TargetLowering::UndefinedBooleanContent:
3672 case TargetLowering::ZeroOrNegativeOneBooleanContent:
3676 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
3677 DAG.getConstant(TrueValue, dl, VT),
3678 DAG.getConstant(0, dl, VT),
3680 Results.push_back(Tmp1);
3683 case ISD::SELECT_CC: {
3684 Tmp1 = Node->getOperand(0); // LHS
3685 Tmp2 = Node->getOperand(1); // RHS
3686 Tmp3 = Node->getOperand(2); // True
3687 Tmp4 = Node->getOperand(3); // False
3688 EVT VT = Node->getValueType(0);
3689 SDValue CC = Node->getOperand(4);
3690 ISD::CondCode CCOp = cast<CondCodeSDNode>(CC)->get();
3692 if (TLI.isCondCodeLegal(CCOp, Tmp1.getSimpleValueType())) {
3693 // If the condition code is legal, then we need to expand this
3694 // node using SETCC and SELECT.
3695 EVT CmpVT = Tmp1.getValueType();
3696 assert(!TLI.isOperationExpand(ISD::SELECT, VT) &&
3697 "Cannot expand ISD::SELECT_CC when ISD::SELECT also needs to be "
3700 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT);
3701 SDValue Cond = DAG.getNode(ISD::SETCC, dl, CCVT, Tmp1, Tmp2, CC);
3702 Results.push_back(DAG.getSelect(dl, VT, Cond, Tmp3, Tmp4));
3706 // SELECT_CC is legal, so the condition code must not be.
3707 bool Legalized = false;
3708 // Try to legalize by inverting the condition. This is for targets that
3709 // might support an ordered version of a condition, but not the unordered
3710 // version (or vice versa).
3711 ISD::CondCode InvCC = ISD::getSetCCInverse(CCOp,
3712 Tmp1.getValueType().isInteger());
3713 if (TLI.isCondCodeLegal(InvCC, Tmp1.getSimpleValueType())) {
3714 // Use the new condition code and swap true and false
3716 Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp4, Tmp3, InvCC);
3718 // If The inverse is not legal, then try to swap the arguments using
3719 // the inverse condition code.
3720 ISD::CondCode SwapInvCC = ISD::getSetCCSwappedOperands(InvCC);
3721 if (TLI.isCondCodeLegal(SwapInvCC, Tmp1.getSimpleValueType())) {
3722 // The swapped inverse condition is legal, so swap true and false,
3725 Tmp1 = DAG.getSelectCC(dl, Tmp2, Tmp1, Tmp4, Tmp3, SwapInvCC);
3730 Legalized = LegalizeSetCCCondCode(
3731 getSetCCResultType(Tmp1.getValueType()), Tmp1, Tmp2, CC, NeedInvert,
3734 assert(Legalized && "Can't legalize SELECT_CC with legal condition!");
3736 // If we expanded the SETCC by inverting the condition code, then swap
3737 // the True/False operands to match.
3739 std::swap(Tmp3, Tmp4);
3741 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
3742 // condition code, create a new SELECT_CC node.
3744 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0),
3745 Tmp1, Tmp2, Tmp3, Tmp4, CC);
3747 Tmp2 = DAG.getConstant(0, dl, Tmp1.getValueType());
3748 CC = DAG.getCondCode(ISD::SETNE);
3749 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1,
3750 Tmp2, Tmp3, Tmp4, CC);
3753 Results.push_back(Tmp1);
3757 Tmp1 = Node->getOperand(0); // Chain
3758 Tmp2 = Node->getOperand(2); // LHS
3759 Tmp3 = Node->getOperand(3); // RHS
3760 Tmp4 = Node->getOperand(1); // CC
3762 bool Legalized = LegalizeSetCCCondCode(getSetCCResultType(
3763 Tmp2.getValueType()), Tmp2, Tmp3, Tmp4, NeedInvert, dl);
3765 assert(Legalized && "Can't legalize BR_CC with legal condition!");
3767 // If we expanded the SETCC by inverting the condition code, then wrap
3768 // the existing SETCC in a NOT to restore the intended condition.
3770 Tmp4 = DAG.getNOT(dl, Tmp4, Tmp4->getValueType(0));
3772 // If we expanded the SETCC by swapping LHS and RHS, create a new BR_CC
3774 if (Tmp4.getNode()) {
3775 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1,
3776 Tmp4, Tmp2, Tmp3, Node->getOperand(4));
3778 Tmp3 = DAG.getConstant(0, dl, Tmp2.getValueType());
3779 Tmp4 = DAG.getCondCode(ISD::SETNE);
3780 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4,
3781 Tmp2, Tmp3, Node->getOperand(4));
3783 Results.push_back(Tmp1);
3786 case ISD::BUILD_VECTOR:
3787 Results.push_back(ExpandBUILD_VECTOR(Node));
3792 // Scalarize vector SRA/SRL/SHL.
3793 EVT VT = Node->getValueType(0);
3794 assert(VT.isVector() && "Unable to legalize non-vector shift");
3795 assert(TLI.isTypeLegal(VT.getScalarType())&& "Element type must be legal");
3796 unsigned NumElem = VT.getVectorNumElements();
3798 SmallVector<SDValue, 8> Scalars;
3799 for (unsigned Idx = 0; Idx < NumElem; Idx++) {
3800 SDValue Ex = DAG.getNode(
3801 ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(), Node->getOperand(0),
3802 DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
3803 SDValue Sh = DAG.getNode(
3804 ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(), Node->getOperand(1),
3805 DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
3806 Scalars.push_back(DAG.getNode(Node->getOpcode(), dl,
3807 VT.getScalarType(), Ex, Sh));
3810 SDValue Result = DAG.getBuildVector(Node->getValueType(0), dl, Scalars);
3811 ReplaceNode(SDValue(Node, 0), Result);
3814 case ISD::GLOBAL_OFFSET_TABLE:
3815 case ISD::GlobalAddress:
3816 case ISD::GlobalTLSAddress:
3817 case ISD::ExternalSymbol:
3818 case ISD::ConstantPool:
3819 case ISD::JumpTable:
3820 case ISD::INTRINSIC_W_CHAIN:
3821 case ISD::INTRINSIC_WO_CHAIN:
3822 case ISD::INTRINSIC_VOID:
3823 // FIXME: Custom lowering for these operations shouldn't return null!
3827 // Replace the original node with the legalized result.
3828 if (Results.empty())
3831 ReplaceNode(Node, Results.data());
3835 void SelectionDAGLegalize::ConvertNodeToLibcall(SDNode *Node) {
3836 SmallVector<SDValue, 8> Results;
3838 SDValue Tmp1, Tmp2, Tmp3, Tmp4;
3839 unsigned Opc = Node->getOpcode();
3841 case ISD::ATOMIC_FENCE: {
3842 // If the target didn't lower this, lower it to '__sync_synchronize()' call
3843 // FIXME: handle "fence singlethread" more efficiently.
3844 TargetLowering::ArgListTy Args;
3846 TargetLowering::CallLoweringInfo CLI(DAG);
3848 .setChain(Node->getOperand(0))
3850 CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3851 DAG.getExternalSymbol("__sync_synchronize",
3852 TLI.getPointerTy(DAG.getDataLayout())),
3855 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
3857 Results.push_back(CallResult.second);
3860 // By default, atomic intrinsics are marked Legal and lowered. Targets
3861 // which don't support them directly, however, may want libcalls, in which
3862 // case they mark them Expand, and we get here.
3863 case ISD::ATOMIC_SWAP:
3864 case ISD::ATOMIC_LOAD_ADD:
3865 case ISD::ATOMIC_LOAD_SUB:
3866 case ISD::ATOMIC_LOAD_AND:
3867 case ISD::ATOMIC_LOAD_OR:
3868 case ISD::ATOMIC_LOAD_XOR:
3869 case ISD::ATOMIC_LOAD_NAND:
3870 case ISD::ATOMIC_LOAD_MIN:
3871 case ISD::ATOMIC_LOAD_MAX:
3872 case ISD::ATOMIC_LOAD_UMIN:
3873 case ISD::ATOMIC_LOAD_UMAX:
3874 case ISD::ATOMIC_CMP_SWAP: {
3875 MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
3876 RTLIB::Libcall LC = RTLIB::getSYNC(Opc, VT);
3877 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected atomic op or value type!");
3879 std::pair<SDValue, SDValue> Tmp = ExpandChainLibCall(LC, Node, false);
3880 Results.push_back(Tmp.first);
3881 Results.push_back(Tmp.second);
3885 // If this operation is not supported, lower it to 'abort()' call
3886 TargetLowering::ArgListTy Args;
3887 TargetLowering::CallLoweringInfo CLI(DAG);
3889 .setChain(Node->getOperand(0))
3890 .setLibCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3891 DAG.getExternalSymbol(
3892 "abort", TLI.getPointerTy(DAG.getDataLayout())),
3894 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
3896 Results.push_back(CallResult.second);
3900 Results.push_back(ExpandFPLibCall(Node, RTLIB::FMIN_F32, RTLIB::FMIN_F64,
3901 RTLIB::FMIN_F80, RTLIB::FMIN_F128,
3902 RTLIB::FMIN_PPCF128));
3905 Results.push_back(ExpandFPLibCall(Node, RTLIB::FMAX_F32, RTLIB::FMAX_F64,
3906 RTLIB::FMAX_F80, RTLIB::FMAX_F128,
3907 RTLIB::FMAX_PPCF128));
3910 Results.push_back(ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
3911 RTLIB::SQRT_F80, RTLIB::SQRT_F128,
3912 RTLIB::SQRT_PPCF128));
3915 Results.push_back(ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64,
3916 RTLIB::SIN_F80, RTLIB::SIN_F128,
3917 RTLIB::SIN_PPCF128));
3920 Results.push_back(ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64,
3921 RTLIB::COS_F80, RTLIB::COS_F128,
3922 RTLIB::COS_PPCF128));
3925 // Expand into sincos libcall.
3926 ExpandSinCosLibCall(Node, Results);
3929 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64,
3930 RTLIB::LOG_F80, RTLIB::LOG_F128,
3931 RTLIB::LOG_PPCF128));
3934 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
3935 RTLIB::LOG2_F80, RTLIB::LOG2_F128,
3936 RTLIB::LOG2_PPCF128));
3939 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
3940 RTLIB::LOG10_F80, RTLIB::LOG10_F128,
3941 RTLIB::LOG10_PPCF128));
3944 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64,
3945 RTLIB::EXP_F80, RTLIB::EXP_F128,
3946 RTLIB::EXP_PPCF128));
3949 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
3950 RTLIB::EXP2_F80, RTLIB::EXP2_F128,
3951 RTLIB::EXP2_PPCF128));
3954 Results.push_back(ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
3955 RTLIB::TRUNC_F80, RTLIB::TRUNC_F128,
3956 RTLIB::TRUNC_PPCF128));
3959 Results.push_back(ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
3960 RTLIB::FLOOR_F80, RTLIB::FLOOR_F128,
3961 RTLIB::FLOOR_PPCF128));
3964 Results.push_back(ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
3965 RTLIB::CEIL_F80, RTLIB::CEIL_F128,
3966 RTLIB::CEIL_PPCF128));
3969 Results.push_back(ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64,
3970 RTLIB::RINT_F80, RTLIB::RINT_F128,
3971 RTLIB::RINT_PPCF128));
3973 case ISD::FNEARBYINT:
3974 Results.push_back(ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32,
3975 RTLIB::NEARBYINT_F64,
3976 RTLIB::NEARBYINT_F80,
3977 RTLIB::NEARBYINT_F128,
3978 RTLIB::NEARBYINT_PPCF128));
3981 Results.push_back(ExpandFPLibCall(Node, RTLIB::ROUND_F32,
3985 RTLIB::ROUND_PPCF128));
3988 Results.push_back(ExpandFPLibCall(Node, RTLIB::POWI_F32, RTLIB::POWI_F64,
3989 RTLIB::POWI_F80, RTLIB::POWI_F128,
3990 RTLIB::POWI_PPCF128));
3993 Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64,
3994 RTLIB::POW_F80, RTLIB::POW_F128,
3995 RTLIB::POW_PPCF128));
3998 Results.push_back(ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64,
3999 RTLIB::DIV_F80, RTLIB::DIV_F128,
4000 RTLIB::DIV_PPCF128));
4003 Results.push_back(ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64,
4004 RTLIB::REM_F80, RTLIB::REM_F128,
4005 RTLIB::REM_PPCF128));
4008 Results.push_back(ExpandFPLibCall(Node, RTLIB::FMA_F32, RTLIB::FMA_F64,
4009 RTLIB::FMA_F80, RTLIB::FMA_F128,
4010 RTLIB::FMA_PPCF128));
4013 Results.push_back(ExpandFPLibCall(Node, RTLIB::ADD_F32, RTLIB::ADD_F64,
4014 RTLIB::ADD_F80, RTLIB::ADD_F128,
4015 RTLIB::ADD_PPCF128));
4018 Results.push_back(ExpandFPLibCall(Node, RTLIB::MUL_F32, RTLIB::MUL_F64,
4019 RTLIB::MUL_F80, RTLIB::MUL_F128,
4020 RTLIB::MUL_PPCF128));
4022 case ISD::FP16_TO_FP:
4023 if (Node->getValueType(0) == MVT::f32) {
4024 Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false));
4027 case ISD::FP_TO_FP16: {
4029 RTLIB::getFPROUND(Node->getOperand(0).getValueType(), MVT::f16);
4030 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to expand fp_to_fp16");
4031 Results.push_back(ExpandLibCall(LC, Node, false));
4035 Results.push_back(ExpandFPLibCall(Node, RTLIB::SUB_F32, RTLIB::SUB_F64,
4036 RTLIB::SUB_F80, RTLIB::SUB_F128,
4037 RTLIB::SUB_PPCF128));
4040 Results.push_back(ExpandIntLibCall(Node, true,
4042 RTLIB::SREM_I16, RTLIB::SREM_I32,
4043 RTLIB::SREM_I64, RTLIB::SREM_I128));
4046 Results.push_back(ExpandIntLibCall(Node, false,
4048 RTLIB::UREM_I16, RTLIB::UREM_I32,
4049 RTLIB::UREM_I64, RTLIB::UREM_I128));
4052 Results.push_back(ExpandIntLibCall(Node, true,
4054 RTLIB::SDIV_I16, RTLIB::SDIV_I32,
4055 RTLIB::SDIV_I64, RTLIB::SDIV_I128));
4058 Results.push_back(ExpandIntLibCall(Node, false,
4060 RTLIB::UDIV_I16, RTLIB::UDIV_I32,
4061 RTLIB::UDIV_I64, RTLIB::UDIV_I128));
4065 // Expand into divrem libcall
4066 ExpandDivRemLibCall(Node, Results);
4069 Results.push_back(ExpandIntLibCall(Node, false,
4071 RTLIB::MUL_I16, RTLIB::MUL_I32,
4072 RTLIB::MUL_I64, RTLIB::MUL_I128));
4076 // Replace the original node with the legalized result.
4077 if (!Results.empty())
4078 ReplaceNode(Node, Results.data());
4081 // Determine the vector type to use in place of an original scalar element when
4082 // promoting equally sized vectors.
4083 static MVT getPromotedVectorElementType(const TargetLowering &TLI,
4084 MVT EltVT, MVT NewEltVT) {
4085 unsigned OldEltsPerNewElt = EltVT.getSizeInBits() / NewEltVT.getSizeInBits();
4086 MVT MidVT = MVT::getVectorVT(NewEltVT, OldEltsPerNewElt);
4087 assert(TLI.isTypeLegal(MidVT) && "unexpected");
4091 void SelectionDAGLegalize::PromoteNode(SDNode *Node) {
4092 SmallVector<SDValue, 8> Results;
4093 MVT OVT = Node->getSimpleValueType(0);
4094 if (Node->getOpcode() == ISD::UINT_TO_FP ||
4095 Node->getOpcode() == ISD::SINT_TO_FP ||
4096 Node->getOpcode() == ISD::SETCC ||
4097 Node->getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
4098 Node->getOpcode() == ISD::INSERT_VECTOR_ELT) {
4099 OVT = Node->getOperand(0).getSimpleValueType();
4101 if (Node->getOpcode() == ISD::BR_CC)
4102 OVT = Node->getOperand(2).getSimpleValueType();
4103 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
4105 SDValue Tmp1, Tmp2, Tmp3;
4106 switch (Node->getOpcode()) {
4108 case ISD::CTTZ_ZERO_UNDEF:
4110 case ISD::CTLZ_ZERO_UNDEF:
4112 // Zero extend the argument.
4113 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
4114 if (Node->getOpcode() == ISD::CTTZ) {
4115 // The count is the same in the promoted type except if the original
4116 // value was zero. This can be handled by setting the bit just off
4117 // the top of the original type.
4118 auto TopBit = APInt::getOneBitSet(NVT.getSizeInBits(),
4119 OVT.getSizeInBits());
4120 Tmp1 = DAG.getNode(ISD::OR, dl, NVT, Tmp1,
4121 DAG.getConstant(TopBit, dl, NVT));
4123 // Perform the larger operation. For CTPOP and CTTZ_ZERO_UNDEF, this is
4124 // already the correct result.
4125 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4126 if (Node->getOpcode() == ISD::CTLZ ||
4127 Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF) {
4128 // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
4129 Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
4130 DAG.getConstant(NVT.getSizeInBits() -
4131 OVT.getSizeInBits(), dl, NVT));
4133 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
4135 case ISD::BITREVERSE:
4137 unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
4138 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
4139 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4141 ISD::SRL, dl, NVT, Tmp1,
4142 DAG.getConstant(DiffBits, dl,
4143 TLI.getShiftAmountTy(NVT, DAG.getDataLayout())));
4144 Results.push_back(Tmp1);
4147 case ISD::FP_TO_UINT:
4148 case ISD::FP_TO_SINT:
4149 Tmp1 = PromoteLegalFP_TO_INT(Node->getOperand(0), Node->getValueType(0),
4150 Node->getOpcode() == ISD::FP_TO_SINT, dl);
4151 Results.push_back(Tmp1);
4153 case ISD::UINT_TO_FP:
4154 case ISD::SINT_TO_FP:
4155 Tmp1 = PromoteLegalINT_TO_FP(Node->getOperand(0), Node->getValueType(0),
4156 Node->getOpcode() == ISD::SINT_TO_FP, dl);
4157 Results.push_back(Tmp1);
4160 SDValue Chain = Node->getOperand(0); // Get the chain.
4161 SDValue Ptr = Node->getOperand(1); // Get the pointer.
4164 if (OVT.isVector()) {
4165 TruncOp = ISD::BITCAST;
4167 assert(OVT.isInteger()
4168 && "VAARG promotion is supported only for vectors or integer types");
4169 TruncOp = ISD::TRUNCATE;
4172 // Perform the larger operation, then convert back
4173 Tmp1 = DAG.getVAArg(NVT, dl, Chain, Ptr, Node->getOperand(2),
4174 Node->getConstantOperandVal(3));
4175 Chain = Tmp1.getValue(1);
4177 Tmp2 = DAG.getNode(TruncOp, dl, OVT, Tmp1);
4179 // Modified the chain result - switch anything that used the old chain to
4181 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Tmp2);
4182 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
4184 UpdatedNodes->insert(Tmp2.getNode());
4185 UpdatedNodes->insert(Chain.getNode());
4197 unsigned ExtOp, TruncOp;
4198 if (OVT.isVector()) {
4199 ExtOp = ISD::BITCAST;
4200 TruncOp = ISD::BITCAST;
4202 assert(OVT.isInteger() && "Cannot promote logic operation");
4204 switch (Node->getOpcode()) {
4206 ExtOp = ISD::ANY_EXTEND;
4210 ExtOp = ISD::SIGN_EXTEND;
4214 ExtOp = ISD::ZERO_EXTEND;
4217 TruncOp = ISD::TRUNCATE;
4219 // Promote each of the values to the new type.
4220 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4221 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4222 // Perform the larger operation, then convert back
4223 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4224 Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1));
4227 case ISD::UMUL_LOHI:
4228 case ISD::SMUL_LOHI: {
4229 // Promote to a multiply in a wider integer type.
4230 unsigned ExtOp = Node->getOpcode() == ISD::UMUL_LOHI ? ISD::ZERO_EXTEND
4232 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4233 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4234 Tmp1 = DAG.getNode(ISD::MUL, dl, NVT, Tmp1, Tmp2);
4236 auto &DL = DAG.getDataLayout();
4237 unsigned OriginalSize = OVT.getScalarSizeInBits();
4239 ISD::SRL, dl, NVT, Tmp1,
4240 DAG.getConstant(OriginalSize, dl, TLI.getScalarShiftAmountTy(DL, NVT)));
4241 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
4242 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp2));
4246 unsigned ExtOp, TruncOp;
4247 if (Node->getValueType(0).isVector() ||
4248 Node->getValueType(0).getSizeInBits() == NVT.getSizeInBits()) {
4249 ExtOp = ISD::BITCAST;
4250 TruncOp = ISD::BITCAST;
4251 } else if (Node->getValueType(0).isInteger()) {
4252 ExtOp = ISD::ANY_EXTEND;
4253 TruncOp = ISD::TRUNCATE;
4255 ExtOp = ISD::FP_EXTEND;
4256 TruncOp = ISD::FP_ROUND;
4258 Tmp1 = Node->getOperand(0);
4259 // Promote each of the values to the new type.
4260 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4261 Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
4262 // Perform the larger operation, then round down.
4263 Tmp1 = DAG.getSelect(dl, NVT, Tmp1, Tmp2, Tmp3);
4264 if (TruncOp != ISD::FP_ROUND)
4265 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1);
4267 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1,
4268 DAG.getIntPtrConstant(0, dl));
4269 Results.push_back(Tmp1);
4272 case ISD::VECTOR_SHUFFLE: {
4273 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
4275 // Cast the two input vectors.
4276 Tmp1 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0));
4277 Tmp2 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(1));
4279 // Convert the shuffle mask to the right # elements.
4280 Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
4281 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OVT, Tmp1);
4282 Results.push_back(Tmp1);
4286 unsigned ExtOp = ISD::FP_EXTEND;
4287 if (NVT.isInteger()) {
4288 ISD::CondCode CCCode =
4289 cast<CondCodeSDNode>(Node->getOperand(2))->get();
4290 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4292 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4293 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4294 Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
4295 Tmp1, Tmp2, Node->getOperand(2)));
4299 unsigned ExtOp = ISD::FP_EXTEND;
4300 if (NVT.isInteger()) {
4301 ISD::CondCode CCCode =
4302 cast<CondCodeSDNode>(Node->getOperand(1))->get();
4303 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4305 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
4306 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(3));
4307 Results.push_back(DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0),
4308 Node->getOperand(0), Node->getOperand(1),
4309 Tmp1, Tmp2, Node->getOperand(4)));
4320 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4321 Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
4322 Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2,
4324 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4325 Tmp3, DAG.getIntPtrConstant(0, dl)));
4329 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4330 Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
4331 Tmp3 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(2));
4333 DAG.getNode(ISD::FP_ROUND, dl, OVT,
4334 DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2, Tmp3),
4335 DAG.getIntPtrConstant(0, dl)));
4338 case ISD::FCOPYSIGN:
4340 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4341 Tmp2 = Node->getOperand(1);
4342 Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4344 // fcopysign doesn't change anything but the sign bit, so
4345 // (fp_round (fcopysign (fpext a), b))
4347 // (fp_round (fpext a))
4348 // which is a no-op. Mark it as a TRUNCating FP_ROUND.
4349 const bool isTrunc = (Node->getOpcode() == ISD::FCOPYSIGN);
4350 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4351 Tmp3, DAG.getIntPtrConstant(isTrunc, dl)));
4357 case ISD::FNEARBYINT:
4370 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4371 Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4372 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4373 Tmp2, DAG.getIntPtrConstant(0, dl)));
4376 case ISD::BUILD_VECTOR: {
4377 MVT EltVT = OVT.getVectorElementType();
4378 MVT NewEltVT = NVT.getVectorElementType();
4380 // Handle bitcasts to a different vector type with the same total bit size
4382 // e.g. v2i64 = build_vector i64:x, i64:y => v4i32
4384 // v4i32 = concat_vectors (v2i32 (bitcast i64:x)), (v2i32 (bitcast i64:y))
4386 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
4387 "Invalid promote type for build_vector");
4388 assert(NewEltVT.bitsLT(EltVT) && "not handled");
4390 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4392 SmallVector<SDValue, 8> NewOps;
4393 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) {
4394 SDValue Op = Node->getOperand(I);
4395 NewOps.push_back(DAG.getNode(ISD::BITCAST, SDLoc(Op), MidVT, Op));
4399 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewOps);
4400 SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat);
4401 Results.push_back(CvtVec);
4404 case ISD::EXTRACT_VECTOR_ELT: {
4405 MVT EltVT = OVT.getVectorElementType();
4406 MVT NewEltVT = NVT.getVectorElementType();
4408 // Handle bitcasts to a different vector type with the same total bit size.
4410 // e.g. v2i64 = extract_vector_elt x:v2i64, y:i32
4412 // v4i32:castx = bitcast x:v2i64
4415 // (v2i32 build_vector (i32 (extract_vector_elt castx, (2 * y))),
4416 // (i32 (extract_vector_elt castx, (2 * y + 1)))
4419 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
4420 "Invalid promote type for extract_vector_elt");
4421 assert(NewEltVT.bitsLT(EltVT) && "not handled");
4423 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4424 unsigned NewEltsPerOldElt = MidVT.getVectorNumElements();
4426 SDValue Idx = Node->getOperand(1);
4427 EVT IdxVT = Idx.getValueType();
4429 SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SL, IdxVT);
4430 SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor);
4432 SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0));
4434 SmallVector<SDValue, 8> NewOps;
4435 for (unsigned I = 0; I < NewEltsPerOldElt; ++I) {
4436 SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT);
4437 SDValue TmpIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset);
4439 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT,
4441 NewOps.push_back(Elt);
4444 SDValue NewVec = DAG.getBuildVector(MidVT, SL, NewOps);
4445 Results.push_back(DAG.getNode(ISD::BITCAST, SL, EltVT, NewVec));
4448 case ISD::INSERT_VECTOR_ELT: {
4449 MVT EltVT = OVT.getVectorElementType();
4450 MVT NewEltVT = NVT.getVectorElementType();
4452 // Handle bitcasts to a different vector type with the same total bit size
4454 // e.g. v2i64 = insert_vector_elt x:v2i64, y:i64, z:i32
4456 // v4i32:castx = bitcast x:v2i64
4457 // v2i32:casty = bitcast y:i64
4460 // (v4i32 insert_vector_elt
4461 // (v4i32 insert_vector_elt v4i32:castx,
4462 // (extract_vector_elt casty, 0), 2 * z),
4463 // (extract_vector_elt casty, 1), (2 * z + 1))
4465 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
4466 "Invalid promote type for insert_vector_elt");
4467 assert(NewEltVT.bitsLT(EltVT) && "not handled");
4469 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4470 unsigned NewEltsPerOldElt = MidVT.getVectorNumElements();
4472 SDValue Val = Node->getOperand(1);
4473 SDValue Idx = Node->getOperand(2);
4474 EVT IdxVT = Idx.getValueType();
4477 SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SDLoc(), IdxVT);
4478 SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor);
4480 SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0));
4481 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val);
4483 SDValue NewVec = CastVec;
4484 for (unsigned I = 0; I < NewEltsPerOldElt; ++I) {
4485 SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT);
4486 SDValue InEltIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset);
4488 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT,
4489 CastVal, IdxOffset);
4491 NewVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, NVT,
4492 NewVec, Elt, InEltIdx);
4495 Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewVec));
4498 case ISD::SCALAR_TO_VECTOR: {
4499 MVT EltVT = OVT.getVectorElementType();
4500 MVT NewEltVT = NVT.getVectorElementType();
4502 // Handle bitcasts to different vector type with the same total bit size.
4504 // e.g. v2i64 = scalar_to_vector x:i64
4506 // concat_vectors (v2i32 bitcast x:i64), (v2i32 undef)
4509 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4510 SDValue Val = Node->getOperand(0);
4513 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val);
4514 SDValue Undef = DAG.getUNDEF(MidVT);
4516 SmallVector<SDValue, 8> NewElts;
4517 NewElts.push_back(CastVal);
4518 for (unsigned I = 1, NElts = OVT.getVectorNumElements(); I != NElts; ++I)
4519 NewElts.push_back(Undef);
4521 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewElts);
4522 SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat);
4523 Results.push_back(CvtVec);
4528 // Replace the original node with the legalized result.
4529 if (!Results.empty())
4530 ReplaceNode(Node, Results.data());
4533 /// This is the entry point for the file.
4534 void SelectionDAG::Legalize() {
4535 AssignTopologicalOrder();
4537 SmallPtrSet<SDNode *, 16> LegalizedNodes;
4538 SelectionDAGLegalize Legalizer(*this, LegalizedNodes);
4540 // Visit all the nodes. We start in topological order, so that we see
4541 // nodes with their original operands intact. Legalization can produce
4542 // new nodes which may themselves need to be legalized. Iterate until all
4543 // nodes have been legalized.
4545 bool AnyLegalized = false;
4546 for (auto NI = allnodes_end(); NI != allnodes_begin();) {
4550 if (N->use_empty() && N != getRoot().getNode()) {
4556 if (LegalizedNodes.insert(N).second) {
4557 AnyLegalized = true;
4558 Legalizer.LegalizeOp(N);
4560 if (N->use_empty() && N != getRoot().getNode()) {
4571 // Remove dead nodes now.
4575 bool SelectionDAG::LegalizeOp(SDNode *N,
4576 SmallSetVector<SDNode *, 16> &UpdatedNodes) {
4577 SmallPtrSet<SDNode *, 16> LegalizedNodes;
4578 SelectionDAGLegalize Legalizer(*this, LegalizedNodes, &UpdatedNodes);
4580 // Directly insert the node in question, and legalize it. This will recurse
4581 // as needed through operands.
4582 LegalizedNodes.insert(N);
4583 Legalizer.LegalizeOp(N);
4585 return LegalizedNodes.count(N);