LLVM 24.0.0git
LegalizeDAG.cpp
Go to the documentation of this file.
1//===- LegalizeDAG.cpp - Implement SelectionDAG::Legalize -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the SelectionDAG::Legalize method.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/ADT/APFloat.h"
14#include "llvm/ADT/APInt.h"
15#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/SetVector.h"
19#include "llvm/ADT/SmallSet.h"
21#include "llvm/ADT/StringRef.h"
37#include "llvm/IR/CallingConv.h"
38#include "llvm/IR/Constants.h"
39#include "llvm/IR/DataLayout.h"
41#include "llvm/IR/Function.h"
42#include "llvm/IR/Metadata.h"
43#include "llvm/IR/Type.h"
46#include "llvm/Support/Debug.h"
52#include <cassert>
53#include <cstdint>
54#include <tuple>
55#include <utility>
56
57using namespace llvm;
58
59#define DEBUG_TYPE "legalizedag"
60
61namespace {
62
63/// Keeps track of state when getting the sign of a floating-point value as an
64/// integer.
65struct FloatSignAsInt {
66 EVT FloatVT;
67 SDValue Chain;
68 SDValue FloatPtr;
69 SDValue IntPtr;
70 MachinePointerInfo IntPointerInfo;
71 MachinePointerInfo FloatPointerInfo;
72 SDValue IntValue;
73 APInt SignMask;
74 uint8_t SignBit;
75};
76
77//===----------------------------------------------------------------------===//
78/// This takes an arbitrary SelectionDAG as input and
79/// hacks on it until the target machine can handle it. This involves
80/// eliminating value sizes the machine cannot handle (promoting small sizes to
81/// large sizes or splitting up large values into small values) as well as
82/// eliminating operations the machine cannot handle.
83///
84/// This code also does a small amount of optimization and recognition of idioms
85/// as part of its processing. For example, if a target does not support a
86/// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
87/// will attempt merge setcc and brc instructions into brcc's.
88class SelectionDAGLegalize {
89 const TargetMachine &TM;
90 const TargetLowering &TLI;
91 SelectionDAG &DAG;
92
93 /// The set of nodes which have already been legalized. We hold a
94 /// reference to it in order to update as necessary on node deletion.
95 SmallPtrSetImpl<SDNode *> &LegalizedNodes;
96
97 /// A set of all the nodes updated during legalization.
98 SmallSetVector<SDNode *, 16> *UpdatedNodes;
99
100 EVT getSetCCResultType(EVT VT) const {
101 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
102 }
103
104 // Libcall insertion helpers.
105
106public:
107 SelectionDAGLegalize(SelectionDAG &DAG,
108 SmallPtrSetImpl<SDNode *> &LegalizedNodes,
109 SmallSetVector<SDNode *, 16> *UpdatedNodes = nullptr)
110 : TM(DAG.getTarget()), TLI(DAG.getTargetLoweringInfo()), DAG(DAG),
111 LegalizedNodes(LegalizedNodes), UpdatedNodes(UpdatedNodes) {}
112
113 /// Legalizes the given operation.
114 void LegalizeOp(SDNode *Node);
115
116private:
117 SDValue OptimizeFloatStore(StoreSDNode *ST);
118
119 void LegalizeLoadOps(SDNode *Node);
120 void LegalizeStoreOps(SDNode *Node);
121
122 SDValue ExpandINSERT_VECTOR_ELT(SDValue Op);
123
124 /// Return a vector shuffle operation which
125 /// performs the same shuffe in terms of order or result bytes, but on a type
126 /// whose vector element type is narrower than the original shuffle type.
127 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
128 SDValue ShuffleWithNarrowerEltType(EVT NVT, EVT VT, const SDLoc &dl,
129 SDValue N1, SDValue N2,
130 ArrayRef<int> Mask) const;
131
132 std::pair<SDValue, SDValue> ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
134 bool IsSigned, EVT RetVT);
135 std::pair<SDValue, SDValue> ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned);
136
137 void ExpandFPLibCall(SDNode *Node, RTLIB::Libcall LC,
139
140 void
141 ExpandFastFPLibCall(SDNode *Node, bool IsFast,
142 std::pair<RTLIB::Libcall, RTLIB::Libcall> Call_F32,
143 std::pair<RTLIB::Libcall, RTLIB::Libcall> Call_F64,
144 std::pair<RTLIB::Libcall, RTLIB::Libcall> Call_F80,
145 std::pair<RTLIB::Libcall, RTLIB::Libcall> Call_F128,
146 std::pair<RTLIB::Libcall, RTLIB::Libcall> Call_PPCF128,
148
149 SDValue ExpandIntLibCall(SDNode *Node, bool isSigned, RTLIB::Libcall Call_I8,
150 RTLIB::Libcall Call_I16, RTLIB::Libcall Call_I32,
151 RTLIB::Libcall Call_I64, RTLIB::Libcall Call_I128);
152 void ExpandArgFPLibCall(SDNode *Node,
153 RTLIB::Libcall Call_F32, RTLIB::Libcall Call_F64,
154 RTLIB::Libcall Call_F80, RTLIB::Libcall Call_F128,
155 RTLIB::Libcall Call_PPCF128,
157 SDValue ExpandBitCountingLibCall(SDNode *Node, RTLIB::Libcall CallI32,
158 RTLIB::Libcall CallI64,
159 RTLIB::Libcall CallI128);
160 void ExpandDivRemLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results);
161
162 SDValue ExpandSincosStretLibCall(SDNode *Node) const;
163
164 SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT,
165 const SDLoc &dl);
166 SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT,
167 const SDLoc &dl, SDValue ChainIn);
168 SDValue ExpandBUILD_VECTOR(SDNode *Node);
169 SDValue ExpandSPLAT_VECTOR(SDNode *Node);
170 SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
171 void ExpandDYNAMIC_STACKALLOC(SDNode *Node,
173 void getSignAsIntValue(FloatSignAsInt &State, const SDLoc &DL,
174 SDValue Value) const;
175 SDValue modifySignAsInt(const FloatSignAsInt &State, const SDLoc &DL,
176 SDValue NewIntValue) const;
177 SDValue ExpandFCOPYSIGN(SDNode *Node) const;
178 SDValue ExpandFABS(SDNode *Node) const;
179 SDValue ExpandFNEG(SDNode *Node) const;
180 SDValue expandLdexp(SDNode *Node) const;
181 SDValue expandFrexp(SDNode *Node) const;
182
183 SDValue ExpandLegalINT_TO_FP(SDNode *Node, SDValue &Chain);
184 void PromoteLegalINT_TO_FP(SDNode *N, const SDLoc &dl,
186 void PromoteLegalFP_TO_INT(SDNode *N, const SDLoc &dl,
188 SDValue PromoteLegalFP_TO_INT_SAT(SDNode *Node, const SDLoc &dl);
189
190 /// Implements vector reduce operation promotion.
191 ///
192 /// All vector operands are promoted to a vector type with larger element
193 /// type, and the start value is promoted to a larger scalar type. Then the
194 /// result is truncated back to the original scalar type.
195 SDValue PromoteReduction(SDNode *Node);
196
197 SDValue ExpandPARITY(SDValue Op, const SDLoc &dl);
198
199 SDValue ExpandExtractFromVectorThroughStack(SDValue Op);
200 SDValue ExpandInsertToVectorThroughStack(SDValue Op);
201 SDValue ExpandVectorBuildThroughStack(SDNode* Node);
202 SDValue ExpandConcatVectors(SDNode *Node);
203
204 SDValue ExpandConstantFP(ConstantFPSDNode *CFP);
205 SDValue ExpandConstant(ConstantSDNode *CP);
206
207 // if ExpandNode returns false, LegalizeOp falls back to ConvertNodeToLibcall
208 bool ExpandNode(SDNode *Node);
209 void ConvertNodeToLibcall(SDNode *Node);
210 void PromoteNode(SDNode *Node);
211
212public:
213 // Node replacement helpers
214
215 void ReplacedNode(SDNode *N) {
216 LegalizedNodes.erase(N);
217 if (UpdatedNodes)
218 UpdatedNodes->insert(N);
219 }
220
221 void ReplaceNode(SDNode *Old, SDNode *New) {
222 LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
223 dbgs() << " with: "; New->dump(&DAG));
224
225 assert(Old->getNumValues() == New->getNumValues() &&
226 "Replacing one node with another that produces a different number "
227 "of values!");
228 DAG.ReplaceAllUsesWith(Old, New);
229 if (UpdatedNodes)
230 UpdatedNodes->insert(New);
231 ReplacedNode(Old);
232 }
233
234 void ReplaceNode(SDValue Old, SDValue New) {
235 LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
236 dbgs() << " with: "; New->dump(&DAG));
237
238 DAG.ReplaceAllUsesWith(Old, New);
239 if (UpdatedNodes)
240 UpdatedNodes->insert(New.getNode());
241 ReplacedNode(Old.getNode());
242 }
243
244 void ReplaceNode(SDNode *Old, const SDValue *New) {
245 LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG));
246
247 DAG.ReplaceAllUsesWith(Old, New);
248 for (unsigned i = 0, e = Old->getNumValues(); i != e; ++i) {
249 LLVM_DEBUG(dbgs() << (i == 0 ? " with: " : " and: ");
250 New[i]->dump(&DAG));
251 if (UpdatedNodes)
252 UpdatedNodes->insert(New[i].getNode());
253 }
254 ReplacedNode(Old);
255 }
256
257 void ReplaceNodeWithValue(SDValue Old, SDValue New) {
258 LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
259 dbgs() << " with: "; New->dump(&DAG));
260
261 DAG.ReplaceAllUsesOfValueWith(Old, New);
262 if (UpdatedNodes)
263 UpdatedNodes->insert(New.getNode());
264 ReplacedNode(Old.getNode());
265 }
266};
267
268} // end anonymous namespace
269
270[[maybe_unused]] static bool hasAtomicLibcallLowering(unsigned Opc) {
271 switch (Opc) {
273 case ISD::ATOMIC_SWAP:
286 return true;
287 default:
288 return false;
289 }
290}
291
292// Helper function that generates an MMO that considers the alignment of the
293// stack, and the size of the stack object
295 MachineFunction &MF,
296 bool isObjectScalable) {
297 auto &MFI = MF.getFrameInfo();
298 int FI = cast<FrameIndexSDNode>(StackPtr)->getIndex();
300 LocationSize ObjectSize = isObjectScalable
302 : LocationSize::precise(MFI.getObjectSize(FI));
304 ObjectSize, MFI.getObjectAlign(FI));
305}
306
307/// Return a vector shuffle operation which
308/// performs the same shuffle in terms of order or result bytes, but on a type
309/// whose vector element type is narrower than the original shuffle type.
310/// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
311SDValue SelectionDAGLegalize::ShuffleWithNarrowerEltType(
312 EVT NVT, EVT VT, const SDLoc &dl, SDValue N1, SDValue N2,
313 ArrayRef<int> Mask) const {
314 unsigned NumMaskElts = VT.getVectorNumElements();
315 unsigned NumDestElts = NVT.getVectorNumElements();
316 unsigned NumEltsGrowth = NumDestElts / NumMaskElts;
317
318 assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
319
320 if (NumEltsGrowth == 1)
321 return DAG.getVectorShuffle(NVT, dl, N1, N2, Mask);
322
323 SmallVector<int, 8> NewMask;
324 for (unsigned i = 0; i != NumMaskElts; ++i) {
325 int Idx = Mask[i];
326 for (unsigned j = 0; j != NumEltsGrowth; ++j) {
327 if (Idx < 0)
328 NewMask.push_back(-1);
329 else
330 NewMask.push_back(Idx * NumEltsGrowth + j);
331 }
332 }
333 assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?");
334 assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?");
335 return DAG.getVectorShuffle(NVT, dl, N1, N2, NewMask);
336}
337
338/// Expands the ConstantFP node to a load from the constant pool.
339SDValue SelectionDAGLegalize::ExpandConstantFP(ConstantFPSDNode *CFP) {
340 bool Extend = false;
341 SDLoc dl(CFP);
342
343 // If a FP immediate is precise when represented as a float and if the
344 // target can do an extending load from float to double, we put it into
345 // the constant pool as a float, even if it's is statically typed as a
346 // double. This shrinks FP constants and canonicalizes them for targets where
347 // an FP extending load is the same cost as a normal load (such as on the x87
348 // fp stack or PPC FP unit).
349 EVT VT = CFP->getValueType(0);
350 ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
351
352 APFloat APF = CFP->getValueAPF();
353 EVT OrigVT = VT;
354 EVT SVT = VT;
355
356 // We don't want to shrink SNaNs. Converting the SNaN back to its real type
357 // can cause it to be changed into a QNaN on some platforms (e.g. on SystemZ).
358 if (!APF.isSignaling()) {
359 while (SVT != MVT::f32 && SVT != MVT::f16 && SVT != MVT::bf16) {
360 SVT = (MVT::SimpleValueType)(SVT.getSimpleVT().SimpleTy - 1);
362 // Only do this if the target has a native EXTLOAD instruction from
363 // smaller type.
365 OrigVT, SVT,
367 SVT.getTypeForEVT(*DAG.getContext()))),
369 .getAddrSpace(),
370 ISD::EXTLOAD, false) &&
371 TLI.ShouldShrinkFPConstant(OrigVT)) {
372 Type *SType = SVT.getTypeForEVT(*DAG.getContext());
374 Instruction::FPTrunc, LLVMC, SType, DAG.getDataLayout()));
375 VT = SVT;
376 Extend = true;
377 }
378 }
379 }
380
381 SDValue CPIdx =
383 Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign();
384 if (Extend) {
386 ISD::EXTLOAD, dl, OrigVT, DAG.getEntryNode(), CPIdx,
388 Alignment);
389 return Result;
390 }
391 SDValue Result = DAG.getLoad(
392 OrigVT, dl, DAG.getEntryNode(), CPIdx,
394 return Result;
395}
396
397/// Expands the Constant node to a load from the constant pool.
398SDValue SelectionDAGLegalize::ExpandConstant(ConstantSDNode *CP) {
399 SDLoc dl(CP);
400 EVT VT = CP->getValueType(0);
403 Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign();
404 SDValue Result = DAG.getLoad(
405 VT, dl, DAG.getEntryNode(), CPIdx,
407 return Result;
408}
409
410SDValue SelectionDAGLegalize::ExpandINSERT_VECTOR_ELT(SDValue Op) {
411 SDValue Vec = Op.getOperand(0);
412 SDValue Val = Op.getOperand(1);
413 SDValue Idx = Op.getOperand(2);
414 SDLoc dl(Op);
415
416 if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) {
417 // SCALAR_TO_VECTOR requires that the type of the value being inserted
418 // match the element type of the vector being created, except for
419 // integers in which case the inserted value can be over width.
420 EVT EltVT = Vec.getValueType().getVectorElementType();
421 if (Val.getValueType() == EltVT ||
422 (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) {
423 SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
424 Vec.getValueType(), Val);
425
426 unsigned NumElts = Vec.getValueType().getVectorNumElements();
427 // We generate a shuffle of InVec and ScVec, so the shuffle mask
428 // should be 0,1,2,3,4,5... with the appropriate element replaced with
429 // elt 0 of the RHS.
430 SmallVector<int, 8> ShufOps;
431 for (unsigned i = 0; i != NumElts; ++i)
432 ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts);
433
434 return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec, ShufOps);
435 }
436 }
437 return ExpandInsertToVectorThroughStack(Op);
438}
439
440SDValue SelectionDAGLegalize::OptimizeFloatStore(StoreSDNode* ST) {
441 if (!ISD::isNormalStore(ST))
442 return SDValue();
443
444 LLVM_DEBUG(dbgs() << "Optimizing float store operations\n");
445 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
446 // FIXME: move this to the DAG Combiner! Note that we can't regress due
447 // to phase ordering between legalized code and the dag combiner. This
448 // probably means that we need to integrate dag combiner and legalizer
449 // together.
450 // We generally can't do this one for long doubles.
451 SDValue Chain = ST->getChain();
452 SDValue Ptr = ST->getBasePtr();
453 SDValue Value = ST->getValue();
454 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
455 AAMDNodes AAInfo = ST->getAAInfo();
456 SDLoc dl(ST);
457
458 // Don't optimise TargetConstantFP
459 if (Value.getOpcode() == ISD::TargetConstantFP)
460 return SDValue();
461
462 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
463 if (CFP->getValueType(0) == MVT::f32 &&
464 TLI.isTypeLegal(MVT::i32)) {
465 SDValue Con = DAG.getConstant(CFP->getValueAPF().
466 bitcastToAPInt().zextOrTrunc(32),
467 SDLoc(CFP), MVT::i32);
468 return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(),
469 ST->getBaseAlign(), MMOFlags, AAInfo);
470 }
471
472 if (CFP->getValueType(0) == MVT::f64 &&
473 !TLI.isFPImmLegal(CFP->getValueAPF(), MVT::f64)) {
474 // If this target supports 64-bit registers, do a single 64-bit store.
475 if (TLI.isTypeLegal(MVT::i64)) {
477 zextOrTrunc(64), SDLoc(CFP), MVT::i64);
478 return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(),
479 ST->getBaseAlign(), MMOFlags, AAInfo);
480 }
481
482 if (TLI.isTypeLegal(MVT::i32) && !ST->isVolatile()) {
483 // Otherwise, if the target supports 32-bit registers, use 2 32-bit
484 // stores. If the target supports neither 32- nor 64-bits, this
485 // xform is certainly not worth it.
486 const APInt &IntVal = CFP->getValueAPF().bitcastToAPInt();
487 SDValue Lo = DAG.getConstant(IntVal.trunc(32), dl, MVT::i32);
488 SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), dl, MVT::i32);
489 if (DAG.getDataLayout().isBigEndian())
490 std::swap(Lo, Hi);
491
492 Lo = DAG.getStore(Chain, dl, Lo, Ptr, ST->getPointerInfo(),
493 ST->getBaseAlign(), MMOFlags, AAInfo);
494 Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::getFixed(4), dl);
495 Hi = DAG.getStore(Chain, dl, Hi, Ptr,
496 ST->getPointerInfo().getWithOffset(4),
497 ST->getBaseAlign(), MMOFlags, AAInfo);
498
499 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
500 }
501 }
502 }
503 return SDValue();
504}
505
506void SelectionDAGLegalize::LegalizeStoreOps(SDNode *Node) {
507 StoreSDNode *ST = cast<StoreSDNode>(Node);
508 SDValue Chain = ST->getChain();
509 SDValue Ptr = ST->getBasePtr();
510 SDLoc dl(Node);
511
512 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
513 MMOMetadata Metadata = ST->getMMOMetadataForSubAccess();
514
515 if (!ST->isTruncatingStore()) {
516 LLVM_DEBUG(dbgs() << "Legalizing store operation\n");
517 if (SDNode *OptStore = OptimizeFloatStore(ST).getNode()) {
518 ReplaceNode(ST, OptStore);
519 return;
520 }
521
522 SDValue Value = ST->getValue();
523 MVT VT = Value.getSimpleValueType();
524 switch (TLI.getOperationAction(ISD::STORE, VT)) {
525 default: llvm_unreachable("This action is not supported yet!");
526 case TargetLowering::Legal: {
527 // If this is an unaligned store and the target doesn't support it,
528 // expand it.
529 EVT MemVT = ST->getMemoryVT();
530 const DataLayout &DL = DAG.getDataLayout();
532 *ST->getMemOperand())) {
533 LLVM_DEBUG(dbgs() << "Expanding unsupported unaligned store\n");
535 ReplaceNode(SDValue(ST, 0), Result);
536 } else
537 LLVM_DEBUG(dbgs() << "Legal store\n");
538 break;
539 }
540 case TargetLowering::Custom: {
541 LLVM_DEBUG(dbgs() << "Trying custom lowering\n");
542 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
543 if (Res && Res != SDValue(Node, 0))
544 ReplaceNode(SDValue(Node, 0), Res);
545 return;
546 }
547 case TargetLowering::Promote: {
548 MVT NVT = TLI.getTypeToPromoteTo(ISD::STORE, VT);
549 assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
550 "Can only promote stores to same size type");
551 Value = DAG.getNode(ISD::BITCAST, dl, NVT, Value);
552 SDValue Result = DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
553 ST->getBaseAlign(), MMOFlags, Metadata);
554 ReplaceNode(SDValue(Node, 0), Result);
555 break;
556 }
557 case TargetLowering::Expand:
558 assert(VT.isVector() && "Cannot expand a scalar store");
559 ReplaceNode(SDValue(Node, 0), TLI.scalarizeVectorStore(ST, DAG));
560 break;
561 }
562 return;
563 }
564
565 LLVM_DEBUG(dbgs() << "Legalizing truncating store operations\n");
566 SDValue Value = ST->getValue();
567 EVT StVT = ST->getMemoryVT();
568 TypeSize StWidth = StVT.getSizeInBits();
569 TypeSize StSize = StVT.getStoreSizeInBits();
570 auto &DL = DAG.getDataLayout();
571
572 if (StWidth != StSize) {
573 // Promote to a byte-sized store with upper bits zero if not
574 // storing an integral number of bytes. For example, promote
575 // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
576 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), StSize.getFixedValue());
577 Value = DAG.getZeroExtendInReg(Value, dl, StVT);
579 DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), NVT,
580 ST->getBaseAlign(), MMOFlags, Metadata);
581 ReplaceNode(SDValue(Node, 0), Result);
582 } else if (!StVT.isVector() && !isPowerOf2_64(StWidth.getFixedValue())) {
583 // If not storing a power-of-2 number of bits, expand as two stores.
584 assert(!StVT.isVector() && "Unsupported truncstore!");
585 unsigned StWidthBits = StWidth.getFixedValue();
586 unsigned LogStWidth = Log2_32(StWidthBits);
587 assert(LogStWidth < 32);
588 unsigned RoundWidth = 1 << LogStWidth;
589 assert(RoundWidth < StWidthBits);
590 unsigned ExtraWidth = StWidthBits - RoundWidth;
591 assert(ExtraWidth < RoundWidth);
592 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
593 "Store size not an integral number of bytes!");
594 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
595 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
596 SDValue Lo, Hi;
597 unsigned IncrementSize;
598
599 if (DL.isLittleEndian()) {
600 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
601 // Store the bottom RoundWidth bits.
602 Lo = DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
603 RoundVT, ST->getBaseAlign(), MMOFlags, Metadata);
604
605 // Store the remaining ExtraWidth bits.
606 IncrementSize = RoundWidth / 8;
607 Ptr =
608 DAG.getMemBasePlusOffset(Ptr, TypeSize::getFixed(IncrementSize), dl);
609 Hi = DAG.getNode(
610 ISD::SRL, dl, Value.getValueType(), Value,
611 DAG.getShiftAmountConstant(RoundWidth, Value.getValueType(), dl));
612 Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr,
613 ST->getPointerInfo().getWithOffset(IncrementSize),
614 ExtraVT, ST->getBaseAlign(), MMOFlags, Metadata);
615 } else {
616 // Big endian - avoid unaligned stores.
617 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
618 // Store the top RoundWidth bits.
619 Hi = DAG.getNode(
620 ISD::SRL, dl, Value.getValueType(), Value,
621 DAG.getShiftAmountConstant(ExtraWidth, Value.getValueType(), dl));
622 Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr, ST->getPointerInfo(), RoundVT,
623 ST->getBaseAlign(), MMOFlags, Metadata);
624
625 // Store the remaining ExtraWidth bits.
626 IncrementSize = RoundWidth / 8;
627 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
628 DAG.getConstant(IncrementSize, dl,
629 Ptr.getValueType()));
630 Lo = DAG.getTruncStore(Chain, dl, Value, Ptr,
631 ST->getPointerInfo().getWithOffset(IncrementSize),
632 ExtraVT, ST->getBaseAlign(), MMOFlags, Metadata);
633 }
634
635 // The order of the stores doesn't matter.
636 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
637 ReplaceNode(SDValue(Node, 0), Result);
638 } else {
639 switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT,
640 ST->getAlign(), ST->getAddressSpace())) {
641 default:
642 llvm_unreachable("This action is not supported yet!");
643 case TargetLowering::Legal: {
644 EVT MemVT = ST->getMemoryVT();
645 // If this is an unaligned store and the target doesn't support it,
646 // expand it.
648 *ST->getMemOperand())) {
650 ReplaceNode(SDValue(ST, 0), Result);
651 }
652 break;
653 }
654 case TargetLowering::Custom: {
655 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
656 if (Res && Res != SDValue(Node, 0))
657 ReplaceNode(SDValue(Node, 0), Res);
658 return;
659 }
660 case TargetLowering::Expand:
661 assert(!StVT.isVector() &&
662 "Vector Stores are handled in LegalizeVectorOps");
663
665
666 // TRUNCSTORE:i16 i32 -> STORE i16
667 if (TLI.isTypeLegal(StVT)) {
668 Value = DAG.getNode(ISD::TRUNCATE, dl, StVT, Value);
669 Result = DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
670 ST->getBaseAlign(), MMOFlags, Metadata);
671 } else {
672 // The in-memory type isn't legal. Truncate to the type it would promote
673 // to, and then do a truncstore.
674 Value = DAG.getNode(ISD::TRUNCATE, dl,
675 TLI.getTypeToTransformTo(*DAG.getContext(), StVT),
676 Value);
677 Result =
678 DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), StVT,
679 ST->getBaseAlign(), MMOFlags, Metadata);
680 }
681
682 ReplaceNode(SDValue(Node, 0), Result);
683 break;
684 }
685 }
686}
687
688void SelectionDAGLegalize::LegalizeLoadOps(SDNode *Node) {
689 LoadSDNode *LD = cast<LoadSDNode>(Node);
690 SDValue Chain = LD->getChain(); // The chain.
691 SDValue Ptr = LD->getBasePtr(); // The base pointer.
692 SDValue Value; // The value returned by the load op.
693 SDLoc dl(Node);
694
695 ISD::LoadExtType ExtType = LD->getExtensionType();
696 if (ExtType == ISD::NON_EXTLOAD) {
697 LLVM_DEBUG(dbgs() << "Legalizing non-extending load operation\n");
698 MVT VT = Node->getSimpleValueType(0);
699 SDValue RVal = SDValue(Node, 0);
700 SDValue RChain = SDValue(Node, 1);
701
702 switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
703 default: llvm_unreachable("This action is not supported yet!");
704 case TargetLowering::Legal: {
705 EVT MemVT = LD->getMemoryVT();
706 const DataLayout &DL = DAG.getDataLayout();
707 // If this is an unaligned load and the target doesn't support it,
708 // expand it.
710 *LD->getMemOperand())) {
711 std::tie(RVal, RChain) = TLI.expandUnalignedLoad(LD, DAG);
712 }
713 break;
714 }
715 case TargetLowering::Custom:
716 if (SDValue Res = TLI.LowerOperation(RVal, DAG)) {
717 RVal = Res;
718 RChain = Res.getValue(1);
719 }
720 break;
721
722 case TargetLowering::Promote: {
723 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
724 assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
725 "Can only promote loads to same size type");
726
727 // If the range metadata type does not match the legalized memory
728 // operation type, remove the range metadata.
729 if (const MDNode *MD = LD->getRanges()) {
730 ConstantInt *Lower = mdconst::extract<ConstantInt>(MD->getOperand(0));
731 if (Lower->getBitWidth() != NVT.getScalarSizeInBits() ||
732 !NVT.isInteger())
733 LD->getMemOperand()->clearRanges();
734 }
735 SDValue Res = DAG.getLoad(NVT, dl, Chain, Ptr, LD->getMemOperand());
736 RVal = DAG.getNode(ISD::BITCAST, dl, VT, Res);
737 RChain = Res.getValue(1);
738 break;
739 }
740 case TargetLowering::Expand:
741 assert(VT.isVector() && "Cannot expand a scalar load");
742 std::tie(RVal, RChain) = TLI.scalarizeVectorLoad(LD, DAG);
743 break;
744 }
745 if (RChain.getNode() != Node) {
746 assert(RVal.getNode() != Node && "Load must be completely replaced");
747 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), RVal);
748 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), RChain);
749 if (UpdatedNodes) {
750 UpdatedNodes->insert(RVal.getNode());
751 UpdatedNodes->insert(RChain.getNode());
752 }
753 ReplacedNode(Node);
754 }
755 return;
756 }
757
758 LLVM_DEBUG(dbgs() << "Legalizing extending load operation\n");
759 EVT SrcVT = LD->getMemoryVT();
760 TypeSize SrcWidth = SrcVT.getSizeInBits();
761 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
762 MMOMetadata Metadata = LD->getMMOMetadataForSubAccess();
763
764 if (SrcWidth != SrcVT.getStoreSizeInBits() &&
765 // Some targets pretend to have an i1 loading operation, and actually
766 // load an i8. This trick is correct for ZEXTLOAD because the top 7
767 // bits are guaranteed to be zero; it helps the optimizers understand
768 // that these bits are zero. It is also useful for EXTLOAD, since it
769 // tells the optimizers that those bits are undefined. It would be
770 // nice to have an effective generic way of getting these benefits...
771 // Until such a way is found, don't insist on promoting i1 here.
772 (SrcVT != MVT::i1 ||
773 TLI.getLoadAction(Node->getValueType(0), MVT::i1, LD->getAlign(),
774 LD->getAddressSpace(), ExtType,
775 false) == TargetLowering::Promote)) {
776 // Promote to a byte-sized load if not loading an integral number of
777 // bytes. For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
778 unsigned NewWidth = SrcVT.getStoreSizeInBits();
779 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), NewWidth);
780 SDValue Ch;
781
782 // The extra bits are guaranteed to be zero, since we stored them that
783 // way. A zext load from NVT thus automatically gives zext from SrcVT.
784
785 ISD::LoadExtType NewExtType =
787
788 SDValue Result = DAG.getExtLoad(NewExtType, dl, Node->getValueType(0),
789 Chain, Ptr, LD->getPointerInfo(), NVT,
790 LD->getBaseAlign(), MMOFlags, Metadata);
791
792 Ch = Result.getValue(1); // The chain.
793
794 if (ExtType == ISD::SEXTLOAD)
795 // Having the top bits zero doesn't help when sign extending.
797 Result.getValueType(),
798 Result, DAG.getValueType(SrcVT));
799 else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
800 // All the top bits are guaranteed to be zero - inform the optimizers.
802 Result.getValueType(), Result,
803 DAG.getValueType(SrcVT));
804
805 Value = Result;
806 Chain = Ch;
807 } else if (!isPowerOf2_64(SrcWidth.getKnownMinValue())) {
808 // If not loading a power-of-2 number of bits, expand as two loads.
809 assert(!SrcVT.isVector() && "Unsupported extload!");
810 unsigned SrcWidthBits = SrcWidth.getFixedValue();
811 unsigned LogSrcWidth = Log2_32(SrcWidthBits);
812 assert(LogSrcWidth < 32);
813 unsigned RoundWidth = 1 << LogSrcWidth;
814 assert(RoundWidth < SrcWidthBits);
815 unsigned ExtraWidth = SrcWidthBits - RoundWidth;
816 assert(ExtraWidth < RoundWidth);
817 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
818 "Load size not an integral number of bytes!");
819 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
820 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
821 SDValue Lo, Hi, Ch;
822 unsigned IncrementSize;
823 auto &DL = DAG.getDataLayout();
824
825 if (DL.isLittleEndian()) {
826 // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
827 // Load the bottom RoundWidth bits.
828 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0), Chain, Ptr,
829 LD->getPointerInfo(), RoundVT, LD->getBaseAlign(),
830 MMOFlags, Metadata);
831
832 // Load the remaining ExtraWidth bits.
833 IncrementSize = RoundWidth / 8;
834 Ptr =
835 DAG.getMemBasePlusOffset(Ptr, TypeSize::getFixed(IncrementSize), dl);
836 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
837 LD->getPointerInfo().getWithOffset(IncrementSize),
838 ExtraVT, LD->getBaseAlign(), MMOFlags, Metadata);
839
840 // Build a factor node to remember that this load is independent of
841 // the other one.
842 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
843 Hi.getValue(1));
844
845 // Move the top bits to the right place.
846 Hi = DAG.getNode(
847 ISD::SHL, dl, Hi.getValueType(), Hi,
848 DAG.getShiftAmountConstant(RoundWidth, Hi.getValueType(), dl));
849
850 // Join the hi and lo parts.
851 Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
852 } else {
853 // Big endian - avoid unaligned loads.
854 // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
855 // Load the top RoundWidth bits.
856 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
857 LD->getPointerInfo(), RoundVT, LD->getBaseAlign(),
858 MMOFlags, Metadata);
859
860 // Load the remaining ExtraWidth bits.
861 IncrementSize = RoundWidth / 8;
862 Ptr =
863 DAG.getMemBasePlusOffset(Ptr, TypeSize::getFixed(IncrementSize), dl);
864 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0), Chain, Ptr,
865 LD->getPointerInfo().getWithOffset(IncrementSize),
866 ExtraVT, LD->getBaseAlign(), MMOFlags, Metadata);
867
868 // Build a factor node to remember that this load is independent of
869 // the other one.
870 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
871 Hi.getValue(1));
872
873 // Move the top bits to the right place.
874 Hi = DAG.getNode(
875 ISD::SHL, dl, Hi.getValueType(), Hi,
876 DAG.getShiftAmountConstant(ExtraWidth, Hi.getValueType(), dl));
877
878 // Join the hi and lo parts.
879 Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
880 }
881
882 Chain = Ch;
883 } else {
884 bool isCustom = false;
885 switch (TLI.getLoadAction(Node->getValueType(0), SrcVT.getSimpleVT(),
886 LD->getAlign(), LD->getAddressSpace(), ExtType,
887 false)) {
888 default:
889 llvm_unreachable("This action is not supported yet!");
890 case TargetLowering::Custom:
891 isCustom = true;
892 [[fallthrough]];
893 case TargetLowering::Legal:
894 Value = SDValue(Node, 0);
895 Chain = SDValue(Node, 1);
896
897 if (isCustom) {
898 if (SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG)) {
899 Value = Res;
900 Chain = Res.getValue(1);
901 }
902 } else {
903 // If this is an unaligned load and the target doesn't support it,
904 // expand it.
905 EVT MemVT = LD->getMemoryVT();
906 const DataLayout &DL = DAG.getDataLayout();
907 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT,
908 *LD->getMemOperand())) {
909 std::tie(Value, Chain) = TLI.expandUnalignedLoad(LD, DAG);
910 }
911 }
912 break;
913
914 case TargetLowering::Expand: {
915 EVT DestVT = Node->getValueType(0);
916 if (!TLI.isLoadLegal(DestVT, SrcVT, LD->getAlign(), LD->getAddressSpace(),
917 ISD::EXTLOAD, false)) {
918 // If the source type is not legal, see if there is a legal extload to
919 // an intermediate type that we can then extend further.
920 EVT LoadVT =
921 TLI.getRegisterType(*DAG.getContext(), SrcVT.getSimpleVT());
922 if ((LoadVT.isFloatingPoint() == SrcVT.isFloatingPoint()) &&
923 (TLI.isTypeLegal(SrcVT) || // Same as SrcVT == LoadVT?
924 TLI.isLoadLegal(LoadVT, SrcVT, LD->getAlign(),
925 LD->getAddressSpace(), ExtType, false))) {
926 // If we are loading a legal type, this is a non-extload followed by a
927 // full extend.
928 ISD::LoadExtType MidExtType =
929 (LoadVT == SrcVT) ? ISD::NON_EXTLOAD : ExtType;
930
931 SDValue Load = DAG.getExtLoad(MidExtType, dl, LoadVT, Chain, Ptr,
932 SrcVT, LD->getMemOperand());
933 unsigned ExtendOp =
935 Value = DAG.getNode(ExtendOp, dl, Node->getValueType(0), Load);
936 Chain = Load.getValue(1);
937 break;
938 }
939
940 // Handle the special case of fp16 extloads. EXTLOAD doesn't have the
941 // normal undefined upper bits behavior to allow using an in-reg extend
942 // with the illegal FP type, so load as an integer and do the
943 // from-integer conversion.
944 EVT SVT = SrcVT.getScalarType();
945 if (SVT == MVT::f16 || SVT == MVT::bf16) {
946 EVT ISrcVT = SrcVT.changeTypeToInteger();
947 EVT IDestVT = DestVT.changeTypeToInteger();
948 EVT ILoadVT =
949 TLI.getRegisterType(*DAG.getContext(), IDestVT.getSimpleVT());
950
951 SDValue Result = DAG.getExtLoad(ISD::ZEXTLOAD, dl, ILoadVT, Chain,
952 Ptr, ISrcVT, LD->getMemOperand());
953 Value =
954 DAG.getNode(SVT == MVT::f16 ? ISD::FP16_TO_FP : ISD::BF16_TO_FP,
955 dl, DestVT, Result);
956 Chain = Result.getValue(1);
957 break;
958 }
959 }
960
961 assert(!SrcVT.isVector() &&
962 "Vector Loads are handled in LegalizeVectorOps");
963
964 // FIXME: This does not work for vectors on most targets. Sign-
965 // and zero-extend operations are currently folded into extending
966 // loads, whether they are legal or not, and then we end up here
967 // without any support for legalizing them.
968 assert(ExtType != ISD::EXTLOAD &&
969 "EXTLOAD should always be supported!");
970 // Turn the unsupported load into an EXTLOAD followed by an
971 // explicit zero/sign extend inreg.
973 Node->getValueType(0),
974 Chain, Ptr, SrcVT,
975 LD->getMemOperand());
976 SDValue ValRes;
977 if (ExtType == ISD::SEXTLOAD)
978 ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
979 Result.getValueType(),
980 Result, DAG.getValueType(SrcVT));
981 else
982 ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT);
983 Value = ValRes;
984 Chain = Result.getValue(1);
985 break;
986 }
987 }
988 }
989
990 // Since loads produce two values, make sure to remember that we legalized
991 // both of them.
992 if (Chain.getNode() != Node) {
993 assert(Value.getNode() != Node && "Load must be completely replaced");
995 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
996 if (UpdatedNodes) {
997 UpdatedNodes->insert(Value.getNode());
998 UpdatedNodes->insert(Chain.getNode());
999 }
1000 ReplacedNode(Node);
1001 }
1002}
1003
1004/// Return a legal replacement for the given operation, with all legal operands.
1005void SelectionDAGLegalize::LegalizeOp(SDNode *Node) {
1006 LLVM_DEBUG(dbgs() << "\nLegalizing: "; Node->dump(&DAG));
1007
1008 // Allow illegal target nodes and illegal registers.
1009 if (Node->getOpcode() == ISD::TargetConstant ||
1010 Node->getOpcode() == ISD::Register)
1011 return;
1012
1013#ifndef NDEBUG
1014 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
1015 assert(TLI.getTypeAction(*DAG.getContext(), Node->getValueType(i)) ==
1016 TargetLowering::TypeLegal &&
1017 "Unexpected illegal type!");
1018
1019 for (const SDValue &Op : Node->op_values())
1020 assert((TLI.getTypeAction(*DAG.getContext(), Op.getValueType()) ==
1021 TargetLowering::TypeLegal ||
1022 Op.getOpcode() == ISD::TargetConstant ||
1023 Op.getOpcode() == ISD::Register) &&
1024 "Unexpected illegal type!");
1025#endif
1026
1027 // Figure out the correct action; the way to query this varies by opcode
1028 TargetLowering::LegalizeAction Action = TargetLowering::Legal;
1029 bool SimpleFinishLegalizing = true;
1030 switch (Node->getOpcode()) {
1034 case ISD::STACKSAVE:
1035 case ISD::STACKADDRESS:
1036 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
1037 break;
1039 Action = TLI.getOperationAction(Node->getOpcode(),
1040 Node->getValueType(0));
1041 break;
1042 case ISD::VAARG:
1043 Action = TLI.getOperationAction(Node->getOpcode(),
1044 Node->getValueType(0));
1045 if (Action != TargetLowering::Promote)
1046 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
1047 break;
1048 case ISD::SET_FPENV:
1049 case ISD::SET_FPMODE:
1050 Action = TLI.getOperationAction(Node->getOpcode(),
1051 Node->getOperand(1).getValueType());
1052 break;
1053 case ISD::FP_TO_FP16:
1054 case ISD::FP_TO_BF16:
1055 case ISD::SINT_TO_FP:
1056 case ISD::UINT_TO_FP:
1058 case ISD::LROUND:
1059 case ISD::LLROUND:
1060 case ISD::LRINT:
1061 case ISD::LLRINT:
1062 Action = TLI.getOperationAction(Node->getOpcode(),
1063 Node->getOperand(0).getValueType());
1064 break;
1069 case ISD::STRICT_LRINT:
1070 case ISD::STRICT_LLRINT:
1071 case ISD::STRICT_LROUND:
1073 // These pseudo-ops are the same as the other STRICT_ ops except
1074 // they are registered with setOperationAction() using the input type
1075 // instead of the output type.
1076 Action = TLI.getOperationAction(Node->getOpcode(),
1077 Node->getOperand(1).getValueType());
1078 break;
1080 EVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT();
1081 Action = TLI.getOperationAction(Node->getOpcode(), InnerType);
1082 break;
1083 }
1084 case ISD::ATOMIC_STORE:
1085 Action = TLI.getOperationAction(Node->getOpcode(),
1086 Node->getOperand(1).getValueType());
1087 break;
1088 case ISD::ATOMIC_SWAP:
1101 Action = TLI.getOperationAction(Node->getOpcode(),
1102 cast<AtomicSDNode>(Node)->getMemoryVT());
1103 break;
1104 case ISD::SELECT_CC:
1105 case ISD::STRICT_FSETCC:
1107 case ISD::SETCC:
1108 case ISD::SETCCCARRY:
1109 case ISD::BR_CC: {
1110 unsigned Opc = Node->getOpcode();
1111 unsigned CCOperand = Opc == ISD::SELECT_CC ? 4
1112 : Opc == ISD::STRICT_FSETCC ? 3
1113 : Opc == ISD::STRICT_FSETCCS ? 3
1114 : Opc == ISD::SETCCCARRY ? 3
1115 : Opc == ISD::SETCC ? 2
1116 : 1;
1117 unsigned CompareOperand = Opc == ISD::BR_CC ? 2
1118 : Opc == ISD::STRICT_FSETCC ? 1
1119 : Opc == ISD::STRICT_FSETCCS ? 1
1120 : 0;
1121 MVT OpVT = Node->getOperand(CompareOperand).getSimpleValueType();
1122 ISD::CondCode CCCode = Node->getOperandCondCode(CCOperand);
1123 Action = TLI.getCondCodeAction(CCCode, OpVT);
1124 if (Action == TargetLowering::Legal) {
1125 if (Node->getOpcode() == ISD::SELECT_CC)
1126 Action = TLI.getOperationAction(Node->getOpcode(),
1127 Node->getValueType(0));
1128 else
1129 Action = TLI.getOperationAction(Node->getOpcode(), OpVT);
1130 }
1131 break;
1132 }
1133 case ISD::LOAD:
1134 case ISD::STORE:
1135 // FIXME: Model these properly. LOAD and STORE are complicated, and
1136 // STORE expects the unlegalized operand in some cases.
1137 SimpleFinishLegalizing = false;
1138 break;
1139 case ISD::CALLSEQ_START:
1140 case ISD::CALLSEQ_END:
1141 // FIXME: This shouldn't be necessary. These nodes have special properties
1142 // dealing with the recursive nature of legalization. Removing this
1143 // special case should be done as part of making LegalizeDAG non-recursive.
1144 SimpleFinishLegalizing = false;
1145 break;
1147 case ISD::GET_ROUNDING:
1148 case ISD::MERGE_VALUES:
1149 case ISD::EH_RETURN:
1151 case ISD::EH_DWARF_CFA:
1155 // These operations lie about being legal: when they claim to be legal,
1156 // they should actually be expanded.
1157 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1158 if (Action == TargetLowering::Legal)
1159 Action = TargetLowering::Expand;
1160 break;
1163 case ISD::FRAMEADDR:
1164 case ISD::RETURNADDR:
1166 case ISD::SPONENTRY:
1167 // These operations lie about being legal: when they claim to be legal,
1168 // they should actually be custom-lowered.
1169 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1170 if (Action == TargetLowering::Legal)
1171 Action = TargetLowering::Custom;
1172 break;
1173 case ISD::CLEAR_CACHE:
1174 // This operation is typically going to be LibCall unless the target wants
1175 // something differrent.
1176 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1177 break;
1180 // READCYCLECOUNTER and READSTEADYCOUNTER return a i64, even if type
1181 // legalization might have expanded that to several smaller types.
1182 Action = TLI.getOperationAction(Node->getOpcode(), MVT::i64);
1183 break;
1184 case ISD::READ_REGISTER:
1186 // Named register is legal in the DAG, but blocked by register name
1187 // selection if not implemented by target (to chose the correct register)
1188 // They'll be converted to Copy(To/From)Reg.
1189 Action = TargetLowering::Legal;
1190 break;
1191 case ISD::UBSANTRAP:
1192 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1193 if (Action == TargetLowering::Expand) {
1194 // replace ISD::UBSANTRAP with ISD::TRAP
1195 SDValue NewVal;
1196 NewVal = DAG.getNode(ISD::TRAP, SDLoc(Node), Node->getVTList(),
1197 Node->getOperand(0));
1198 ReplaceNode(Node, NewVal.getNode());
1199 LegalizeOp(NewVal.getNode());
1200 return;
1201 }
1202 break;
1203 case ISD::DEBUGTRAP:
1204 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1205 if (Action == TargetLowering::Expand) {
1206 // replace ISD::DEBUGTRAP with ISD::TRAP
1207 SDValue NewVal;
1208 NewVal = DAG.getNode(ISD::TRAP, SDLoc(Node), Node->getVTList(),
1209 Node->getOperand(0));
1210 ReplaceNode(Node, NewVal.getNode());
1211 LegalizeOp(NewVal.getNode());
1212 return;
1213 }
1214 break;
1215 case ISD::SADDSAT:
1216 case ISD::UADDSAT:
1217 case ISD::SSUBSAT:
1218 case ISD::USUBSAT:
1219 case ISD::SSHLSAT:
1220 case ISD::USHLSAT:
1221 case ISD::SCMP:
1222 case ISD::UCMP:
1225 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1226 break;
1227 case ISD::SMULFIX:
1228 case ISD::SMULFIXSAT:
1229 case ISD::UMULFIX:
1230 case ISD::UMULFIXSAT:
1231 case ISD::SDIVFIX:
1232 case ISD::SDIVFIXSAT:
1233 case ISD::UDIVFIX:
1234 case ISD::UDIVFIXSAT: {
1235 unsigned Scale = Node->getConstantOperandVal(2);
1236 Action = TLI.getFixedPointOperationAction(Node->getOpcode(),
1237 Node->getValueType(0), Scale);
1238 break;
1239 }
1240 case ISD::MSCATTER:
1241 Action = TLI.getOperationAction(Node->getOpcode(),
1242 cast<MaskedScatterSDNode>(Node)->getValue().getValueType());
1243 break;
1244 case ISD::MSTORE:
1245 Action = TLI.getOperationAction(Node->getOpcode(),
1246 cast<MaskedStoreSDNode>(Node)->getValue().getValueType());
1247 break;
1248 case ISD::VP_SCATTER:
1249 Action = TLI.getOperationAction(
1250 Node->getOpcode(),
1251 cast<VPScatterSDNode>(Node)->getValue().getValueType());
1252 break;
1253 case ISD::VP_STORE:
1254 Action = TLI.getOperationAction(
1255 Node->getOpcode(),
1256 cast<VPStoreSDNode>(Node)->getValue().getValueType());
1257 break;
1258 case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
1259 Action = TLI.getOperationAction(
1260 Node->getOpcode(),
1261 cast<VPStridedStoreSDNode>(Node)->getValue().getValueType());
1262 break;
1265 case ISD::VECREDUCE_ADD:
1266 case ISD::VECREDUCE_MUL:
1267 case ISD::VECREDUCE_AND:
1268 case ISD::VECREDUCE_OR:
1269 case ISD::VECREDUCE_XOR:
1280 case ISD::IS_FPCLASS:
1281 Action = TLI.getOperationAction(
1282 Node->getOpcode(), Node->getOperand(0).getValueType());
1283 break;
1286 case ISD::VP_REDUCE_FADD:
1287 case ISD::VP_REDUCE_FMUL:
1288 case ISD::VP_REDUCE_ADD:
1289 case ISD::VP_REDUCE_MUL:
1290 case ISD::VP_REDUCE_AND:
1291 case ISD::VP_REDUCE_OR:
1292 case ISD::VP_REDUCE_XOR:
1293 case ISD::VP_REDUCE_SMAX:
1294 case ISD::VP_REDUCE_SMIN:
1295 case ISD::VP_REDUCE_UMAX:
1296 case ISD::VP_REDUCE_UMIN:
1297 case ISD::VP_REDUCE_FMAX:
1298 case ISD::VP_REDUCE_FMIN:
1299 case ISD::VP_REDUCE_FMAXIMUM:
1300 case ISD::VP_REDUCE_FMINIMUM:
1301 case ISD::VP_REDUCE_SEQ_FADD:
1302 case ISD::VP_REDUCE_SEQ_FMUL:
1303 Action = TLI.getOperationAction(
1304 Node->getOpcode(), Node->getOperand(1).getValueType());
1305 break;
1306 case ISD::CTTZ_ELTS:
1308 case ISD::VP_CTTZ_ELTS:
1309 case ISD::VP_CTTZ_ELTS_ZERO_POISON:
1310 Action = TLI.getOperationAction(Node->getOpcode(),
1311 Node->getOperand(0).getValueType());
1312 break;
1316 Node->getOpcode(), Node->getNumOperands(), Node->getValueType(0));
1317 break;
1319 Action = TLI.getOperationAction(
1320 Node->getOpcode(),
1321 cast<MaskedHistogramSDNode>(Node)->getIndex().getValueType());
1322 break;
1323 default:
1324 if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
1325 Action = TLI.getCustomOperationAction(*Node);
1326 } else {
1327 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1328 }
1329 break;
1330 }
1331
1332 if (SimpleFinishLegalizing) {
1333 SDNode *NewNode = Node;
1334 switch (Node->getOpcode()) {
1335 default: break;
1336 case ISD::SHL:
1337 case ISD::SRL:
1338 case ISD::SRA:
1339 case ISD::ROTL:
1340 case ISD::ROTR:
1341 case ISD::SSHLSAT:
1342 case ISD::USHLSAT: {
1343 // Legalizing shifts/rotates requires adjusting the shift amount
1344 // to the appropriate width.
1345 SDValue Op0 = Node->getOperand(0);
1346 SDValue Op1 = Node->getOperand(1);
1347 if (!Op1.getValueType().isVector()) {
1348 SDValue SAO = DAG.getShiftAmountOperand(Op0.getValueType(), Op1);
1349 // The getShiftAmountOperand() may create a new operand node or
1350 // return the existing one. If new operand is created we need
1351 // to update the parent node.
1352 // Do not try to legalize SAO here! It will be automatically legalized
1353 // in the next round.
1354 if (SAO != Op1)
1355 NewNode = DAG.UpdateNodeOperands(Node, Op0, SAO);
1356 }
1357 break;
1358 }
1359 case ISD::FSHL:
1360 case ISD::FSHR:
1361 case ISD::SRL_PARTS:
1362 case ISD::SRA_PARTS:
1363 case ISD::SHL_PARTS: {
1364 // Legalizing shifts/rotates requires adjusting the shift amount
1365 // to the appropriate width.
1366 SDValue Op0 = Node->getOperand(0);
1367 SDValue Op1 = Node->getOperand(1);
1368 SDValue Op2 = Node->getOperand(2);
1369 if (!Op2.getValueType().isVector()) {
1370 SDValue SAO = DAG.getShiftAmountOperand(Op0.getValueType(), Op2);
1371 // The getShiftAmountOperand() may create a new operand node or
1372 // return the existing one. If new operand is created we need
1373 // to update the parent node.
1374 if (SAO != Op2)
1375 NewNode = DAG.UpdateNodeOperands(Node, Op0, Op1, SAO);
1376 }
1377 break;
1378 }
1379 }
1380
1381 if (NewNode != Node) {
1382 ReplaceNode(Node, NewNode);
1383 Node = NewNode;
1384 }
1385 switch (Action) {
1386 case TargetLowering::Legal:
1387 LLVM_DEBUG(dbgs() << "Legal node: nothing to do\n");
1388 return;
1389 case TargetLowering::Custom:
1390 LLVM_DEBUG(dbgs() << "Trying custom legalization\n");
1391 // FIXME: The handling for custom lowering with multiple results is
1392 // a complete mess.
1393 if (SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG)) {
1394 if (!(Res.getNode() != Node || Res.getResNo() != 0))
1395 return;
1396
1397 if (Node->getNumValues() == 1) {
1398 // Verify the new types match the original. Glue is waived because
1399 // ISD::ADDC can be legalized by replacing Glue with an integer type.
1400 assert((Res.getValueType() == Node->getValueType(0) ||
1401 Node->getValueType(0) == MVT::Glue) &&
1402 "Type mismatch for custom legalized operation");
1403 LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n");
1404 // We can just directly replace this node with the lowered value.
1405 ReplaceNode(SDValue(Node, 0), Res);
1406 return;
1407 }
1408
1409 SmallVector<SDValue, 8> ResultVals;
1410 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
1411 // Verify the new types match the original. Glue is waived because
1412 // ISD::ADDC can be legalized by replacing Glue with an integer type.
1413 assert((Res->getValueType(i) == Node->getValueType(i) ||
1414 Node->getValueType(i) == MVT::Glue) &&
1415 "Type mismatch for custom legalized operation");
1416 ResultVals.push_back(Res.getValue(i));
1417 }
1418 LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n");
1419 ReplaceNode(Node, ResultVals.data());
1420 return;
1421 }
1422 LLVM_DEBUG(dbgs() << "Could not custom legalize node\n");
1423 [[fallthrough]];
1424 case TargetLowering::Expand:
1425 if (ExpandNode(Node))
1426 return;
1427 assert((Action != TargetLowering::Expand ||
1428 !hasAtomicLibcallLowering(Node->getOpcode())) &&
1429 "atomic operations lowered to calls must use LibCall");
1430 [[fallthrough]];
1431 case TargetLowering::LibCall:
1432 ConvertNodeToLibcall(Node);
1433 return;
1434 case TargetLowering::Promote:
1435 PromoteNode(Node);
1436 return;
1437 }
1438 }
1439
1440 switch (Node->getOpcode()) {
1441 default:
1442#ifndef NDEBUG
1443 dbgs() << "NODE: ";
1444 Node->dump( &DAG);
1445 dbgs() << "\n";
1446#endif
1447 llvm_unreachable("Do not know how to legalize this operator!");
1448
1449 case ISD::CALLSEQ_START:
1450 case ISD::CALLSEQ_END:
1451 break;
1452 case ISD::LOAD:
1453 return LegalizeLoadOps(Node);
1454 case ISD::STORE:
1455 return LegalizeStoreOps(Node);
1456 }
1457}
1458
1459SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
1460 SDValue Vec = Op.getOperand(0);
1461 SDValue Idx = Op.getOperand(1);
1462 SDLoc dl(Op);
1463
1464 // Before we generate a new store to a temporary stack slot, see if there is
1465 // already one that we can use. There often is because when we scalarize
1466 // vector operations (using SelectionDAG::UnrollVectorOp for example) a whole
1467 // series of EXTRACT_VECTOR_ELT nodes are generated, one for each element in
1468 // the vector. If all are expanded here, we don't want one store per vector
1469 // element.
1470
1471 // Caches for hasPredecessorHelper
1472 SmallPtrSet<const SDNode *, 32> Visited;
1474 Visited.insert(Op.getNode());
1475 Worklist.push_back(Idx.getNode());
1476 SDValue StackPtr, Ch;
1477 for (SDNode *User : Vec.getNode()->users()) {
1478 if (StoreSDNode *ST = dyn_cast<StoreSDNode>(User)) {
1479 if (ST->isIndexed() || ST->isTruncatingStore() ||
1480 ST->getValue() != Vec)
1481 continue;
1482
1483 // Make sure that nothing else could have stored into the destination of
1484 // this store.
1485 if (!ST->getChain().reachesChainWithoutSideEffects(DAG.getEntryNode()))
1486 continue;
1487
1488 // If the index is dependent on the store we will introduce a cycle when
1489 // creating the load (the load uses the index, and by replacing the chain
1490 // we will make the index dependent on the load). Also, the store might be
1491 // dependent on the extractelement and introduce a cycle when creating
1492 // the load.
1493 if (SDNode::hasPredecessorHelper(ST, Visited, Worklist) ||
1494 ST->hasPredecessor(Op.getNode()))
1495 continue;
1496
1497 StackPtr = ST->getBasePtr();
1498 Ch = SDValue(ST, 0);
1499 break;
1500 }
1501 }
1502
1503 EVT VecVT = Vec.getValueType();
1504
1505 if (!Ch.getNode()) {
1506 // Store the value to a temporary stack slot, then LOAD the returned part.
1507 StackPtr = DAG.CreateStackTemporary(VecVT);
1508 MachineMemOperand *StoreMMO = getStackAlignedMMO(
1509 StackPtr, DAG.getMachineFunction(), VecVT.isScalableVector());
1510 Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, StoreMMO);
1511 }
1512
1513 SDValue NewLoad;
1514 Align ElementAlignment =
1515 std::min(cast<StoreSDNode>(Ch)->getAlign(),
1517 Op.getValueType().getTypeForEVT(*DAG.getContext())));
1518
1519 if (Op.getValueType().isVector()) {
1520 StackPtr = TLI.getVectorSubVecPointer(DAG, StackPtr, VecVT,
1521 Op.getValueType(), Idx);
1522 NewLoad = DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr,
1523 MachinePointerInfo(), ElementAlignment);
1524 } else {
1525 StackPtr = TLI.getVectorElementPointer(DAG, StackPtr, VecVT, Idx);
1526 NewLoad = DAG.getExtLoad(ISD::EXTLOAD, dl, Op.getValueType(), Ch, StackPtr,
1527 MachinePointerInfo(), VecVT.getVectorElementType(),
1528 ElementAlignment);
1529 }
1530
1531 // Replace the chain going out of the store, by the one out of the load.
1532 DAG.ReplaceAllUsesOfValueWith(Ch, SDValue(NewLoad.getNode(), 1));
1533
1534 // We introduced a cycle though, so update the loads operands, making sure
1535 // to use the original store's chain as an incoming chain.
1536 SmallVector<SDValue, 6> NewLoadOperands(NewLoad->ops());
1537 NewLoadOperands[0] = Ch;
1538 NewLoad =
1539 SDValue(DAG.UpdateNodeOperands(NewLoad.getNode(), NewLoadOperands), 0);
1540 return NewLoad;
1541}
1542
1543SDValue SelectionDAGLegalize::ExpandInsertToVectorThroughStack(SDValue Op) {
1544 assert(Op.getValueType().isVector() && "Non-vector insert subvector!");
1545
1546 SDValue Vec = Op.getOperand(0);
1547 SDValue Part = Op.getOperand(1);
1548 SDValue Idx = Op.getOperand(2);
1549 SDLoc dl(Op);
1550
1551 // Store the value to a temporary stack slot, then LOAD the returned part.
1552 EVT VecVT = Vec.getValueType();
1553 EVT PartVT = Part.getValueType();
1554 bool IsInsertSubvector = Op.getOpcode() == ISD::INSERT_SUBVECTOR;
1556 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
1557 MachinePointerInfo PtrInfo =
1559
1560 // First store the whole vector.
1561 Align BaseVecAlignment =
1563 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, PtrInfo,
1564 BaseVecAlignment);
1565
1566 // Freeze the index so we don't poison the clamping code we're about to emit.
1567 Idx = DAG.getFreeze(Idx);
1568
1569 // INSERT_VECTOR_ELT implicitly truncates an over-width scalar, so use the
1570 // vector element type as the actual store type.
1571 EVT PartMemVT = IsInsertSubvector ? PartVT : VecVT.getVectorElementType();
1572 Type *PartTy = PartMemVT.getTypeForEVT(*DAG.getContext());
1573 Align PartAlignment = DAG.getDataLayout().getPrefTypeAlign(PartTy);
1574
1575 // Then store the inserted part.
1576 if (IsInsertSubvector) {
1577 SDValue SubStackPtr =
1578 TLI.getVectorSubVecPointer(DAG, StackPtr, VecVT, PartVT, Idx);
1579
1580 // Store the subvector.
1581 Ch = DAG.getStore(
1582 Ch, dl, Part, SubStackPtr,
1584 PartAlignment);
1585 } else {
1586 SDValue SubStackPtr =
1587 TLI.getVectorElementPointer(DAG, StackPtr, VecVT, Idx);
1588
1589 // Store the scalar value.
1590 Ch = DAG.getTruncStore(
1591 Ch, dl, Part, SubStackPtr,
1593 VecVT.getVectorElementType(), PartAlignment);
1594 }
1595
1596 assert(cast<StoreSDNode>(Ch)->getAlign() == PartAlignment &&
1597 "ElementAlignment does not match!");
1598
1599 // Finally, load the updated vector.
1600 return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, PtrInfo,
1601 BaseVecAlignment);
1602}
1603
1604SDValue SelectionDAGLegalize::ExpandConcatVectors(SDNode *Node) {
1605 assert(Node->getOpcode() == ISD::CONCAT_VECTORS && "Unexpected opcode!");
1606 SDLoc DL(Node);
1608 unsigned NumOperands = Node->getNumOperands();
1609 MVT VectorIdxType = TLI.getVectorIdxTy(DAG.getDataLayout());
1610 EVT VectorValueType = Node->getOperand(0).getValueType();
1611 unsigned NumSubElem = VectorValueType.getVectorNumElements();
1612 EVT ElementValueType = TLI.getTypeToTransformTo(
1613 *DAG.getContext(), VectorValueType.getVectorElementType());
1614 for (unsigned I = 0; I < NumOperands; ++I) {
1615 SDValue SubOp = Node->getOperand(I);
1616 for (unsigned Idx = 0; Idx < NumSubElem; ++Idx) {
1617 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ElementValueType,
1618 SubOp,
1619 DAG.getConstant(Idx, DL, VectorIdxType)));
1620 }
1621 }
1622 return DAG.getBuildVector(Node->getValueType(0), DL, Ops);
1623}
1624
1625SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) {
1626 assert((Node->getOpcode() == ISD::BUILD_VECTOR ||
1627 Node->getOpcode() == ISD::CONCAT_VECTORS) &&
1628 "Unexpected opcode!");
1629
1630 // We can't handle this case efficiently. Allocate a sufficiently
1631 // aligned object on the stack, store each operand into it, then load
1632 // the result as a vector.
1633 // Create the stack frame object.
1634 EVT VT = Node->getValueType(0);
1635 EVT MemVT = isa<BuildVectorSDNode>(Node) ? VT.getVectorElementType()
1636 : Node->getOperand(0).getValueType();
1637 SDLoc dl(Node);
1638 SDValue FIPtr = DAG.CreateStackTemporary(VT);
1639 int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
1640 MachinePointerInfo PtrInfo =
1642
1643 // Emit a store of each element to the stack slot.
1645 unsigned TypeByteSize = MemVT.getSizeInBits() / 8;
1646 assert(TypeByteSize > 0 && "Vector element type too small for stack store!");
1647
1648 // If the destination vector element type of a BUILD_VECTOR is narrower than
1649 // the source element type, only store the bits necessary.
1650 bool Truncate = isa<BuildVectorSDNode>(Node) &&
1651 MemVT.bitsLT(Node->getOperand(0).getValueType());
1652
1653 // Store (in the right endianness) the elements to memory.
1654 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1655 // Ignore undef elements.
1656 if (Node->getOperand(i).isUndef()) continue;
1657
1658 unsigned Offset = TypeByteSize*i;
1659
1660 SDValue Idx =
1662
1663 if (Truncate)
1664 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
1665 Node->getOperand(i), Idx,
1666 PtrInfo.getWithOffset(Offset), MemVT));
1667 else
1668 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, Node->getOperand(i),
1669 Idx, PtrInfo.getWithOffset(Offset)));
1670 }
1671
1672 SDValue StoreChain;
1673 if (!Stores.empty()) // Not all undef elements?
1674 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
1675 else
1676 StoreChain = DAG.getEntryNode();
1677
1678 // Result is a load from the stack slot.
1679 return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo);
1680}
1681
1682/// Bitcast a floating-point value to an integer value. Only bitcast the part
1683/// containing the sign bit if the target has no integer value capable of
1684/// holding all bits of the floating-point value.
1685void SelectionDAGLegalize::getSignAsIntValue(FloatSignAsInt &State,
1686 const SDLoc &DL,
1687 SDValue Value) const {
1688 EVT FloatVT = Value.getValueType();
1689 unsigned NumBits = FloatVT.getScalarSizeInBits();
1690 State.FloatVT = FloatVT;
1691 EVT IVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
1692 // Convert to an integer of the same size.
1693 if (TLI.isTypeLegal(IVT)) {
1694 State.IntValue = DAG.getNode(ISD::BITCAST, DL, IVT, Value);
1695 State.SignMask = APInt::getSignMask(NumBits);
1696 State.SignBit = NumBits - 1;
1697 return;
1698 }
1699
1700 auto &DataLayout = DAG.getDataLayout();
1701 // Store the float to memory, then load the sign part out as an integer.
1702 MVT LoadTy = TLI.getRegisterType(*DAG.getContext(), MVT::i8);
1703 // First create a temporary that is aligned for both the load and store.
1704 SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy);
1705 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
1706 // Then store the float to it.
1707 State.FloatPtr = StackPtr;
1709 State.FloatPointerInfo = MachinePointerInfo::getFixedStack(MF, FI);
1710 State.Chain = DAG.getStore(DAG.getEntryNode(), DL, Value, State.FloatPtr,
1711 State.FloatPointerInfo);
1712
1713 SDValue IntPtr;
1714 if (DataLayout.isBigEndian()) {
1715 assert(FloatVT.isByteSized() && "Unsupported floating point type!");
1716 // Load out a legal integer with the same sign bit as the float.
1717 IntPtr = StackPtr;
1718 State.IntPointerInfo = State.FloatPointerInfo;
1719 } else {
1720 // Advance the pointer so that the loaded byte will contain the sign bit.
1721 unsigned ByteOffset = (NumBits / 8) - 1;
1722 IntPtr =
1723 DAG.getMemBasePlusOffset(StackPtr, TypeSize::getFixed(ByteOffset), DL);
1724 State.IntPointerInfo = MachinePointerInfo::getFixedStack(MF, FI,
1725 ByteOffset);
1726 }
1727
1728 State.IntPtr = IntPtr;
1729 State.IntValue = DAG.getExtLoad(ISD::EXTLOAD, DL, LoadTy, State.Chain, IntPtr,
1730 State.IntPointerInfo, MVT::i8);
1731 State.SignMask = APInt::getOneBitSet(LoadTy.getScalarSizeInBits(), 7);
1732 State.SignBit = 7;
1733}
1734
1735/// Replace the integer value produced by getSignAsIntValue() with a new value
1736/// and cast the result back to a floating-point type.
1737SDValue SelectionDAGLegalize::modifySignAsInt(const FloatSignAsInt &State,
1738 const SDLoc &DL,
1739 SDValue NewIntValue) const {
1740 if (!State.Chain)
1741 return DAG.getNode(ISD::BITCAST, DL, State.FloatVT, NewIntValue);
1742
1743 // Override the part containing the sign bit in the value stored on the stack.
1744 SDValue Chain = DAG.getTruncStore(State.Chain, DL, NewIntValue, State.IntPtr,
1745 State.IntPointerInfo, MVT::i8);
1746 return DAG.getLoad(State.FloatVT, DL, Chain, State.FloatPtr,
1747 State.FloatPointerInfo);
1748}
1749
1750SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode *Node) const {
1751 SDLoc DL(Node);
1752 SDValue Mag = Node->getOperand(0);
1753 SDValue Sign = Node->getOperand(1);
1754
1755 if (Sign.getValueType().isVector())
1756 return DAG.UnrollVectorOp(Node);
1757
1758 // Get sign bit into an integer value.
1759 FloatSignAsInt SignAsInt;
1760 getSignAsIntValue(SignAsInt, DL, Sign);
1761
1762 EVT IntVT = SignAsInt.IntValue.getValueType();
1763 SDValue SignMask = DAG.getConstant(SignAsInt.SignMask, DL, IntVT);
1764 SDValue SignBit = DAG.getNode(ISD::AND, DL, IntVT, SignAsInt.IntValue,
1765 SignMask);
1766
1767 // If FABS is legal transform
1768 // FCOPYSIGN(x, y) => SignBit(y) ? -FABS(x) : FABS(x)
1769 EVT FloatVT = Mag.getValueType();
1770 if (TLI.isOperationLegalOrCustom(ISD::FABS, FloatVT) &&
1772 SDValue AbsValue = DAG.getNode(ISD::FABS, DL, FloatVT, Mag);
1773 SDValue NegValue = DAG.getNode(ISD::FNEG, DL, FloatVT, AbsValue);
1774 SDValue Cond = DAG.getSetCC(DL, getSetCCResultType(IntVT), SignBit,
1775 DAG.getConstant(0, DL, IntVT), ISD::SETNE);
1776 return DAG.getSelect(DL, FloatVT, Cond, NegValue, AbsValue);
1777 }
1778
1779 // Transform Mag value to integer, and clear the sign bit.
1780 FloatSignAsInt MagAsInt;
1781 getSignAsIntValue(MagAsInt, DL, Mag);
1782 EVT MagVT = MagAsInt.IntValue.getValueType();
1783 SDValue ClearSignMask = DAG.getConstant(~MagAsInt.SignMask, DL, MagVT);
1784 SDValue ClearedSign = DAG.getNode(ISD::AND, DL, MagVT, MagAsInt.IntValue,
1785 ClearSignMask);
1786
1787 // Get the signbit at the right position for MagAsInt.
1788 int ShiftAmount = SignAsInt.SignBit - MagAsInt.SignBit;
1789 EVT ShiftVT = IntVT;
1790 if (SignBit.getScalarValueSizeInBits() <
1791 ClearedSign.getScalarValueSizeInBits()) {
1792 SignBit = DAG.getNode(ISD::ZERO_EXTEND, DL, MagVT, SignBit);
1793 ShiftVT = MagVT;
1794 }
1795 if (ShiftAmount > 0) {
1796 SDValue ShiftCnst = DAG.getConstant(ShiftAmount, DL, ShiftVT);
1797 SignBit = DAG.getNode(ISD::SRL, DL, ShiftVT, SignBit, ShiftCnst);
1798 } else if (ShiftAmount < 0) {
1799 SDValue ShiftCnst = DAG.getConstant(-ShiftAmount, DL, ShiftVT);
1800 SignBit = DAG.getNode(ISD::SHL, DL, ShiftVT, SignBit, ShiftCnst);
1801 }
1802 if (SignBit.getScalarValueSizeInBits() >
1803 ClearedSign.getScalarValueSizeInBits()) {
1804 SignBit = DAG.getNode(ISD::TRUNCATE, DL, MagVT, SignBit);
1805 }
1806
1807 // Store the part with the modified sign and convert back to float.
1808 SDValue CopiedSign = DAG.getNode(ISD::OR, DL, MagVT, ClearedSign, SignBit,
1810
1811 return modifySignAsInt(MagAsInt, DL, CopiedSign);
1812}
1813
1814SDValue SelectionDAGLegalize::ExpandFNEG(SDNode *Node) const {
1815 // Get the sign bit as an integer.
1816 SDLoc DL(Node);
1817 if (Node->getValueType(0).isVector())
1818 return DAG.UnrollVectorOp(Node);
1819
1820 FloatSignAsInt SignAsInt;
1821 getSignAsIntValue(SignAsInt, DL, Node->getOperand(0));
1822 EVT IntVT = SignAsInt.IntValue.getValueType();
1823
1824 // Flip the sign.
1825 SDValue SignMask = DAG.getConstant(SignAsInt.SignMask, DL, IntVT);
1826 SDValue SignFlip =
1827 DAG.getNode(ISD::XOR, DL, IntVT, SignAsInt.IntValue, SignMask);
1828
1829 // Convert back to float.
1830 return modifySignAsInt(SignAsInt, DL, SignFlip);
1831}
1832
1833SDValue SelectionDAGLegalize::ExpandFABS(SDNode *Node) const {
1834 SDLoc DL(Node);
1835 SDValue Value = Node->getOperand(0);
1836
1837 // Transform FABS(x) => FCOPYSIGN(x, 0.0) if FCOPYSIGN is legal.
1838 EVT FloatVT = Value.getValueType();
1840 SDValue Zero = DAG.getConstantFP(0.0, DL, FloatVT);
1841 return DAG.getNode(ISD::FCOPYSIGN, DL, FloatVT, Value, Zero);
1842 }
1843
1844 if (FloatVT.isVector())
1845 return DAG.UnrollVectorOp(Node);
1846
1847 // Transform value to integer, clear the sign bit and transform back.
1848 FloatSignAsInt ValueAsInt;
1849 getSignAsIntValue(ValueAsInt, DL, Value);
1850 EVT IntVT = ValueAsInt.IntValue.getValueType();
1851 SDValue ClearSignMask = DAG.getConstant(~ValueAsInt.SignMask, DL, IntVT);
1852 SDValue ClearedSign = DAG.getNode(ISD::AND, DL, IntVT, ValueAsInt.IntValue,
1853 ClearSignMask);
1854 return modifySignAsInt(ValueAsInt, DL, ClearedSign);
1855}
1856
1857void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node,
1858 SmallVectorImpl<SDValue> &Results) {
1860 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1861 " not tell us which reg is the stack pointer!");
1862 SDLoc dl(Node);
1863 EVT VT = Node->getValueType(0);
1864 SDValue Tmp1 = SDValue(Node, 0);
1865 SDValue Tmp2 = SDValue(Node, 1);
1866 SDValue Tmp3 = Node->getOperand(2);
1867 SDValue Chain = Tmp1.getOperand(0);
1868
1869 // Chain the dynamic stack allocation so that it doesn't modify the stack
1870 // pointer when other instructions are using the stack.
1871 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
1872
1873 SDValue Size = Tmp2.getOperand(1);
1874 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
1875 Chain = SP.getValue(1);
1876 Align Alignment = cast<ConstantSDNode>(Tmp3)->getAlignValue();
1877 const TargetFrameLowering *TFL = DAG.getSubtarget().getFrameLowering();
1878 unsigned Opc =
1881
1882 Align StackAlign = TFL->getStackAlign();
1883 Tmp1 = DAG.getNode(Opc, dl, VT, SP, Size); // Value
1884 if (Alignment > StackAlign)
1885 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
1886 DAG.getSignedConstant(-Alignment.value(), dl, VT));
1887 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
1888
1889 Tmp2 = DAG.getCALLSEQ_END(Chain, 0, 0, SDValue(), dl);
1890
1891 Results.push_back(Tmp1);
1892 Results.push_back(Tmp2);
1893}
1894
1895SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp, EVT SlotVT,
1896 EVT DestVT, const SDLoc &dl) {
1897 return EmitStackConvert(SrcOp, SlotVT, DestVT, dl, DAG.getEntryNode());
1898}
1899
1900SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp, EVT SlotVT,
1901 EVT DestVT, const SDLoc &dl,
1902 SDValue Chain) {
1903 EVT SrcVT = SrcOp.getValueType();
1904 Type *DestType = DestVT.getTypeForEVT(*DAG.getContext());
1905 Align DestAlign = DAG.getDataLayout().getPrefTypeAlign(DestType);
1906 // Don't convert with stack if the load/store is expensive.
1907 if ((SrcVT.bitsGT(SlotVT) && !TLI.isTruncStoreLegalOrCustom(
1908 SrcVT, SlotVT, DestAlign,
1910 (SlotVT.bitsLT(DestVT) &&
1911 !TLI.isLoadLegalOrCustom(DestVT, SlotVT, DestAlign,
1913 ISD::EXTLOAD, false)))
1914 return SDValue();
1915
1916 return DAG.emitStackConvert(SrcOp, SlotVT, DestVT, dl, Chain);
1917}
1918
1919SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
1920 SDLoc dl(Node);
1921 // Create a vector sized/aligned stack slot, store the value to element #0,
1922 // then load the whole vector back out.
1923 SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
1924
1925 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
1926 int SPFI = StackPtrFI->getIndex();
1927
1928 SDValue Ch = DAG.getTruncStore(
1929 DAG.getEntryNode(), dl, Node->getOperand(0), StackPtr,
1931 Node->getValueType(0).getVectorElementType());
1932 return DAG.getLoad(
1933 Node->getValueType(0), dl, Ch, StackPtr,
1935}
1936
1937static bool
1939 const TargetLowering &TLI, SDValue &Res) {
1940 unsigned NumElems = Node->getNumOperands();
1941 SDLoc dl(Node);
1942 EVT VT = Node->getValueType(0);
1943
1944 // Try to group the scalars into pairs, shuffle the pairs together, then
1945 // shuffle the pairs of pairs together, etc. until the vector has
1946 // been built. This will work only if all of the necessary shuffle masks
1947 // are legal.
1948
1949 // We do this in two phases; first to check the legality of the shuffles,
1950 // and next, assuming that all shuffles are legal, to create the new nodes.
1951 for (int Phase = 0; Phase < 2; ++Phase) {
1953 NewIntermedVals;
1954 for (unsigned i = 0; i < NumElems; ++i) {
1955 SDValue V = Node->getOperand(i);
1956 if (V.isUndef())
1957 continue;
1958
1959 SDValue Vec;
1960 if (Phase)
1961 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, V);
1962 IntermedVals.push_back(std::make_pair(Vec, SmallVector<int, 16>(1, i)));
1963 }
1964
1965 while (IntermedVals.size() > 2) {
1966 NewIntermedVals.clear();
1967 for (unsigned i = 0, e = (IntermedVals.size() & ~1u); i < e; i += 2) {
1968 // This vector and the next vector are shuffled together (simply to
1969 // append the one to the other).
1970 SmallVector<int, 16> ShuffleVec(NumElems, -1);
1971
1972 SmallVector<int, 16> FinalIndices;
1973 FinalIndices.reserve(IntermedVals[i].second.size() +
1974 IntermedVals[i+1].second.size());
1975
1976 int k = 0;
1977 for (unsigned j = 0, f = IntermedVals[i].second.size(); j != f;
1978 ++j, ++k) {
1979 ShuffleVec[k] = j;
1980 FinalIndices.push_back(IntermedVals[i].second[j]);
1981 }
1982 for (unsigned j = 0, f = IntermedVals[i+1].second.size(); j != f;
1983 ++j, ++k) {
1984 ShuffleVec[k] = NumElems + j;
1985 FinalIndices.push_back(IntermedVals[i+1].second[j]);
1986 }
1987
1988 SDValue Shuffle;
1989 if (Phase)
1990 Shuffle = DAG.getVectorShuffle(VT, dl, IntermedVals[i].first,
1991 IntermedVals[i+1].first,
1992 ShuffleVec);
1993 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
1994 return false;
1995 NewIntermedVals.push_back(
1996 std::make_pair(Shuffle, std::move(FinalIndices)));
1997 }
1998
1999 // If we had an odd number of defined values, then append the last
2000 // element to the array of new vectors.
2001 if ((IntermedVals.size() & 1) != 0)
2002 NewIntermedVals.push_back(IntermedVals.back());
2003
2004 IntermedVals.swap(NewIntermedVals);
2005 }
2006
2007 assert(IntermedVals.size() <= 2 && IntermedVals.size() > 0 &&
2008 "Invalid number of intermediate vectors");
2009 SDValue Vec1 = IntermedVals[0].first;
2010 SDValue Vec2;
2011 if (IntermedVals.size() > 1)
2012 Vec2 = IntermedVals[1].first;
2013 else if (Phase)
2014 Vec2 = DAG.getPOISON(VT);
2015
2016 SmallVector<int, 16> ShuffleVec(NumElems, -1);
2017 for (unsigned i = 0, e = IntermedVals[0].second.size(); i != e; ++i)
2018 ShuffleVec[IntermedVals[0].second[i]] = i;
2019 for (unsigned i = 0, e = IntermedVals[1].second.size(); i != e; ++i)
2020 ShuffleVec[IntermedVals[1].second[i]] = NumElems + i;
2021
2022 if (Phase)
2023 Res = DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec);
2024 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
2025 return false;
2026 }
2027
2028 return true;
2029}
2030
2031/// Expand a BUILD_VECTOR node on targets that don't
2032/// support the operation, but do support the resultant vector type.
2033SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
2034 unsigned NumElems = Node->getNumOperands();
2035 SDValue Value1, Value2;
2036 SDLoc dl(Node);
2037 EVT VT = Node->getValueType(0);
2038 EVT OpVT = Node->getOperand(0).getValueType();
2039 EVT EltVT = VT.getVectorElementType();
2040
2041 // If the only non-undef value is the low element, turn this into a
2042 // SCALAR_TO_VECTOR node. If this is { X, X, X, X }, determine X.
2043 bool isOnlyLowElement = true;
2044 bool MoreThanTwoValues = false;
2045 bool isConstant = true;
2046 for (unsigned i = 0; i < NumElems; ++i) {
2047 SDValue V = Node->getOperand(i);
2048 if (V.isUndef())
2049 continue;
2050 if (i > 0)
2051 isOnlyLowElement = false;
2053 isConstant = false;
2054
2055 if (!Value1.getNode()) {
2056 Value1 = V;
2057 } else if (!Value2.getNode()) {
2058 if (V != Value1)
2059 Value2 = V;
2060 } else if (V != Value1 && V != Value2) {
2061 MoreThanTwoValues = true;
2062 }
2063 }
2064
2065 if (!Value1.getNode())
2066 return DAG.getUNDEF(VT);
2067
2068 if (isOnlyLowElement)
2069 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
2070
2071 // If all elements are constants, create a load from the constant pool.
2072 if (isConstant) {
2074 for (unsigned i = 0, e = NumElems; i != e; ++i) {
2075 if (ConstantFPSDNode *V =
2076 dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
2077 CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
2078 } else if (ConstantSDNode *V =
2079 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
2080 if (OpVT==EltVT)
2081 CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
2082 else {
2083 // If OpVT and EltVT don't match, EltVT is not legal and the
2084 // element values have been promoted/truncated earlier. Undo this;
2085 // we don't want a v16i8 to become a v16i32 for example.
2086 const ConstantInt *CI = V->getConstantIntValue();
2087 CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()),
2088 CI->getZExtValue(), /*IsSigned=*/false,
2089 /*ImplicitTrunc=*/true));
2090 }
2091 } else {
2092 assert(Node->getOperand(i).isUndef());
2093 Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext());
2094 CV.push_back(UndefValue::get(OpNTy));
2095 }
2096 }
2097 Constant *CP = ConstantVector::get(CV);
2098 SDValue CPIdx =
2100 Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign();
2101 return DAG.getLoad(
2102 VT, dl, DAG.getEntryNode(), CPIdx,
2104 Alignment);
2105 }
2106
2107 SmallSet<SDValue, 16> DefinedValues;
2108 for (unsigned i = 0; i < NumElems; ++i) {
2109 if (Node->getOperand(i).isUndef())
2110 continue;
2111 DefinedValues.insert(Node->getOperand(i));
2112 }
2113
2114 if (TLI.shouldExpandBuildVectorWithShuffles(VT, DefinedValues.size())) {
2115 if (!MoreThanTwoValues) {
2116 SmallVector<int, 8> ShuffleVec(NumElems, -1);
2117 for (unsigned i = 0; i < NumElems; ++i) {
2118 SDValue V = Node->getOperand(i);
2119 if (V.isUndef())
2120 continue;
2121 ShuffleVec[i] = V == Value1 ? 0 : NumElems;
2122 }
2123 if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) {
2124 // Get the splatted value into the low element of a vector register.
2125 SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1);
2126 SDValue Vec2;
2127 if (Value2.getNode())
2128 Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2);
2129 else
2130 Vec2 = DAG.getPOISON(VT);
2131
2132 // Return shuffle(LowValVec, undef, <0,0,0,0>)
2133 return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec);
2134 }
2135 } else {
2136 SDValue Res;
2137 if (ExpandBVWithShuffles(Node, DAG, TLI, Res))
2138 return Res;
2139 }
2140 }
2141
2142 // Otherwise, we can't handle this case efficiently.
2143 return ExpandVectorBuildThroughStack(Node);
2144}
2145
2146SDValue SelectionDAGLegalize::ExpandSPLAT_VECTOR(SDNode *Node) {
2147 SDLoc DL(Node);
2148 EVT VT = Node->getValueType(0);
2149 SDValue SplatVal = Node->getOperand(0);
2150
2151 return DAG.getSplatBuildVector(VT, DL, SplatVal);
2152}
2153
2154// Expand a node into a call to a libcall, returning the value as the first
2155// result and the chain as the second. If the result value does not fit into a
2156// register, return the lo part and set the hi part to the by-reg argument in
2157// the first. If it does fit into a single register, return the result and
2158// leave the Hi part unset.
2159std::pair<SDValue, SDValue>
2160SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
2161 TargetLowering::ArgListTy &&Args,
2162 bool IsSigned, EVT RetVT) {
2163 EVT CodePtrTy = TLI.getPointerTy(DAG.getDataLayout());
2165 RTLIB::LibcallImpl LCImpl = DAG.getLibcalls().getLibcallImpl(LC);
2166 if (LCImpl != RTLIB::Unsupported)
2167 Callee = DAG.getExternalSymbol(LCImpl, CodePtrTy);
2168 else {
2169 Callee = DAG.getPOISON(CodePtrTy);
2170 DAG.getContext()->emitError(Twine("no libcall available for ") +
2171 Node->getOperationName(&DAG));
2172 }
2173
2174 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2175
2176 // By default, the input chain to this libcall is the entry node of the
2177 // function. If the libcall is going to be emitted as a tail call then
2178 // TLI.isUsedByReturnOnly will change it to the right chain if the return
2179 // node which is being folded has a non-entry input chain.
2180 SDValue InChain = DAG.getEntryNode();
2181
2182 // isTailCall may be true since the callee does not reference caller stack
2183 // frame. Check if it's in the right position and that the return types match.
2184 SDValue TCChain = InChain;
2185 const Function &F = DAG.getMachineFunction().getFunction();
2186 bool isTailCall =
2187 TLI.isInTailCallPosition(DAG, Node, TCChain) &&
2188 (RetTy == F.getReturnType() || F.getReturnType()->isVoidTy()) &&
2189 // Lowering doesn't support tail calling inside a function with
2190 // a swifterror argument yet.
2191 !DAG.hasSwiftErrorArg();
2192 if (isTailCall)
2193 InChain = TCChain;
2194
2195 TargetLowering::CallLoweringInfo CLI(DAG);
2196 bool signExtend = TLI.shouldSignExtendTypeInLibCall(RetTy, IsSigned);
2197 CLI.setDebugLoc(SDLoc(Node))
2198 .setChain(InChain)
2199 .setLibCallee(DAG.getLibcalls().getLibcallImplCallingConv(LCImpl), RetTy,
2200 Callee, std::move(Args))
2201 .setTailCall(isTailCall)
2202 .setSExtResult(signExtend)
2203 .setZExtResult(!signExtend)
2204 .setIsPostTypeLegalization(true);
2205
2206 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2207
2208 if (!CallInfo.second.getNode()) {
2209 LLVM_DEBUG(dbgs() << "Created tailcall: "; DAG.getRoot().dump(&DAG));
2210 // It's a tailcall, return the chain (which is the DAG root).
2211 return {DAG.getRoot(), DAG.getRoot()};
2212 }
2213
2214 LLVM_DEBUG(dbgs() << "Created libcall: "; CallInfo.first.dump(&DAG));
2215 return CallInfo;
2216}
2217
2218std::pair<SDValue, SDValue> SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
2219 bool isSigned) {
2220 TargetLowering::ArgListTy Args;
2221 for (const SDValue &Op : Node->op_values()) {
2222 EVT ArgVT = Op.getValueType();
2223 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2224 TargetLowering::ArgListEntry Entry(Op, ArgTy);
2226 Entry.IsZExt = !Entry.IsSExt;
2227 Args.push_back(Entry);
2228 }
2229
2230 return ExpandLibCall(LC, Node, std::move(Args), isSigned,
2231 Node->getValueType(0));
2232}
2233
2234void SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
2235 RTLIB::Libcall LC,
2236 SmallVectorImpl<SDValue> &Results) {
2237 if (LC == RTLIB::UNKNOWN_LIBCALL)
2238 llvm_unreachable("Can't create an unknown libcall!");
2239
2240 if (Node->isStrictFPOpcode()) {
2241 EVT RetVT = Node->getValueType(0);
2242 RTLIB::LibcallImpl LCImpl = DAG.getLibcalls().getLibcallImpl(LC);
2243 if (LCImpl == RTLIB::Unsupported) {
2244 DAG.getContext()->emitError(Twine("no libcall available for ") +
2245 Node->getOperationName(&DAG));
2246 Results.push_back(DAG.getPOISON(RetVT));
2247 Results.push_back(Node->getOperand(0));
2248 return;
2249 }
2251 TargetLowering::MakeLibCallOptions CallOptions;
2252 CallOptions.IsPostTypeLegalization = true;
2253 // FIXME: This doesn't support tail calls.
2254 std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(
2255 DAG, LCImpl, RetVT, Ops, CallOptions, SDLoc(Node), Node->getOperand(0));
2256 Results.push_back(Tmp.first);
2257 Results.push_back(Tmp.second);
2258 } else {
2259 bool IsSignedArgument = Node->getOpcode() == ISD::FLDEXP;
2260 SDValue Tmp = ExpandLibCall(LC, Node, IsSignedArgument).first;
2261 Results.push_back(Tmp);
2262 }
2263}
2264
2265/// Expand the node to a libcall based on the result type.
2266void SelectionDAGLegalize::ExpandFastFPLibCall(
2267 SDNode *Node, bool IsFast,
2268 std::pair<RTLIB::Libcall, RTLIB::Libcall> Call_F32,
2269 std::pair<RTLIB::Libcall, RTLIB::Libcall> Call_F64,
2270 std::pair<RTLIB::Libcall, RTLIB::Libcall> Call_F80,
2271 std::pair<RTLIB::Libcall, RTLIB::Libcall> Call_F128,
2272 std::pair<RTLIB::Libcall, RTLIB::Libcall> Call_PPCF128,
2273 SmallVectorImpl<SDValue> &Results) {
2274
2275 EVT VT = Node->getSimpleValueType(0);
2276
2277 RTLIB::Libcall LC;
2278
2279 // FIXME: Probably should define fast to respect nan/inf and only be
2280 // approximate functions.
2281
2282 if (IsFast) {
2283 LC = RTLIB::getFPLibCall(VT, Call_F32.first, Call_F64.first, Call_F80.first,
2284 Call_F128.first, Call_PPCF128.first);
2285 }
2286
2287 if (!IsFast || DAG.getLibcalls().getLibcallImpl(LC) == RTLIB::Unsupported) {
2288 // Fall back if we don't have a fast implementation.
2289 LC = RTLIB::getFPLibCall(VT, Call_F32.second, Call_F64.second,
2290 Call_F80.second, Call_F128.second,
2291 Call_PPCF128.second);
2292 }
2293
2294 ExpandFPLibCall(Node, LC, Results);
2295}
2296
2297SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned,
2298 RTLIB::Libcall Call_I8,
2299 RTLIB::Libcall Call_I16,
2300 RTLIB::Libcall Call_I32,
2301 RTLIB::Libcall Call_I64,
2302 RTLIB::Libcall Call_I128) {
2303 RTLIB::Libcall LC;
2304 switch (Node->getSimpleValueType(0).SimpleTy) {
2305 default: llvm_unreachable("Unexpected request for libcall!");
2306 case MVT::i8: LC = Call_I8; break;
2307 case MVT::i16: LC = Call_I16; break;
2308 case MVT::i32: LC = Call_I32; break;
2309 case MVT::i64: LC = Call_I64; break;
2310 case MVT::i128: LC = Call_I128; break;
2311 }
2312 return ExpandLibCall(LC, Node, isSigned).first;
2313}
2314
2315/// Expand the node to a libcall based on first argument type (for instance
2316/// lround and its variant).
2317void SelectionDAGLegalize::ExpandArgFPLibCall(SDNode* Node,
2318 RTLIB::Libcall Call_F32,
2319 RTLIB::Libcall Call_F64,
2320 RTLIB::Libcall Call_F80,
2321 RTLIB::Libcall Call_F128,
2322 RTLIB::Libcall Call_PPCF128,
2323 SmallVectorImpl<SDValue> &Results) {
2324 EVT InVT = Node->getOperand(Node->isStrictFPOpcode() ? 1 : 0).getValueType();
2325 RTLIB::Libcall LC = RTLIB::getFPLibCall(InVT.getSimpleVT(),
2326 Call_F32, Call_F64, Call_F80,
2327 Call_F128, Call_PPCF128);
2328 ExpandFPLibCall(Node, LC, Results);
2329}
2330
2331SDValue SelectionDAGLegalize::ExpandBitCountingLibCall(
2332 SDNode *Node, RTLIB::Libcall CallI32, RTLIB::Libcall CallI64,
2333 RTLIB::Libcall CallI128) {
2334 RTLIB::Libcall LC;
2335 switch (Node->getSimpleValueType(0).SimpleTy) {
2336 default:
2337 llvm_unreachable("Unexpected request for libcall!");
2338 case MVT::i32:
2339 LC = CallI32;
2340 break;
2341 case MVT::i64:
2342 LC = CallI64;
2343 break;
2344 case MVT::i128:
2345 LC = CallI128;
2346 break;
2347 }
2348
2349 // Bit-counting libcalls have one unsigned argument and return `int`.
2350 // Note that `int` may be illegal on this target; ExpandLibCall will
2351 // take care of promoting it to a legal type.
2352 SDValue Op = Node->getOperand(0);
2353 EVT IntVT =
2355
2356 EVT ArgVT = Op.getValueType();
2357 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2358 TargetLowering::ArgListEntry Arg(Op, ArgTy);
2359 Arg.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgTy, /*IsSigned=*/false);
2360 Arg.IsZExt = !Arg.IsSExt;
2361
2362 SDValue Res = ExpandLibCall(LC, Node, TargetLowering::ArgListTy{Arg},
2363 /*IsSigned=*/true, IntVT)
2364 .first;
2365
2366 // If ExpandLibCall created a tail call, the result was already
2367 // of the correct type. Otherwise, we need to sign extend it.
2368 if (Res.getValueType() != MVT::Other)
2369 Res = DAG.getSExtOrTrunc(Res, SDLoc(Node), Node->getValueType(0));
2370 return Res;
2371}
2372
2373/// Issue libcalls to __{u}divmod to compute div / rem pairs.
2374void
2375SelectionDAGLegalize::ExpandDivRemLibCall(SDNode *Node,
2376 SmallVectorImpl<SDValue> &Results) {
2377 unsigned Opcode = Node->getOpcode();
2378 bool isSigned = Opcode == ISD::SDIVREM;
2379
2380 RTLIB::Libcall LC;
2381 switch (Node->getSimpleValueType(0).SimpleTy) {
2382 default: llvm_unreachable("Unexpected request for libcall!");
2383 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2384 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2385 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2386 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2387 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2388 }
2389
2390 // The input chain to this libcall is the entry node of the function.
2391 // Legalizing the call will automatically add the previous call to the
2392 // dependence.
2393 SDValue InChain = DAG.getEntryNode();
2394
2395 EVT RetVT = Node->getValueType(0);
2396 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2397
2398 TargetLowering::ArgListTy Args;
2399 for (const SDValue &Op : Node->op_values()) {
2400 EVT ArgVT = Op.getValueType();
2401 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2402 TargetLowering::ArgListEntry Entry(Op, ArgTy);
2403 Entry.IsSExt = isSigned;
2404 Entry.IsZExt = !isSigned;
2405 Args.push_back(Entry);
2406 }
2407
2408 // Also pass the return address of the remainder.
2409 SDValue FIPtr = DAG.CreateStackTemporary(RetVT);
2410 TargetLowering::ArgListEntry Entry(
2411 FIPtr, PointerType::getUnqual(RetTy->getContext()));
2412 Entry.IsSExt = isSigned;
2413 Entry.IsZExt = !isSigned;
2414 Args.push_back(Entry);
2415
2416 RTLIB::LibcallImpl LibcallImpl = DAG.getLibcalls().getLibcallImpl(LC);
2417 if (LibcallImpl == RTLIB::Unsupported) {
2418 DAG.getContext()->emitError(Twine("no libcall available for ") +
2419 Node->getOperationName(&DAG));
2420 SDValue Poison = DAG.getPOISON(RetVT);
2421 Results.push_back(Poison);
2422 Results.push_back(Poison);
2423 return;
2424 }
2425
2426 SDValue Callee =
2427 DAG.getExternalSymbol(LibcallImpl, TLI.getPointerTy(DAG.getDataLayout()));
2428
2429 SDLoc dl(Node);
2430 TargetLowering::CallLoweringInfo CLI(DAG);
2431 CLI.setDebugLoc(dl)
2432 .setChain(InChain)
2433 .setLibCallee(DAG.getLibcalls().getLibcallImplCallingConv(LibcallImpl),
2434 RetTy, Callee, std::move(Args))
2435 .setSExtResult(isSigned)
2436 .setZExtResult(!isSigned);
2437
2438 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2439
2440 // Remainder is loaded back from the stack frame.
2441 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
2442 MachinePointerInfo PtrInfo =
2444
2445 SDValue Rem = DAG.getLoad(RetVT, dl, CallInfo.second, FIPtr, PtrInfo);
2446 Results.push_back(CallInfo.first);
2447 Results.push_back(Rem);
2448}
2449
2450/// Return true if sincos or __sincos_stret libcall is available.
2452 const LibcallLoweringInfo &Libcalls) {
2453 MVT::SimpleValueType VT = Node->getSimpleValueType(0).SimpleTy;
2454 return Libcalls.getLibcallImpl(RTLIB::getSINCOS(VT)) != RTLIB::Unsupported ||
2455 Libcalls.getLibcallImpl(RTLIB::getSINCOS_STRET(VT)) !=
2456 RTLIB::Unsupported;
2457}
2458
2459/// Only issue sincos libcall if both sin and cos are needed.
2460static bool useSinCos(SDNode *Node) {
2461 unsigned OtherOpcode = Node->getOpcode() == ISD::FSIN
2462 ? ISD::FCOS : ISD::FSIN;
2463
2464 SDValue Op0 = Node->getOperand(0);
2465 for (const SDNode *User : Op0.getNode()->users()) {
2466 if (User == Node)
2467 continue;
2468 // The other user might have been turned into sincos already.
2469 if (User->getOpcode() == OtherOpcode || User->getOpcode() == ISD::FSINCOS)
2470 return true;
2471 }
2472 return false;
2473}
2474
2475SDValue SelectionDAGLegalize::ExpandSincosStretLibCall(SDNode *Node) const {
2476 // For iOS, we want to call an alternative entry point: __sincos_stret,
2477 // which returns the values in two S / D registers.
2478 SDLoc dl(Node);
2479 SDValue Arg = Node->getOperand(0);
2480 EVT ArgVT = Arg.getValueType();
2481 RTLIB::Libcall LC = RTLIB::getSINCOS_STRET(ArgVT);
2482 RTLIB::LibcallImpl SincosStret = DAG.getLibcalls().getLibcallImpl(LC);
2483 if (SincosStret == RTLIB::Unsupported)
2484 return SDValue();
2485
2486 /// There are 3 different ABI cases to handle:
2487 /// - Direct return of separate fields in registers
2488 /// - Single return as vector elements
2489 /// - sret struct
2490
2491 const RTLIB::RuntimeLibcallsInfo &CallsInfo =
2493
2494 const DataLayout &DL = DAG.getDataLayout();
2495
2496 auto [FuncTy, FuncAttrs] = CallsInfo.getFunctionTy(
2497 *DAG.getContext(), TM.getTargetTriple(), DL, SincosStret);
2498
2499 Type *SincosStretRetTy = FuncTy->getReturnType();
2500 CallingConv::ID CallConv = CallsInfo.getLibcallImplCallingConv(SincosStret);
2501
2502 SDValue Callee =
2503 DAG.getExternalSymbol(SincosStret, TLI.getProgramPointerTy(DL));
2504
2505 TargetLowering::ArgListTy Args;
2506 SDValue SRet;
2507
2508 int FrameIdx;
2509 if (FuncTy->getParamType(0)->isPointerTy()) {
2510 // Uses sret
2511 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2512
2513 AttributeSet PtrAttrs = FuncAttrs.getParamAttrs(0);
2514 Type *StructTy = PtrAttrs.getStructRetType();
2515 const uint64_t ByteSize = DL.getTypeAllocSize(StructTy);
2516 const Align StackAlign = DL.getPrefTypeAlign(StructTy);
2517
2518 FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
2519 SRet = DAG.getFrameIndex(FrameIdx, TLI.getFrameIndexTy(DL));
2520
2521 TargetLowering::ArgListEntry Entry(SRet, FuncTy->getParamType(0));
2522 Entry.IsSRet = true;
2523 Entry.IndirectType = StructTy;
2524 Entry.Alignment = StackAlign;
2525
2526 Args.push_back(Entry);
2527 Args.emplace_back(Arg, FuncTy->getParamType(1));
2528 } else {
2529 Args.emplace_back(Arg, FuncTy->getParamType(0));
2530 }
2531
2532 TargetLowering::CallLoweringInfo CLI(DAG);
2533 CLI.setDebugLoc(dl)
2534 .setChain(DAG.getEntryNode())
2535 .setLibCallee(CallConv, SincosStretRetTy, Callee, std::move(Args))
2536 .setIsPostTypeLegalization();
2537
2538 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
2539
2540 if (SRet) {
2541 MachinePointerInfo PtrInfo =
2543 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet, PtrInfo);
2544
2545 TypeSize StoreSize = ArgVT.getStoreSize();
2546
2547 // Address of cos field.
2548 SDValue Add = DAG.getObjectPtrOffset(dl, SRet, StoreSize);
2549 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
2550 PtrInfo.getWithOffset(StoreSize));
2551
2552 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
2553 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, LoadSin.getValue(0),
2554 LoadCos.getValue(0));
2555 }
2556
2557 if (!CallResult.first.getValueType().isVector())
2558 return CallResult.first;
2559
2560 SDValue SinVal =
2561 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT, CallResult.first,
2562 DAG.getVectorIdxConstant(0, dl));
2563 SDValue CosVal =
2564 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT, CallResult.first,
2565 DAG.getVectorIdxConstant(1, dl));
2566 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
2567 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
2568}
2569
2570SDValue SelectionDAGLegalize::expandLdexp(SDNode *Node) const {
2571 SDLoc dl(Node);
2572 EVT VT = Node->getValueType(0);
2573 SDValue X = Node->getOperand(0);
2574 SDValue N = Node->getOperand(1);
2575 EVT ExpVT = N.getValueType();
2576 EVT AsIntVT = VT.changeTypeToInteger();
2577 if (AsIntVT == EVT()) // TODO: How to handle f80?
2578 return SDValue();
2579
2580 // The expansion works through the integer-equivalent type; if that is not
2581 // legal, bail out and let the caller use a libcall (or diagnose a missing
2582 // one).
2583 if (!TLI.isTypeLegal(AsIntVT))
2584 return SDValue();
2585
2586 if (Node->getOpcode() == ISD::STRICT_FLDEXP) // TODO
2587 return SDValue();
2588
2589 SDNodeFlags NSW;
2590 NSW.setNoSignedWrap(true);
2591 SDNodeFlags NUW_NSW;
2592 NUW_NSW.setNoUnsignedWrap(true);
2593 NUW_NSW.setNoSignedWrap(true);
2594
2595 EVT SetCCVT =
2596 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ExpVT);
2597 const fltSemantics &FltSem = VT.getFltSemantics();
2598
2599 const APFloat::ExponentType MaxExpVal = APFloat::semanticsMaxExponent(FltSem);
2600 const APFloat::ExponentType MinExpVal = APFloat::semanticsMinExponent(FltSem);
2601 const int Precision = APFloat::semanticsPrecision(FltSem);
2602
2603 const SDValue MaxExp = DAG.getSignedConstant(MaxExpVal, dl, ExpVT);
2604 const SDValue MinExp = DAG.getSignedConstant(MinExpVal, dl, ExpVT);
2605
2606 const SDValue DoubleMaxExp = DAG.getSignedConstant(2 * MaxExpVal, dl, ExpVT);
2607
2608 const APFloat One(FltSem, "1.0");
2609 APFloat ScaleUpK = scalbn(One, MaxExpVal, APFloat::rmNearestTiesToEven);
2610
2611 // Offset by precision to avoid denormal range.
2612 APFloat ScaleDownK =
2613 scalbn(One, MinExpVal + Precision, APFloat::rmNearestTiesToEven);
2614
2615 // TODO: Should really introduce control flow and use a block for the >
2616 // MaxExp, < MinExp cases
2617
2618 // First, handle exponents Exp > MaxExp and scale down.
2619 SDValue NGtMaxExp = DAG.getSetCC(dl, SetCCVT, N, MaxExp, ISD::SETGT);
2620
2621 SDValue DecN0 = DAG.getNode(ISD::SUB, dl, ExpVT, N, MaxExp, NSW);
2622 SDValue ClampMaxVal = DAG.getConstant(3 * MaxExpVal, dl, ExpVT);
2623 SDValue ClampN_Big = DAG.getNode(ISD::SMIN, dl, ExpVT, N, ClampMaxVal);
2624 SDValue DecN1 =
2625 DAG.getNode(ISD::SUB, dl, ExpVT, ClampN_Big, DoubleMaxExp, NSW);
2626
2627 SDValue ScaleUpTwice =
2628 DAG.getSetCC(dl, SetCCVT, N, DoubleMaxExp, ISD::SETUGT);
2629
2630 const SDValue ScaleUpVal = DAG.getConstantFP(ScaleUpK, dl, VT);
2631 SDValue ScaleUp0 = DAG.getNode(ISD::FMUL, dl, VT, X, ScaleUpVal);
2632 SDValue ScaleUp1 = DAG.getNode(ISD::FMUL, dl, VT, ScaleUp0, ScaleUpVal);
2633
2634 SDValue SelectN_Big =
2635 DAG.getNode(ISD::SELECT, dl, ExpVT, ScaleUpTwice, DecN1, DecN0);
2636 SDValue SelectX_Big =
2637 DAG.getNode(ISD::SELECT, dl, VT, ScaleUpTwice, ScaleUp1, ScaleUp0);
2638
2639 // Now handle exponents Exp < MinExp
2640 SDValue NLtMinExp = DAG.getSetCC(dl, SetCCVT, N, MinExp, ISD::SETLT);
2641
2642 SDValue Increment0 = DAG.getConstant(-(MinExpVal + Precision), dl, ExpVT);
2643 SDValue Increment1 = DAG.getConstant(-2 * (MinExpVal + Precision), dl, ExpVT);
2644
2645 SDValue IncN0 = DAG.getNode(ISD::ADD, dl, ExpVT, N, Increment0, NUW_NSW);
2646
2647 SDValue ClampMinVal =
2648 DAG.getSignedConstant(3 * MinExpVal + 2 * Precision, dl, ExpVT);
2649 SDValue ClampN_Small = DAG.getNode(ISD::SMAX, dl, ExpVT, N, ClampMinVal);
2650 SDValue IncN1 =
2651 DAG.getNode(ISD::ADD, dl, ExpVT, ClampN_Small, Increment1, NSW);
2652
2653 const SDValue ScaleDownVal = DAG.getConstantFP(ScaleDownK, dl, VT);
2654 SDValue ScaleDown0 = DAG.getNode(ISD::FMUL, dl, VT, X, ScaleDownVal);
2655 SDValue ScaleDown1 = DAG.getNode(ISD::FMUL, dl, VT, ScaleDown0, ScaleDownVal);
2656
2657 SDValue ScaleDownTwice = DAG.getSetCC(
2658 dl, SetCCVT, N,
2659 DAG.getSignedConstant(2 * MinExpVal + Precision, dl, ExpVT), ISD::SETULT);
2660
2661 SDValue SelectN_Small =
2662 DAG.getNode(ISD::SELECT, dl, ExpVT, ScaleDownTwice, IncN1, IncN0);
2663 SDValue SelectX_Small =
2664 DAG.getNode(ISD::SELECT, dl, VT, ScaleDownTwice, ScaleDown1, ScaleDown0);
2665
2666 // Now combine the two out of range exponent handling cases with the base
2667 // case.
2668 SDValue NewX = DAG.getNode(
2669 ISD::SELECT, dl, VT, NGtMaxExp, SelectX_Big,
2670 DAG.getNode(ISD::SELECT, dl, VT, NLtMinExp, SelectX_Small, X));
2671
2672 SDValue NewN = DAG.getNode(
2673 ISD::SELECT, dl, ExpVT, NGtMaxExp, SelectN_Big,
2674 DAG.getNode(ISD::SELECT, dl, ExpVT, NLtMinExp, SelectN_Small, N));
2675
2676 SDValue BiasedN = DAG.getNode(ISD::ADD, dl, ExpVT, NewN, MaxExp, NSW);
2677
2678 SDValue ExponentShiftAmt =
2679 DAG.getShiftAmountConstant(Precision - 1, ExpVT, dl);
2680 SDValue CastExpToValTy = DAG.getZExtOrTrunc(BiasedN, dl, AsIntVT);
2681
2682 SDValue AsInt = DAG.getNode(ISD::SHL, dl, AsIntVT, CastExpToValTy,
2683 ExponentShiftAmt, NUW_NSW);
2684 SDValue AsFP = DAG.getNode(ISD::BITCAST, dl, VT, AsInt);
2685 return DAG.getNode(ISD::FMUL, dl, VT, NewX, AsFP);
2686}
2687
2688SDValue SelectionDAGLegalize::expandFrexp(SDNode *Node) const {
2689 SDLoc dl(Node);
2690 SDValue Val = Node->getOperand(0);
2691 EVT VT = Val.getValueType();
2692 EVT ExpVT = Node->getValueType(1);
2693 EVT AsIntVT = VT.changeTypeToInteger();
2694 if (AsIntVT == EVT()) // TODO: How to handle f80?
2695 return SDValue();
2696
2697 // The expansion works through the integer-equivalent type; if that is not
2698 // legal, bail out and let the caller use a libcall (or diagnose a missing
2699 // one).
2700 if (!TLI.isTypeLegal(AsIntVT))
2701 return SDValue();
2702
2703 const fltSemantics &FltSem = VT.getFltSemantics();
2704 const APFloat::ExponentType MinExpVal = APFloat::semanticsMinExponent(FltSem);
2705 const unsigned Precision = APFloat::semanticsPrecision(FltSem);
2706 const unsigned BitSize = VT.getScalarSizeInBits();
2707
2708 // TODO: Could introduce control flow and skip over the denormal handling.
2709
2710 // scale_up = fmul value, scalbn(1.0, precision + 1)
2711 // extracted_exp = (bitcast value to uint) >> precision - 1
2712 // biased_exp = extracted_exp + min_exp
2713 // extracted_fract = (bitcast value to uint) & (fract_mask | sign_mask)
2714 //
2715 // is_denormal = val < smallest_normalized
2716 // computed_fract = is_denormal ? scale_up : extracted_fract
2717 // computed_exp = is_denormal ? biased_exp + (-precision - 1) : biased_exp
2718 //
2719 // result_0 = (!isfinite(val) || iszero(val)) ? val : computed_fract
2720 // result_1 = (!isfinite(val) || iszero(val)) ? 0 : computed_exp
2721
2722 SDValue NegSmallestNormalizedInt = DAG.getConstant(
2723 APFloat::getSmallestNormalized(FltSem, true).bitcastToAPInt(), dl,
2724 AsIntVT);
2725
2726 SDValue SmallestNormalizedInt = DAG.getConstant(
2727 APFloat::getSmallestNormalized(FltSem, false).bitcastToAPInt(), dl,
2728 AsIntVT);
2729
2730 // Masks out the exponent bits.
2731 SDValue ExpMask =
2732 DAG.getConstant(APFloat::getInf(FltSem).bitcastToAPInt(), dl, AsIntVT);
2733
2734 // Mask out the exponent part of the value.
2735 //
2736 // e.g, for f32 FractSignMaskVal = 0x807fffff
2737 APInt FractSignMaskVal = APInt::getBitsSet(BitSize, 0, Precision - 1);
2738 FractSignMaskVal.setBit(BitSize - 1); // Set the sign bit
2739
2740 APInt SignMaskVal = APInt::getSignedMaxValue(BitSize);
2741 SDValue SignMask = DAG.getConstant(SignMaskVal, dl, AsIntVT);
2742
2743 SDValue FractSignMask = DAG.getConstant(FractSignMaskVal, dl, AsIntVT);
2744
2745 const APFloat One(FltSem, "1.0");
2746 // Scale a possible denormal input.
2747 // e.g., for f64, 0x1p+54
2748 APFloat ScaleUpKVal =
2749 scalbn(One, Precision + 1, APFloat::rmNearestTiesToEven);
2750
2751 SDValue ScaleUpK = DAG.getConstantFP(ScaleUpKVal, dl, VT);
2752 SDValue ScaleUp = DAG.getNode(ISD::FMUL, dl, VT, Val, ScaleUpK);
2753
2754 EVT SetCCVT =
2756
2757 SDValue AsInt = DAG.getNode(ISD::BITCAST, dl, AsIntVT, Val);
2758
2759 SDValue Abs = DAG.getNode(ISD::AND, dl, AsIntVT, AsInt, SignMask);
2760
2761 SDValue AddNegSmallestNormal =
2762 DAG.getNode(ISD::ADD, dl, AsIntVT, Abs, NegSmallestNormalizedInt);
2763 SDValue DenormOrZero = DAG.getSetCC(dl, SetCCVT, AddNegSmallestNormal,
2764 NegSmallestNormalizedInt, ISD::SETULE);
2765
2766 SDValue IsDenormal =
2767 DAG.getSetCC(dl, SetCCVT, Abs, SmallestNormalizedInt, ISD::SETULT);
2768
2769 SDValue MinExp = DAG.getSignedConstant(MinExpVal, dl, ExpVT);
2770 SDValue Zero = DAG.getConstant(0, dl, ExpVT);
2771
2772 SDValue ScaledAsInt = DAG.getNode(ISD::BITCAST, dl, AsIntVT, ScaleUp);
2773 SDValue ScaledSelect =
2774 DAG.getNode(ISD::SELECT, dl, AsIntVT, IsDenormal, ScaledAsInt, AsInt);
2775
2776 SDValue ExpMaskScaled =
2777 DAG.getNode(ISD::AND, dl, AsIntVT, ScaledAsInt, ExpMask);
2778
2779 SDValue ScaledValue =
2780 DAG.getNode(ISD::SELECT, dl, AsIntVT, IsDenormal, ExpMaskScaled, Abs);
2781
2782 // Extract the exponent bits.
2783 SDValue ExponentShiftAmt =
2784 DAG.getShiftAmountConstant(Precision - 1, AsIntVT, dl);
2785 SDValue ShiftedExp =
2786 DAG.getNode(ISD::SRL, dl, AsIntVT, ScaledValue, ExponentShiftAmt);
2787 SDValue Exp = DAG.getSExtOrTrunc(ShiftedExp, dl, ExpVT);
2788
2789 SDValue NormalBiasedExp = DAG.getNode(ISD::ADD, dl, ExpVT, Exp, MinExp);
2790 SDValue DenormalOffset = DAG.getConstant(-Precision - 1, dl, ExpVT);
2791 SDValue DenormalExpBias =
2792 DAG.getNode(ISD::SELECT, dl, ExpVT, IsDenormal, DenormalOffset, Zero);
2793
2794 SDValue MaskedFractAsInt =
2795 DAG.getNode(ISD::AND, dl, AsIntVT, ScaledSelect, FractSignMask);
2796 const APFloat Half(FltSem, "0.5");
2797 SDValue FPHalf = DAG.getConstant(Half.bitcastToAPInt(), dl, AsIntVT);
2798 SDValue Or = DAG.getNode(ISD::OR, dl, AsIntVT, MaskedFractAsInt, FPHalf);
2799 SDValue MaskedFract = DAG.getNode(ISD::BITCAST, dl, VT, Or);
2800
2801 SDValue ComputedExp =
2802 DAG.getNode(ISD::ADD, dl, ExpVT, NormalBiasedExp, DenormalExpBias);
2803
2804 SDValue Result0 =
2805 DAG.getNode(ISD::SELECT, dl, VT, DenormOrZero, Val, MaskedFract);
2806
2807 SDValue Result1 =
2808 DAG.getNode(ISD::SELECT, dl, ExpVT, DenormOrZero, Zero, ComputedExp);
2809
2810 return DAG.getMergeValues({Result0, Result1}, dl);
2811}
2812
2813/// This function is responsible for legalizing a
2814/// INT_TO_FP operation of the specified operand when the target requests that
2815/// we expand it. At this point, we know that the result and operand types are
2816/// legal for the target.
2817SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(SDNode *Node,
2818 SDValue &Chain) {
2819 bool isSigned = (Node->getOpcode() == ISD::STRICT_SINT_TO_FP ||
2820 Node->getOpcode() == ISD::SINT_TO_FP);
2821 EVT DestVT = Node->getValueType(0);
2822 SDLoc dl(Node);
2823 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
2824 SDValue Op0 = Node->getOperand(OpNo);
2825 EVT SrcVT = Op0.getValueType();
2826
2827 // TODO: Should any fast-math-flags be set for the created nodes?
2828 LLVM_DEBUG(dbgs() << "Legalizing INT_TO_FP\n");
2829 if (SrcVT == MVT::i32 && TLI.isTypeLegal(MVT::f64) &&
2830 (DestVT.bitsLE(MVT::f64) ||
2831 TLI.isOperationLegal(Node->isStrictFPOpcode() ? ISD::STRICT_FP_EXTEND
2833 DestVT))) {
2834 LLVM_DEBUG(dbgs() << "32-bit [signed|unsigned] integer to float/double "
2835 "expansion\n");
2836
2837 // Get the stack frame index of a 8 byte buffer.
2838 SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
2839
2840 SDValue Lo = Op0;
2841 // if signed map to unsigned space
2842 if (isSigned) {
2843 // Invert sign bit (signed to unsigned mapping).
2844 Lo = DAG.getNode(ISD::XOR, dl, MVT::i32, Lo,
2845 DAG.getConstant(0x80000000u, dl, MVT::i32));
2846 }
2847 // Initial hi portion of constructed double.
2848 SDValue Hi = DAG.getConstant(0x43300000u, dl, MVT::i32);
2849
2850 // If this a big endian target, swap the lo and high data.
2851 if (DAG.getDataLayout().isBigEndian())
2852 std::swap(Lo, Hi);
2853
2854 SDValue MemChain = DAG.getEntryNode();
2855
2856 // Store the lo of the constructed double.
2857 SDValue Store1 = DAG.getStore(MemChain, dl, Lo, StackSlot,
2858 MachinePointerInfo());
2859 // Store the hi of the constructed double.
2860 SDValue HiPtr =
2861 DAG.getMemBasePlusOffset(StackSlot, TypeSize::getFixed(4), dl);
2862 SDValue Store2 =
2863 DAG.getStore(MemChain, dl, Hi, HiPtr, MachinePointerInfo());
2864 MemChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
2865
2866 // load the constructed double
2867 SDValue Load =
2868 DAG.getLoad(MVT::f64, dl, MemChain, StackSlot, MachinePointerInfo());
2869 // FP constant to bias correct the final result
2870 SDValue Bias = DAG.getConstantFP(
2871 isSigned ? llvm::bit_cast<double>(0x4330000080000000ULL)
2872 : llvm::bit_cast<double>(0x4330000000000000ULL),
2873 dl, MVT::f64);
2874 // Subtract the bias and get the final result.
2875 SDValue Sub;
2877 if (Node->isStrictFPOpcode()) {
2878 Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::f64, MVT::Other},
2879 {Node->getOperand(0), Load, Bias});
2880 Chain = Sub.getValue(1);
2881 if (DestVT != Sub.getValueType()) {
2882 std::pair<SDValue, SDValue> ResultPair;
2883 ResultPair =
2884 DAG.getStrictFPExtendOrRound(Sub, Chain, dl, DestVT);
2885 Result = ResultPair.first;
2886 Chain = ResultPair.second;
2887 }
2888 else
2889 Result = Sub;
2890 } else {
2891 Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
2892 Result = DAG.getFPExtendOrRound(Sub, dl, DestVT);
2893 }
2894 return Result;
2895 }
2896
2897 if (isSigned)
2898 return SDValue();
2899
2900 // TODO: Generalize this for use with other types.
2901 if (((SrcVT == MVT::i32 || SrcVT == MVT::i64) && DestVT == MVT::f32) ||
2902 (SrcVT == MVT::i64 && DestVT == MVT::f64)) {
2903 LLVM_DEBUG(dbgs() << "Converting unsigned i32/i64 to f32/f64\n");
2904 // For unsigned conversions, convert them to signed conversions using the
2905 // algorithm from the x86_64 __floatundisf in compiler_rt. That method
2906 // should be valid for i32->f32 as well.
2907
2908 // More generally this transform should be valid if there are 3 more bits
2909 // in the integer type than the significand. Rounding uses the first bit
2910 // after the width of the significand and the OR of all bits after that. So
2911 // we need to be able to OR the shifted out bit into one of the bits that
2912 // participate in the OR.
2913
2914 // TODO: This really should be implemented using a branch rather than a
2915 // select. We happen to get lucky and machinesink does the right
2916 // thing most of the time. This would be a good candidate for a
2917 // pseudo-op, or, even better, for whole-function isel.
2918 EVT SetCCVT = getSetCCResultType(SrcVT);
2919
2920 SDValue SignBitTest = DAG.getSetCC(
2921 dl, SetCCVT, Op0, DAG.getConstant(0, dl, SrcVT), ISD::SETLT);
2922
2923 SDValue ShiftConst = DAG.getShiftAmountConstant(1, SrcVT, dl);
2924 SDValue Shr = DAG.getNode(ISD::SRL, dl, SrcVT, Op0, ShiftConst);
2925 SDValue AndConst = DAG.getConstant(1, dl, SrcVT);
2926 SDValue And = DAG.getNode(ISD::AND, dl, SrcVT, Op0, AndConst);
2927 SDValue Or = DAG.getNode(ISD::OR, dl, SrcVT, And, Shr);
2928
2929 SDValue Slow, Fast;
2930 if (Node->isStrictFPOpcode()) {
2931 // In strict mode, we must avoid spurious exceptions, and therefore
2932 // must make sure to only emit a single STRICT_SINT_TO_FP.
2933 SDValue InCvt = DAG.getSelect(dl, SrcVT, SignBitTest, Or, Op0);
2934 // The STRICT_SINT_TO_FP inherits the exception mode from the
2935 // incoming STRICT_UINT_TO_FP node; the STRICT_FADD node can
2936 // never raise any exception.
2937 SDNodeFlags Flags;
2938 Flags.setNoFPExcept(Node->getFlags().hasNoFPExcept());
2939 Fast = DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {DestVT, MVT::Other},
2940 {Node->getOperand(0), InCvt}, Flags);
2941 Flags.setNoFPExcept(true);
2942 Slow = DAG.getNode(ISD::STRICT_FADD, dl, {DestVT, MVT::Other},
2943 {Fast.getValue(1), Fast, Fast}, Flags);
2944 Chain = Slow.getValue(1);
2945 } else {
2946 SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Or);
2947 Slow = DAG.getNode(ISD::FADD, dl, DestVT, SignCvt, SignCvt);
2948 Fast = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2949 }
2950
2951 return DAG.getSelect(dl, DestVT, SignBitTest, Slow, Fast);
2952 }
2953
2954 // Don't expand it if there isn't cheap fadd.
2956 Node->isStrictFPOpcode() ? ISD::STRICT_FADD : ISD::FADD, DestVT))
2957 return SDValue();
2958
2959 // The following optimization is valid only if every value in SrcVT (when
2960 // treated as signed) is representable in DestVT. Check that the mantissa
2961 // size of DestVT is >= than the number of bits in SrcVT -1.
2962 assert(APFloat::semanticsPrecision(DestVT.getFltSemantics()) >=
2963 SrcVT.getSizeInBits() - 1 &&
2964 "Cannot perform lossless SINT_TO_FP!");
2965
2966 SDValue Tmp1;
2967 if (Node->isStrictFPOpcode()) {
2968 Tmp1 = DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, { DestVT, MVT::Other },
2969 { Node->getOperand(0), Op0 });
2970 } else
2971 Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2972
2973 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(SrcVT), Op0,
2974 DAG.getConstant(0, dl, SrcVT), ISD::SETLT);
2975 SDValue Zero = DAG.getIntPtrConstant(0, dl),
2976 Four = DAG.getIntPtrConstant(4, dl);
2977 SDValue CstOffset = DAG.getSelect(dl, Zero.getValueType(),
2978 SignSet, Four, Zero);
2979
2980 // If the sign bit of the integer is set, the large number will be treated
2981 // as a negative number. To counteract this, the dynamic code adds an
2982 // offset depending on the data type.
2983 uint64_t FF;
2984 switch (SrcVT.getSimpleVT().SimpleTy) {
2985 default:
2986 return SDValue();
2987 case MVT::i8 : FF = 0x43800000ULL; break; // 2^8 (as a float)
2988 case MVT::i16: FF = 0x47800000ULL; break; // 2^16 (as a float)
2989 case MVT::i32: FF = 0x4F800000ULL; break; // 2^32 (as a float)
2990 case MVT::i64: FF = 0x5F800000ULL; break; // 2^64 (as a float)
2991 }
2992 if (DAG.getDataLayout().isLittleEndian())
2993 FF <<= 32;
2994 Constant *FudgeFactor = ConstantInt::get(
2995 Type::getInt64Ty(*DAG.getContext()), FF);
2996
2997 SDValue CPIdx =
2998 DAG.getConstantPool(FudgeFactor, TLI.getPointerTy(DAG.getDataLayout()));
2999 Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign();
3000 CPIdx = DAG.getNode(ISD::ADD, dl, CPIdx.getValueType(), CPIdx, CstOffset);
3001 Alignment = commonAlignment(Alignment, 4);
3002 SDValue FudgeInReg;
3003 if (DestVT == MVT::f32)
3004 FudgeInReg = DAG.getLoad(
3005 MVT::f32, dl, DAG.getEntryNode(), CPIdx,
3007 Alignment);
3008 else {
3009 SDValue Load = DAG.getExtLoad(
3010 ISD::EXTLOAD, dl, DestVT, DAG.getEntryNode(), CPIdx,
3012 Alignment);
3013 HandleSDNode Handle(Load);
3014 LegalizeOp(Load.getNode());
3015 FudgeInReg = Handle.getValue();
3016 }
3017
3018 if (Node->isStrictFPOpcode()) {
3019 SDValue Result = DAG.getNode(ISD::STRICT_FADD, dl, { DestVT, MVT::Other },
3020 { Tmp1.getValue(1), Tmp1, FudgeInReg });
3021 Chain = Result.getValue(1);
3022 return Result;
3023 }
3024
3025 return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
3026}
3027
3028/// This function is responsible for legalizing a
3029/// *INT_TO_FP operation of the specified operand when the target requests that
3030/// we promote it. At this point, we know that the result and operand types are
3031/// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
3032/// operation that takes a larger input.
3033void SelectionDAGLegalize::PromoteLegalINT_TO_FP(
3034 SDNode *N, const SDLoc &dl, SmallVectorImpl<SDValue> &Results) {
3035 bool IsStrict = N->isStrictFPOpcode();
3036 bool IsSigned = N->getOpcode() == ISD::SINT_TO_FP ||
3037 N->getOpcode() == ISD::STRICT_SINT_TO_FP;
3038 EVT DestVT = N->getValueType(0);
3039 SDValue LegalOp = N->getOperand(IsStrict ? 1 : 0);
3040 unsigned UIntOp = IsStrict ? ISD::STRICT_UINT_TO_FP : ISD::UINT_TO_FP;
3041 unsigned SIntOp = IsStrict ? ISD::STRICT_SINT_TO_FP : ISD::SINT_TO_FP;
3042
3043 // First step, figure out the appropriate *INT_TO_FP operation to use.
3044 EVT NewInTy = LegalOp.getValueType();
3045
3046 unsigned OpToUse = 0;
3047
3048 // Scan for the appropriate larger type to use.
3049 while (true) {
3050 NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1);
3051 assert(NewInTy.isInteger() && "Ran out of possibilities!");
3052
3053 // If the target supports SINT_TO_FP of this type, use it.
3054 if (TLI.isOperationLegalOrCustom(SIntOp, NewInTy)) {
3055 OpToUse = SIntOp;
3056 break;
3057 }
3058 if (IsSigned)
3059 continue;
3060
3061 // If the target supports UINT_TO_FP of this type, use it.
3062 if (TLI.isOperationLegalOrCustom(UIntOp, NewInTy)) {
3063 OpToUse = UIntOp;
3064 break;
3065 }
3066
3067 // Otherwise, try a larger type.
3068 }
3069
3070 // Okay, we found the operation and type to use. Zero extend our input to the
3071 // desired type then run the operation on it.
3072 if (IsStrict) {
3073 SDValue Res =
3074 DAG.getNode(OpToUse, dl, {DestVT, MVT::Other},
3075 {N->getOperand(0),
3076 DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
3077 dl, NewInTy, LegalOp)});
3078 Results.push_back(Res);
3079 Results.push_back(Res.getValue(1));
3080 return;
3081 }
3082
3083 Results.push_back(
3084 DAG.getNode(OpToUse, dl, DestVT,
3085 DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
3086 dl, NewInTy, LegalOp)));
3087}
3088
3089/// This function is responsible for legalizing a
3090/// FP_TO_*INT operation of the specified operand when the target requests that
3091/// we promote it. At this point, we know that the result and operand types are
3092/// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
3093/// operation that returns a larger result.
3094void SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDNode *N, const SDLoc &dl,
3095 SmallVectorImpl<SDValue> &Results) {
3096 bool IsStrict = N->isStrictFPOpcode();
3097 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
3098 N->getOpcode() == ISD::STRICT_FP_TO_SINT;
3099 EVT DestVT = N->getValueType(0);
3100 SDValue LegalOp = N->getOperand(IsStrict ? 1 : 0);
3101 // First step, figure out the appropriate FP_TO*INT operation to use.
3102 EVT NewOutTy = DestVT;
3103
3104 unsigned OpToUse = 0;
3105
3106 // Scan for the appropriate larger type to use.
3107 while (true) {
3108 NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1);
3109 assert(NewOutTy.isInteger() && "Ran out of possibilities!");
3110
3111 // A larger signed type can hold all unsigned values of the requested type,
3112 // so using FP_TO_SINT is valid
3113 OpToUse = IsStrict ? ISD::STRICT_FP_TO_SINT : ISD::FP_TO_SINT;
3114 if (TLI.isOperationLegalOrCustom(OpToUse, NewOutTy))
3115 break;
3116
3117 // However, if the value may be < 0.0, we *must* use some FP_TO_SINT.
3118 OpToUse = IsStrict ? ISD::STRICT_FP_TO_UINT : ISD::FP_TO_UINT;
3119 if (!IsSigned && TLI.isOperationLegalOrCustom(OpToUse, NewOutTy))
3120 break;
3121
3122 // Otherwise, try a larger type.
3123 }
3124
3125 // Okay, we found the operation and type to use.
3127 if (IsStrict) {
3128 SDVTList VTs = DAG.getVTList(NewOutTy, MVT::Other);
3129 Operation = DAG.getNode(OpToUse, dl, VTs, N->getOperand(0), LegalOp);
3130 } else
3131 Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
3132
3133 // Truncate the result of the extended FP_TO_*INT operation to the desired
3134 // size.
3135 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
3136 Results.push_back(Trunc);
3137 if (IsStrict)
3138 Results.push_back(Operation.getValue(1));
3139}
3140
3141/// Promote FP_TO_*INT_SAT operation to a larger result type. At this point
3142/// the result and operand types are legal and there must be a legal
3143/// FP_TO_*INT_SAT operation for a larger result type.
3144SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT_SAT(SDNode *Node,
3145 const SDLoc &dl) {
3146 unsigned Opcode = Node->getOpcode();
3147
3148 // Scan for the appropriate larger type to use.
3149 EVT NewOutTy = Node->getValueType(0);
3150 while (true) {
3151 NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy + 1);
3152 assert(NewOutTy.isInteger() && "Ran out of possibilities!");
3153
3154 if (TLI.isOperationLegalOrCustom(Opcode, NewOutTy))
3155 break;
3156 }
3157
3158 // Saturation width is determined by second operand, so we don't have to
3159 // perform any fixup and can directly truncate the result.
3160 SDValue Result = DAG.getNode(Opcode, dl, NewOutTy, Node->getOperand(0),
3161 Node->getOperand(1));
3162 return DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Result);
3163}
3164
3165/// Open code the operations for PARITY of the specified operation.
3166SDValue SelectionDAGLegalize::ExpandPARITY(SDValue Op, const SDLoc &dl) {
3167 EVT VT = Op.getValueType();
3168 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
3169 unsigned Sz = VT.getScalarSizeInBits();
3170
3171 // If CTPOP is legal, use it. Otherwise use shifts and xor.
3174 Result = DAG.getNode(ISD::CTPOP, dl, VT, Op);
3175 } else {
3176 Result = Op;
3177 for (unsigned i = Log2_32_Ceil(Sz); i != 0;) {
3178 SDValue Shift = DAG.getNode(ISD::SRL, dl, VT, Result,
3179 DAG.getConstant(1ULL << (--i), dl, ShVT));
3180 Result = DAG.getNode(ISD::XOR, dl, VT, Result, Shift);
3181 }
3182 }
3183
3184 return DAG.getNode(ISD::AND, dl, VT, Result, DAG.getConstant(1, dl, VT));
3185}
3186
3187SDValue SelectionDAGLegalize::PromoteReduction(SDNode *Node) {
3188 bool IsVPOpcode = ISD::isVPOpcode(Node->getOpcode());
3189 MVT VecVT = IsVPOpcode ? Node->getOperand(1).getSimpleValueType()
3190 : Node->getOperand(0).getSimpleValueType();
3191 MVT NewVecVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VecVT);
3192 MVT ScalarVT = Node->getSimpleValueType(0);
3193 MVT NewScalarVT = NewVecVT.getVectorElementType();
3194
3195 SDLoc DL(Node);
3196 SmallVector<SDValue, 4> Operands(Node->getNumOperands());
3197
3198 // FIXME: Support integer.
3199 assert(Node->getOperand(0).getValueType().isFloatingPoint() &&
3200 "Only FP promotion is supported");
3201
3202 for (unsigned j = 0; j != Node->getNumOperands(); ++j)
3203 if (Node->getOperand(j).getValueType().isVector() &&
3204 !(IsVPOpcode &&
3205 ISD::getVPMaskIdx(Node->getOpcode()) == j)) { // Skip mask operand.
3206 // promote the vector operand.
3207 // FIXME: Support integer.
3208 assert(Node->getOperand(j).getValueType().isFloatingPoint() &&
3209 "Only FP promotion is supported");
3210 Operands[j] =
3211 DAG.getNode(ISD::FP_EXTEND, DL, NewVecVT, Node->getOperand(j));
3212 } else if (Node->getOperand(j).getValueType().isFloatingPoint()) {
3213 // promote the initial value.
3214 Operands[j] =
3215 DAG.getNode(ISD::FP_EXTEND, DL, NewScalarVT, Node->getOperand(j));
3216 } else {
3217 Operands[j] = Node->getOperand(j); // Skip VL operand.
3218 }
3219
3220 SDValue Res = DAG.getNode(Node->getOpcode(), DL, NewScalarVT, Operands,
3221 Node->getFlags());
3222
3223 assert(ScalarVT.isFloatingPoint() && "Only FP promotion is supported");
3224 return DAG.getNode(ISD::FP_ROUND, DL, ScalarVT, Res,
3225 DAG.getIntPtrConstant(0, DL, /*isTarget=*/true));
3226}
3227
3228bool SelectionDAGLegalize::ExpandNode(SDNode *Node) {
3229 LLVM_DEBUG(dbgs() << "Trying to expand node\n");
3231 SDLoc dl(Node);
3232 SDValue Tmp1, Tmp2, Tmp3, Tmp4;
3233 bool NeedInvert;
3234 switch (Node->getOpcode()) {
3235 case ISD::ABS:
3237 if ((Tmp1 = TLI.expandABS(Node, DAG)))
3238 Results.push_back(Tmp1);
3239 break;
3240 case ISD::ABDS:
3241 case ISD::ABDU:
3242 if ((Tmp1 = TLI.expandABD(Node, DAG)))
3243 Results.push_back(Tmp1);
3244 break;
3245 case ISD::AVGCEILS:
3246 case ISD::AVGCEILU:
3247 case ISD::AVGFLOORS:
3248 case ISD::AVGFLOORU:
3249 if ((Tmp1 = TLI.expandAVG(Node, DAG)))
3250 Results.push_back(Tmp1);
3251 break;
3252 case ISD::CTPOP:
3253 if ((Tmp1 = TLI.expandCTPOP(Node, DAG)))
3254 Results.push_back(Tmp1);
3255 break;
3256 case ISD::CTLZ:
3258 if ((Tmp1 = TLI.expandCTLZ(Node, DAG)))
3259 Results.push_back(Tmp1);
3260 break;
3261 case ISD::CTLS:
3262 if ((Tmp1 = TLI.expandCTLS(Node, DAG)))
3263 Results.push_back(Tmp1);
3264 break;
3265 case ISD::CTTZ:
3267 if ((Tmp1 = TLI.expandCTTZ(Node, DAG)))
3268 Results.push_back(Tmp1);
3269 break;
3270 case ISD::BITREVERSE:
3271 if ((Tmp1 = TLI.expandBITREVERSE(Node, DAG)))
3272 Results.push_back(Tmp1);
3273 break;
3274 case ISD::BSWAP:
3275 if ((Tmp1 = TLI.expandBSWAP(Node, DAG)))
3276 Results.push_back(Tmp1);
3277 break;
3278 case ISD::PARITY:
3279 Results.push_back(ExpandPARITY(Node->getOperand(0), dl));
3280 break;
3281 case ISD::FRAMEADDR:
3282 case ISD::RETURNADDR:
3284 Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0)));
3285 break;
3286 case ISD::EH_DWARF_CFA: {
3287 SDValue CfaArg = DAG.getSExtOrTrunc(Node->getOperand(0), dl,
3289 SDValue Offset = DAG.getNode(ISD::ADD, dl,
3290 CfaArg.getValueType(),
3292 CfaArg.getValueType()),
3293 CfaArg);
3294 SDValue FA = DAG.getNode(
3296 DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())));
3297 Results.push_back(DAG.getNode(ISD::ADD, dl, FA.getValueType(),
3298 FA, Offset));
3299 break;
3300 }
3301 case ISD::GET_ROUNDING:
3302 Results.push_back(DAG.getConstant(1, dl, Node->getValueType(0)));
3303 Results.push_back(Node->getOperand(0));
3304 break;
3305 case ISD::EH_RETURN:
3306 case ISD::PREFETCH:
3307 case ISD::VAEND:
3309 // If the target didn't expand these, there's nothing to do, so just
3310 // preserve the chain and be done.
3311 Results.push_back(Node->getOperand(0));
3312 break;
3315 // If the target didn't expand this, just return 'zero' and preserve the
3316 // chain.
3317 Results.append(Node->getNumValues() - 1,
3318 DAG.getConstant(0, dl, Node->getValueType(0)));
3319 Results.push_back(Node->getOperand(0));
3320 break;
3322 // If the target didn't expand this, just return 'zero' and preserve the
3323 // chain.
3324 Results.push_back(DAG.getConstant(0, dl, MVT::i32));
3325 Results.push_back(Node->getOperand(0));
3326 break;
3327 case ISD::ATOMIC_LOAD: {
3328 // There is no libcall for atomic load; fake it with ATOMIC_CMP_SWAP.
3329 SDValue Zero = DAG.getConstant(0, dl, Node->getValueType(0));
3330 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
3332 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
3333 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
3334 cast<AtomicSDNode>(Node)->getMemOperand());
3335 Results.push_back(Swap.getValue(0));
3336 Results.push_back(Swap.getValue(1));
3337 break;
3338 }
3339 case ISD::ATOMIC_STORE: {
3340 // There is no libcall for atomic store; fake it with ATOMIC_SWAP.
3341 SDValue Swap = DAG.getAtomic(
3342 ISD::ATOMIC_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(),
3343 Node->getOperand(0), Node->getOperand(2), Node->getOperand(1),
3344 cast<AtomicSDNode>(Node)->getMemOperand());
3345 Results.push_back(Swap.getValue(1));
3346 break;
3347 }
3349 // Expanding an ATOMIC_CMP_SWAP_WITH_SUCCESS produces an ATOMIC_CMP_SWAP and
3350 // splits out the success value as a comparison. Expanding the resulting
3351 // ATOMIC_CMP_SWAP will produce a libcall.
3352 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
3353 SDValue Res = DAG.getAtomicCmpSwap(
3354 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
3355 Node->getOperand(0), Node->getOperand(1), Node->getOperand(2),
3356 Node->getOperand(3), cast<MemSDNode>(Node)->getMemOperand());
3357
3358 SDValue ExtRes = Res;
3359 SDValue LHS = Res;
3360 SDValue RHS = Node->getOperand(1);
3361
3362 EVT AtomicType = cast<AtomicSDNode>(Node)->getMemoryVT();
3363 EVT OuterType = Node->getValueType(0);
3364 switch (TLI.getExtendForAtomicOps()) {
3365 case ISD::SIGN_EXTEND:
3366 LHS = DAG.getNode(ISD::AssertSext, dl, OuterType, Res,
3367 DAG.getValueType(AtomicType));
3368 RHS = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, OuterType,
3369 Node->getOperand(2), DAG.getValueType(AtomicType));
3370 ExtRes = LHS;
3371 break;
3372 case ISD::ZERO_EXTEND:
3373 LHS = DAG.getNode(ISD::AssertZext, dl, OuterType, Res,
3374 DAG.getValueType(AtomicType));
3375 RHS = DAG.getZeroExtendInReg(Node->getOperand(2), dl, AtomicType);
3376 ExtRes = LHS;
3377 break;
3378 case ISD::ANY_EXTEND:
3379 LHS = DAG.getZeroExtendInReg(Res, dl, AtomicType);
3380 RHS = DAG.getZeroExtendInReg(Node->getOperand(2), dl, AtomicType);
3381 break;
3382 default:
3383 llvm_unreachable("Invalid atomic op extension");
3384 }
3385
3387 DAG.getSetCC(dl, Node->getValueType(1), LHS, RHS, ISD::SETEQ);
3388
3389 Results.push_back(ExtRes.getValue(0));
3390 Results.push_back(Success);
3391 Results.push_back(Res.getValue(1));
3392 break;
3393 }
3394 case ISD::ATOMIC_LOAD_SUB: {
3395 SDLoc DL(Node);
3396 EVT VT = Node->getValueType(0);
3397 SDValue RHS = Node->getOperand(2);
3398 AtomicSDNode *AN = cast<AtomicSDNode>(Node);
3399 if (RHS->getOpcode() == ISD::SIGN_EXTEND_INREG &&
3400 cast<VTSDNode>(RHS->getOperand(1))->getVT() == AN->getMemoryVT())
3401 RHS = RHS->getOperand(0);
3402 SDValue NewRHS =
3403 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), RHS);
3405 Node->getOperand(0), Node->getOperand(1),
3406 NewRHS, AN->getMemOperand());
3407 Results.push_back(Res);
3408 Results.push_back(Res.getValue(1));
3409 break;
3410 }
3411 case ISD::ATOMIC_LOAD_AND: {
3412 AtomicSDNode *AN = cast<AtomicSDNode>(Node);
3414 TargetLowering::Expand)
3415 break;
3416
3417 SDLoc DL(Node);
3418 EVT VT = Node->getValueType(0);
3419 SDValue NewRHS = DAG.getNOT(DL, Node->getOperand(2), VT);
3421 Node->getOperand(0), Node->getOperand(1),
3422 NewRHS, AN->getMemOperand());
3423 Results.push_back(Res);
3424 Results.push_back(Res.getValue(1));
3425 break;
3426 }
3427 case ISD::ATOMIC_LOAD_FSUB: {
3428 SDLoc DL(Node);
3429 EVT VT = Node->getValueType(0);
3430 AtomicSDNode *AN = cast<AtomicSDNode>(Node);
3431 SDValue NewRHS = DAG.getNode(ISD::FNEG, DL, VT, Node->getOperand(2));
3433 Node->getOperand(0), Node->getOperand(1),
3434 NewRHS, AN->getMemOperand());
3435 Results.push_back(Res);
3436 Results.push_back(Res.getValue(1));
3437 break;
3438 }
3440 ExpandDYNAMIC_STACKALLOC(Node, Results);
3441 break;
3442 case ISD::MERGE_VALUES:
3443 for (unsigned i = 0; i < Node->getNumValues(); i++)
3444 Results.push_back(Node->getOperand(i));
3445 break;
3446 case ISD::POISON:
3447 case ISD::UNDEF: {
3448 EVT VT = Node->getValueType(0);
3449 if (VT.isInteger())
3450 Results.push_back(DAG.getConstant(0, dl, VT));
3451 else {
3452 assert(VT.isFloatingPoint() && "Unknown value type!");
3453 Results.push_back(DAG.getConstantFP(0, dl, VT));
3454 }
3455 break;
3456 }
3458 // When strict mode is enforced we can't do expansion because it
3459 // does not honor the "strict" properties. Only libcall is allowed.
3460 if (TLI.isStrictFPEnabled())
3461 break;
3462 // We might as well mutate to FP_ROUND when FP_ROUND operation is legal
3463 // since this operation is more efficient than stack operation.
3464 if (TLI.getStrictFPOperationAction(Node->getOpcode(),
3465 Node->getValueType(0))
3466 == TargetLowering::Legal)
3467 break;
3468 // We fall back to use stack operation when the FP_ROUND operation
3469 // isn't available.
3470 if ((Tmp1 = EmitStackConvert(Node->getOperand(1), Node->getValueType(0),
3471 Node->getValueType(0), dl,
3472 Node->getOperand(0)))) {
3473 ReplaceNode(Node, Tmp1.getNode());
3474 LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_ROUND node\n");
3475 return true;
3476 }
3477 break;
3478 case ISD::FP_ROUND: {
3479 if ((Tmp1 = TLI.expandFP_ROUND(Node, DAG))) {
3480 Results.push_back(Tmp1);
3481 break;
3482 }
3483
3484 [[fallthrough]];
3485 }
3486 case ISD::BITCAST:
3487 if ((Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
3488 Node->getValueType(0), dl)))
3489 Results.push_back(Tmp1);
3490 break;
3492 // When strict mode is enforced we can't do expansion because it
3493 // does not honor the "strict" properties. Only libcall is allowed.
3494 if (TLI.isStrictFPEnabled())
3495 break;
3496 // We might as well mutate to FP_EXTEND when FP_EXTEND operation is legal
3497 // since this operation is more efficient than stack operation.
3498 if (TLI.getStrictFPOperationAction(Node->getOpcode(),
3499 Node->getValueType(0))
3500 == TargetLowering::Legal)
3501 break;
3502 // We fall back to use stack operation when the FP_EXTEND operation
3503 // isn't available.
3504 if ((Tmp1 = EmitStackConvert(
3505 Node->getOperand(1), Node->getOperand(1).getValueType(),
3506 Node->getValueType(0), dl, Node->getOperand(0)))) {
3507 ReplaceNode(Node, Tmp1.getNode());
3508 LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_EXTEND node\n");
3509 return true;
3510 }
3511 break;
3512 case ISD::FP_EXTEND: {
3513 SDValue Op = Node->getOperand(0);
3514 EVT SrcVT = Op.getValueType();
3515 EVT DstVT = Node->getValueType(0);
3516 if (SrcVT.getScalarType() == MVT::bf16) {
3517 Results.push_back(DAG.getNode(ISD::BF16_TO_FP, SDLoc(Node), DstVT, Op));
3518 break;
3519 }
3520
3521 if ((Tmp1 = EmitStackConvert(Op, SrcVT, DstVT, dl)))
3522 Results.push_back(Tmp1);
3523 break;
3524 }
3525 case ISD::BF16_TO_FP: {
3526 // Always expand bf16 to f32 casts, they lower to ext + shift.
3527 //
3528 // Note that the operand of this code can be bf16 or an integer type in case
3529 // bf16 is not supported on the target and was softened.
3530 SDValue Op = Node->getOperand(0);
3531 if (Op.getValueType() == MVT::bf16) {
3532 Op = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32,
3533 DAG.getNode(ISD::BITCAST, dl, MVT::i16, Op));
3534 } else {
3535 Op = DAG.getAnyExtOrTrunc(Op, dl, MVT::i32);
3536 }
3537 Op = DAG.getNode(ISD::SHL, dl, MVT::i32, Op,
3538 DAG.getShiftAmountConstant(16, MVT::i32, dl));
3539 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op);
3540 // Add fp_extend in case the output is bigger than f32.
3541 if (Node->getValueType(0) != MVT::f32)
3542 Op = DAG.getNode(ISD::FP_EXTEND, dl, Node->getValueType(0), Op);
3543 Results.push_back(Op);
3544 break;
3545 }
3546 case ISD::FP_TO_BF16: {
3547 SDValue Op = Node->getOperand(0);
3548 if (Op.getValueType() != MVT::f32)
3549 Op = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Op,
3550 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
3551 // Certain SNaNs will turn into infinities if we do a simple shift right.
3552 if (!DAG.isKnownNeverSNaN(Op)) {
3553 Op = DAG.getNode(ISD::FCANONICALIZE, dl, MVT::f32, Op, Node->getFlags());
3554 }
3555 Op = DAG.getNode(ISD::SRL, dl, MVT::i32,
3556 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op),
3557 DAG.getShiftAmountConstant(16, MVT::i32, dl));
3558 // The result of this node can be bf16 or an integer type in case bf16 is
3559 // not supported on the target and was softened to i16 for storage.
3560 if (Node->getValueType(0) == MVT::bf16) {
3561 Op = DAG.getNode(ISD::BITCAST, dl, MVT::bf16,
3562 DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Op));
3563 } else {
3564 Op = DAG.getAnyExtOrTrunc(Op, dl, Node->getValueType(0));
3565 }
3566 Results.push_back(Op);
3567 break;
3568 }
3570 // Expand conversion from arbitrary FP format stored in an integer to a
3571 // native IEEE float type using integer bit manipulation.
3572 //
3573 // TODO: currently only conversions from FP4, FP6 and FP8 formats from OCP
3574 // specification are expanded. Remaining arbitrary FP types: Float8E4M3,
3575 // Float8E3M4, Float8E5M2FNUZ, Float8E4M3FNUZ, Float8E4M3B11FNUZ,
3576 // Float8E8M0FNU.
3577 EVT DstVT = Node->getValueType(0);
3578 if (SDValue Expanded = TLI.expandCONVERT_FROM_ARBITRARY_FP(Node, DAG))
3579 Results.push_back(Expanded);
3580 else
3581 Results.push_back(DAG.getPOISON(DstVT));
3582 break;
3583 }
3585 // Expand conversion from a native IEEE float type to an arbitrary FP
3586 // format, returning the result as an integer using bit manipulation.
3587 //
3588 // TODO: currently only conversions to FP4, FP6 and FP8 formats from OCP
3589 // specification are expanded. Remaining arbitrary FP types: Float8E4M3,
3590 // Float8E3M4, Float8E5M2FNUZ, Float8E4M3FNUZ, Float8E4M3B11FNUZ,
3591 // Float8E8M0FNU.
3592 EVT ResVT = Node->getValueType(0);
3593 if (SDValue Expanded = TLI.expandCONVERT_TO_ARBITRARY_FP(Node, DAG))
3594 Results.push_back(Expanded);
3595 else
3596 Results.push_back(DAG.getPOISON(ResVT));
3597 break;
3598 }
3599 case ISD::FCANONICALIZE: {
3600 SDValue Mul = TLI.expandFCANONICALIZE(Node, DAG);
3601 Results.push_back(Mul);
3602 break;
3603 }
3605 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
3606 EVT VT = Node->getValueType(0);
3607
3608 // An in-register sign-extend of a boolean is a negation:
3609 // 'true' (1) sign-extended is -1.
3610 // 'false' (0) sign-extended is 0.
3611 // However, we must mask the high bits of the source operand because the
3612 // SIGN_EXTEND_INREG does not guarantee that the high bits are already zero.
3613
3614 // TODO: Do this for vectors too?
3615 if (ExtraVT.isScalarInteger() && ExtraVT.getSizeInBits() == 1) {
3616 SDValue One = DAG.getConstant(1, dl, VT);
3617 SDValue And = DAG.getNode(ISD::AND, dl, VT, Node->getOperand(0), One);
3618 SDValue Zero = DAG.getConstant(0, dl, VT);
3619 SDValue Neg = DAG.getNode(ISD::SUB, dl, VT, Zero, And);
3620 Results.push_back(Neg);
3621 break;
3622 }
3623
3624 // NOTE: we could fall back on load/store here too for targets without
3625 // SRA. However, it is doubtful that any exist.
3626 unsigned BitsDiff = VT.getScalarSizeInBits() -
3627 ExtraVT.getScalarSizeInBits();
3628 SDValue ShiftCst = DAG.getShiftAmountConstant(BitsDiff, VT, dl);
3629 Tmp1 = DAG.getNode(ISD::SHL, dl, VT, Node->getOperand(0), ShiftCst);
3630 Tmp1 = DAG.getNode(ISD::SRA, dl, VT, Tmp1, ShiftCst);
3631 Results.push_back(Tmp1);
3632 break;
3633 }
3634 case ISD::UINT_TO_FP:
3636 if (TLI.expandUINT_TO_FP(Node, Tmp1, Tmp2, DAG)) {
3637 Results.push_back(Tmp1);
3638 if (Node->isStrictFPOpcode())
3639 Results.push_back(Tmp2);
3640 break;
3641 }
3642 [[fallthrough]];
3643 case ISD::SINT_TO_FP:
3645 if ((Tmp1 = ExpandLegalINT_TO_FP(Node, Tmp2))) {
3646 Results.push_back(Tmp1);
3647 if (Node->isStrictFPOpcode())
3648 Results.push_back(Tmp2);
3649 }
3650 break;
3651 case ISD::FP_TO_SINT:
3652 if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG))
3653 Results.push_back(Tmp1);
3654 break;
3656 if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG)) {
3657 ReplaceNode(Node, Tmp1.getNode());
3658 LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_TO_SINT node\n");
3659 return true;
3660 }
3661 break;
3662 case ISD::FP_TO_UINT:
3663 if (TLI.expandFP_TO_UINT(Node, Tmp1, Tmp2, DAG))
3664 Results.push_back(Tmp1);
3665 break;
3667 if (TLI.expandFP_TO_UINT(Node, Tmp1, Tmp2, DAG)) {
3668 // Relink the chain.
3669 DAG.ReplaceAllUsesOfValueWith(SDValue(Node,1), Tmp2);
3670 // Replace the new UINT result.
3671 ReplaceNodeWithValue(SDValue(Node, 0), Tmp1);
3672 LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_TO_UINT node\n");
3673 return true;
3674 }
3675 break;
3678 Results.push_back(TLI.expandFP_TO_INT_SAT(Node, DAG));
3679 break;
3680 case ISD::LROUND:
3681 case ISD::LLROUND: {
3682 SDValue Arg = Node->getOperand(0);
3683 EVT ArgVT = Arg.getValueType();
3684 EVT ResVT = Node->getValueType(0);
3685 SDLoc dl(Node);
3686 SDValue RoundNode = DAG.getNode(ISD::FROUND, dl, ArgVT, Arg);
3687 Results.push_back(DAG.getNode(ISD::FP_TO_SINT, dl, ResVT, RoundNode));
3688 break;
3689 }
3690 case ISD::VAARG:
3691 Results.push_back(DAG.expandVAArg(Node));
3692 Results.push_back(Results[0].getValue(1));
3693 break;
3694 case ISD::VACOPY:
3695 Results.push_back(DAG.expandVACopy(Node));
3696 break;
3698 if (Node->getOperand(0).getValueType().getVectorElementCount().isScalar())
3699 // This must be an access of the only element. Return it.
3700 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0),
3701 Node->getOperand(0));
3702 else
3703 Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0));
3704 Results.push_back(Tmp1);
3705 break;
3707 Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0)));
3708 break;
3710 Results.push_back(ExpandInsertToVectorThroughStack(SDValue(Node, 0)));
3711 break;
3713 if (EVT VectorValueType = Node->getOperand(0).getValueType();
3714 VectorValueType.isScalableVector() ||
3716 Results.push_back(ExpandVectorBuildThroughStack(Node));
3717 else
3718 Results.push_back(ExpandConcatVectors(Node));
3719 break;
3721 Results.push_back(ExpandSCALAR_TO_VECTOR(Node));
3722 break;
3724 Results.push_back(ExpandINSERT_VECTOR_ELT(SDValue(Node, 0)));
3725 break;
3726 case ISD::VECTOR_SHUFFLE: {
3727 SmallVector<int, 32> NewMask;
3728 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
3729
3730 EVT VT = Node->getValueType(0);
3731 EVT EltVT = VT.getVectorElementType();
3732 SDValue Op0 = Node->getOperand(0);
3733 SDValue Op1 = Node->getOperand(1);
3734 if (!TLI.isTypeLegal(EltVT)) {
3735 EVT NewEltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT);
3736
3737 // BUILD_VECTOR operands are allowed to be wider than the element type.
3738 // But if NewEltVT is smaller that EltVT the BUILD_VECTOR does not accept
3739 // it.
3740 if (NewEltVT.bitsLT(EltVT)) {
3741 // Convert shuffle node.
3742 // If original node was v4i64 and the new EltVT is i32,
3743 // cast operands to v8i32 and re-build the mask.
3744
3745 // Calculate new VT, the size of the new VT should be equal to original.
3746 EVT NewVT =
3747 EVT::getVectorVT(*DAG.getContext(), NewEltVT,
3748 VT.getSizeInBits() / NewEltVT.getSizeInBits());
3749 assert(NewVT.bitsEq(VT));
3750
3751 // cast operands to new VT
3752 Op0 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op0);
3753 Op1 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op1);
3754
3755 // Convert the shuffle mask
3756 unsigned int factor =
3758
3759 // EltVT gets smaller
3760 assert(factor > 0);
3761
3762 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
3763 if (Mask[i] < 0) {
3764 for (unsigned fi = 0; fi < factor; ++fi)
3765 NewMask.push_back(Mask[i]);
3766 }
3767 else {
3768 for (unsigned fi = 0; fi < factor; ++fi)
3769 NewMask.push_back(Mask[i]*factor+fi);
3770 }
3771 }
3772 Mask = NewMask;
3773 VT = NewVT;
3774 }
3775 EltVT = NewEltVT;
3776 }
3777 unsigned NumElems = VT.getVectorNumElements();
3779 for (unsigned i = 0; i != NumElems; ++i) {
3780 if (Mask[i] < 0) {
3781 Ops.push_back(DAG.getUNDEF(EltVT));
3782 continue;
3783 }
3784 unsigned Idx = Mask[i];
3785 if (Idx < NumElems)
3786 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
3787 DAG.getVectorIdxConstant(Idx, dl)));
3788 else
3789 Ops.push_back(
3790 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op1,
3791 DAG.getVectorIdxConstant(Idx - NumElems, dl)));
3792 }
3793
3794 Tmp1 = DAG.getBuildVector(VT, dl, Ops);
3795 // We may have changed the BUILD_VECTOR type. Cast it back to the Node type.
3796 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), Tmp1);
3797 Results.push_back(Tmp1);
3798 break;
3799 }
3802 Results.push_back(TLI.expandVectorSplice(Node, DAG));
3803 break;
3804 }
3807 break;
3810 break;
3811 case ISD::EXTRACT_ELEMENT: {
3812 EVT OpTy = Node->getOperand(0).getValueType();
3813 if (Node->getConstantOperandVal(1)) {
3814 // 1 -> Hi
3815 Tmp1 = DAG.getNode(
3816 ISD::SRL, dl, OpTy, Node->getOperand(0),
3817 DAG.getShiftAmountConstant(OpTy.getSizeInBits() / 2, OpTy, dl));
3818 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
3819 } else {
3820 // 0 -> Lo
3821 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
3822 Node->getOperand(0));
3823 }
3824 Results.push_back(Tmp1);
3825 break;
3826 }
3827 case ISD::STACKADDRESS:
3828 case ISD::STACKSAVE:
3829 // Expand to CopyFromReg if the target set
3830 // StackPointerRegisterToSaveRestore.
3832 Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP,
3833 Node->getValueType(0)));
3834 Results.push_back(Results[0].getValue(1));
3835 } else {
3836 Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
3837 Results.push_back(Node->getOperand(0));
3838
3839 StringRef IntrinsicName = Node->getOpcode() == ISD::STACKADDRESS
3840 ? "llvm.stackaddress"
3841 : "llvm.stacksave";
3842 DAG.getContext()->diagnose(DiagnosticInfoLegalizationFailure(
3843 Twine(IntrinsicName) + " is not supported on this target.",
3845 }
3846 break;
3847 case ISD::STACKRESTORE:
3848 // Expand to CopyToReg if the target set
3849 // StackPointerRegisterToSaveRestore.
3851 Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP,
3852 Node->getOperand(1)));
3853 } else {
3854 Results.push_back(Node->getOperand(0));
3855 }
3856 break;
3858 Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0)));
3859 Results.push_back(Results[0].getValue(0));
3860 break;
3861 case ISD::FCOPYSIGN:
3862 Results.push_back(ExpandFCOPYSIGN(Node));
3863 break;
3864 case ISD::FNEG:
3865 Results.push_back(ExpandFNEG(Node));
3866 break;
3867 case ISD::FABS:
3868 Results.push_back(ExpandFABS(Node));
3869 break;
3870 case ISD::IS_FPCLASS: {
3871 auto Test = static_cast<FPClassTest>(Node->getConstantOperandVal(1));
3872 if (SDValue Expanded =
3873 TLI.expandIS_FPCLASS(Node->getValueType(0), Node->getOperand(0),
3874 Test, Node->getFlags(), SDLoc(Node), DAG))
3875 Results.push_back(Expanded);
3876 break;
3877 }
3878 case ISD::SMIN:
3879 case ISD::SMAX:
3880 case ISD::UMIN:
3881 case ISD::UMAX: {
3882 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
3884 switch (Node->getOpcode()) {
3885 default: llvm_unreachable("How did we get here?");
3886 case ISD::SMAX: Pred = ISD::SETGT; break;
3887 case ISD::SMIN: Pred = ISD::SETLT; break;
3888 case ISD::UMAX: Pred = ISD::SETUGT; break;
3889 case ISD::UMIN: Pred = ISD::SETULT; break;
3890 }
3891 Tmp1 = Node->getOperand(0);
3892 Tmp2 = Node->getOperand(1);
3893 Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp1, Tmp2, Pred);
3894 Results.push_back(Tmp1);
3895 break;
3896 }
3897 case ISD::FMINNUM:
3898 case ISD::FMAXNUM: {
3899 if (SDValue Expanded = TLI.expandFMINNUM_FMAXNUM(Node, DAG))
3900 Results.push_back(Expanded);
3901 break;
3902 }
3903 case ISD::FMINIMUM:
3904 case ISD::FMAXIMUM: {
3905 if (SDValue Expanded = TLI.expandFMINIMUM_FMAXIMUM(Node, DAG))
3906 Results.push_back(Expanded);
3907 break;
3908 }
3909 case ISD::FMINIMUMNUM:
3910 case ISD::FMAXIMUMNUM: {
3911 Results.push_back(TLI.expandFMINIMUMNUM_FMAXIMUMNUM(Node, DAG));
3912 break;
3913 }
3914 case ISD::FSIN:
3915 case ISD::FCOS: {
3916 EVT VT = Node->getValueType(0);
3917 // Turn fsin / fcos into ISD::FSINCOS node if there are a pair of fsin /
3918 // fcos which share the same operand and both are used.
3919 if ((TLI.isOperationLegal(ISD::FSINCOS, VT) ||
3920 isSinCosLibcallAvailable(Node, DAG.getLibcalls())) &&
3921 useSinCos(Node)) {
3922 SDVTList VTs = DAG.getVTList(VT, VT);
3923 Tmp1 = DAG.getNode(ISD::FSINCOS, dl, VTs, Node->getOperand(0));
3924 if (Node->getOpcode() == ISD::FCOS)
3925 Tmp1 = Tmp1.getValue(1);
3926 Results.push_back(Tmp1);
3927 }
3928 break;
3929 }
3930 case ISD::FLDEXP:
3931 case ISD::STRICT_FLDEXP: {
3932 EVT VT = Node->getValueType(0);
3933 RTLIB::Libcall LC = RTLIB::getLDEXP(VT);
3934 // Use the LibCall instead, it is very likely faster
3935 // FIXME: Use separate LibCall action.
3936 if (DAG.getLibcalls().getLibcallImpl(LC) != RTLIB::Unsupported)
3937 break;
3938
3939 if (SDValue Expanded = expandLdexp(Node)) {
3940 Results.push_back(Expanded);
3941 if (Node->getOpcode() == ISD::STRICT_FLDEXP)
3942 Results.push_back(Expanded.getValue(1));
3943 }
3944
3945 break;
3946 }
3947 case ISD::FFREXP: {
3948 RTLIB::Libcall LC = RTLIB::getFREXP(Node->getValueType(0));
3949 // Use the LibCall instead, it is very likely faster
3950 // FIXME: Use separate LibCall action.
3951 if (DAG.getLibcalls().getLibcallImpl(LC) != RTLIB::Unsupported)
3952 break;
3953
3954 if (SDValue Expanded = expandFrexp(Node)) {
3955 Results.push_back(Expanded);
3956 Results.push_back(Expanded.getValue(1));
3957 }
3958 break;
3959 }
3960 case ISD::FMODF: {
3961 RTLIB::Libcall LC = RTLIB::getMODF(Node->getValueType(0));
3962 // Use the LibCall instead, it is very likely faster
3963 // FIXME: Use separate LibCall action.
3964 if (DAG.getLibcalls().getLibcallImpl(LC) != RTLIB::Unsupported)
3965 break;
3966
3967 TLI.expandMODF(Node, DAG, Results);
3968 break;
3969 }
3970 case ISD::FSINCOS: {
3971 if (isSinCosLibcallAvailable(Node, DAG.getLibcalls()))
3972 break;
3973 EVT VT = Node->getValueType(0);
3974 SDValue Op = Node->getOperand(0);
3975 SDNodeFlags Flags = Node->getFlags();
3976 Tmp1 = DAG.getNode(ISD::FSIN, dl, VT, Op, Flags);
3977 Tmp2 = DAG.getNode(ISD::FCOS, dl, VT, Op, Flags);
3978 Results.append({Tmp1, Tmp2});
3979 break;
3980 }
3981 case ISD::FMAD:
3982 llvm_unreachable("Illegal fmad should never be formed");
3983
3984 case ISD::FP16_TO_FP:
3985 if (Node->getValueType(0) != MVT::f32) {
3986 // We can extend to types bigger than f32 in two steps without changing
3987 // the result. Since "f16 -> f32" is much more commonly available, give
3988 // CodeGen the option of emitting that before resorting to a libcall.
3989 SDValue Res =
3990 DAG.getNode(ISD::FP16_TO_FP, dl, MVT::f32, Node->getOperand(0));
3991 Results.push_back(
3992 DAG.getNode(ISD::FP_EXTEND, dl, Node->getValueType(0), Res));
3993 }
3994 break;
3997 if (Node->getValueType(0) != MVT::f32) {
3998 // We can extend to types bigger than f32 in two steps without changing
3999 // the result. Since "f16 -> f32" is much more commonly available, give
4000 // CodeGen the option of emitting that before resorting to a libcall.
4001 SDValue Res = DAG.getNode(Node->getOpcode(), dl, {MVT::f32, MVT::Other},
4002 {Node->getOperand(0), Node->getOperand(1)});
4003 Res = DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
4004 {Node->getValueType(0), MVT::Other},
4005 {Res.getValue(1), Res});
4006 Results.push_back(Res);
4007 Results.push_back(Res.getValue(1));
4008 }
4009 break;
4010 case ISD::FP_TO_FP16:
4011 LLVM_DEBUG(dbgs() << "Legalizing FP_TO_FP16\n");
4012 if (Node->getFlags().hasApproximateFuncs() && !TLI.useSoftFloat()) {
4013 SDValue Op = Node->getOperand(0);
4014 MVT SVT = Op.getSimpleValueType();
4015 if ((SVT == MVT::f64 || SVT == MVT::f80) &&
4017 // Under fastmath, we can expand this node into a fround followed by
4018 // a float-half conversion.
4019 SDValue FloatVal =
4020 DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Op,
4021 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
4022 Results.push_back(
4023 DAG.getNode(ISD::FP_TO_FP16, dl, Node->getValueType(0), FloatVal));
4024 }
4025 }
4026 break;
4027 case ISD::ConstantFP: {
4028 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
4029 EVT VT = Node->getValueType(0);
4030 TargetLowering::FPImmAction Action =
4032 switch (Action) {
4033 case TargetLowering::FPImmAction::Legal:
4034 break;
4035 case TargetLowering::FPImmAction::Bitcast: {
4036 EVT IntVT = VT.changeTypeToInteger();
4037 assert(TLI.isTypeLegal(IntVT) &&
4038 "integer type for FP immediate bits must be legal");
4039 // The constant is opaque so the bitcast is not folded back.
4040 SDValue Bits =
4041 DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(), dl, IntVT,
4042 /*isTarget=*/false, /*isOpaque=*/true);
4043 Results.push_back(DAG.getBitcast(VT, Bits));
4044 break;
4045 }
4046 case TargetLowering::FPImmAction::ConstantPool:
4047 Results.push_back(ExpandConstantFP(CFP));
4048 break;
4049 }
4050
4051 break;
4052 }
4053 case ISD::Constant: {
4054 ConstantSDNode *CP = cast<ConstantSDNode>(Node);
4055 Results.push_back(ExpandConstant(CP));
4056 break;
4057 }
4058 case ISD::FSUB: {
4059 EVT VT = Node->getValueType(0);
4062 const SDNodeFlags Flags = Node->getFlags();
4063 Tmp1 = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(1));
4064 Tmp1 = DAG.getNode(ISD::FADD, dl, VT, Node->getOperand(0), Tmp1, Flags);
4065 Results.push_back(Tmp1);
4066 }
4067 break;
4068 }
4069 case ISD::SUB: {
4070 EVT VT = Node->getValueType(0);
4073 "Don't know how to expand this subtraction!");
4074 Tmp1 = DAG.getNOT(dl, Node->getOperand(1), VT);
4075 Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp1, DAG.getConstant(1, dl, VT));
4076 Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1));
4077 break;
4078 }
4079 case ISD::UREM:
4080 case ISD::SREM:
4081 if (TLI.expandREM(Node, Tmp1, DAG))
4082 Results.push_back(Tmp1);
4083 break;
4084 case ISD::UDIV:
4085 case ISD::SDIV: {
4086 bool isSigned = Node->getOpcode() == ISD::SDIV;
4087 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
4088 EVT VT = Node->getValueType(0);
4089 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) {
4090 SDVTList VTs = DAG.getVTList(VT, VT);
4091 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0),
4092 Node->getOperand(1));
4093 Results.push_back(Tmp1);
4094 }
4095 break;
4096 }
4097 case ISD::MULHU:
4098 case ISD::MULHS: {
4099 unsigned ExpandOpcode =
4100 Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI : ISD::SMUL_LOHI;
4101 EVT VT = Node->getValueType(0);
4102 SDVTList VTs = DAG.getVTList(VT, VT);
4103
4104 Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0),
4105 Node->getOperand(1));
4106 Results.push_back(Tmp1.getValue(1));
4107 break;
4108 }
4109 case ISD::UMUL_LOHI:
4110 case ISD::SMUL_LOHI: {
4111 SDValue LHS = Node->getOperand(0);
4112 SDValue RHS = Node->getOperand(1);
4113 EVT VT = LHS.getValueType();
4114 bool IsSigned = Node->getOpcode() == ISD::SMUL_LOHI;
4115 unsigned MULHOpcode = IsSigned ? ISD::MULHS : ISD::MULHU;
4116
4117 if (TLI.isOperationLegalOrCustom(MULHOpcode, VT)) {
4118 Results.push_back(DAG.getNode(ISD::MUL, dl, VT, LHS, RHS));
4119 Results.push_back(DAG.getNode(MULHOpcode, dl, VT, LHS, RHS));
4120 break;
4121 }
4122
4124 EVT HalfType = VT.getHalfSizedIntegerVT(*DAG.getContext());
4125 if (TLI.isTypeLegal(HalfType) &&
4126 TLI.expandMUL_LOHI(Node->getOpcode(), VT, dl, LHS, RHS, Halves,
4127 HalfType, DAG,
4128 TargetLowering::MulExpansionKind::Always)) {
4129 for (unsigned i = 0; i < 2; ++i) {
4130 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Halves[2 * i]);
4131 SDValue Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Halves[2 * i + 1]);
4132 SDValue Shift =
4133 DAG.getShiftAmountConstant(HalfType.getScalarSizeInBits(), VT, dl);
4134 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
4135 Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi));
4136 }
4137 break;
4138 }
4139
4140 SDValue Lo, Hi;
4141 TLI.forceExpandWideMUL(DAG, dl, IsSigned, LHS, RHS, Lo, Hi);
4142 Results.push_back(Lo);
4143 Results.push_back(Hi);
4144 break;
4145 }
4146 case ISD::MUL: {
4147 EVT VT = Node->getValueType(0);
4148 SDVTList VTs = DAG.getVTList(VT, VT);
4149 // See if multiply or divide can be lowered using two-result operations.
4150 // We just need the low half of the multiply; try both the signed
4151 // and unsigned forms. If the target supports both SMUL_LOHI and
4152 // UMUL_LOHI, form a preference by checking which forms of plain
4153 // MULH it supports.
4154 bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
4155 bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
4156 bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
4157 bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
4158 unsigned OpToUse = 0;
4159 if (HasSMUL_LOHI && !HasMULHS) {
4160 OpToUse = ISD::SMUL_LOHI;
4161 } else if (HasUMUL_LOHI && !HasMULHU) {
4162 OpToUse = ISD::UMUL_LOHI;
4163 } else if (HasSMUL_LOHI) {
4164 OpToUse = ISD::SMUL_LOHI;
4165 } else if (HasUMUL_LOHI) {
4166 OpToUse = ISD::UMUL_LOHI;
4167 }
4168 if (OpToUse) {
4169 Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0),
4170 Node->getOperand(1)));
4171 break;
4172 }
4173
4174 SDValue Lo, Hi;
4175 EVT HalfType = VT.getHalfSizedIntegerVT(*DAG.getContext());
4180 TLI.expandMUL(Node, Lo, Hi, HalfType, DAG,
4181 TargetLowering::MulExpansionKind::OnlyLegalOrCustom)) {
4182 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
4183 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Hi);
4184 SDValue Shift =
4185 DAG.getShiftAmountConstant(HalfType.getSizeInBits(), VT, dl);
4186 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
4187 Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi));
4188 }
4189 break;
4190 }
4191 case ISD::FSHL:
4192 case ISD::FSHR:
4193 if (SDValue Expanded = TLI.expandFunnelShift(Node, DAG))
4194 Results.push_back(Expanded);
4195 break;
4196 case ISD::ROTL:
4197 case ISD::ROTR:
4198 if (SDValue Expanded = TLI.expandROT(Node, true /*AllowVectorOps*/, DAG))
4199 Results.push_back(Expanded);
4200 break;
4201 case ISD::CLMUL:
4202 case ISD::CLMULR:
4203 case ISD::CLMULH:
4204 if (SDValue Expanded = TLI.expandCLMUL(Node, DAG))
4205 Results.push_back(Expanded);
4206 break;
4207 case ISD::PEXT:
4208 Results.push_back(TLI.expandPEXT(Node, DAG));
4209 break;
4210 case ISD::PDEP:
4211 Results.push_back(TLI.expandPDEP(Node, DAG));
4212 break;
4213 case ISD::SADDSAT:
4214 case ISD::UADDSAT:
4215 case ISD::SSUBSAT:
4216 case ISD::USUBSAT:
4217 Results.push_back(TLI.expandAddSubSat(Node, DAG));
4218 break;
4219 case ISD::SCMP:
4220 case ISD::UCMP:
4221 Results.push_back(TLI.expandCMP(Node, DAG));
4222 break;
4223 case ISD::SSHLSAT:
4224 case ISD::USHLSAT:
4225 Results.push_back(TLI.expandShlSat(Node, DAG));
4226 break;
4227 case ISD::SMULFIX:
4228 case ISD::SMULFIXSAT:
4229 case ISD::UMULFIX:
4230 case ISD::UMULFIXSAT:
4231 Results.push_back(TLI.expandFixedPointMul(Node, DAG));
4232 break;
4233 case ISD::SDIVFIX:
4234 case ISD::SDIVFIXSAT:
4235 case ISD::UDIVFIX:
4236 case ISD::UDIVFIXSAT:
4237 if (SDValue V = TLI.expandFixedPointDiv(Node->getOpcode(), SDLoc(Node),
4238 Node->getOperand(0),
4239 Node->getOperand(1),
4240 Node->getConstantOperandVal(2),
4241 DAG)) {
4242 Results.push_back(V);
4243 break;
4244 }
4245 // FIXME: We might want to retry here with a wider type if we fail, if that
4246 // type is legal.
4247 // FIXME: Technically, so long as we only have sdivfixes where BW+Scale is
4248 // <= 128 (which is the case for all of the default Embedded-C types),
4249 // we will only get here with types and scales that we could always expand
4250 // if we were allowed to generate libcalls to division functions of illegal
4251 // type. But we cannot do that.
4252 llvm_unreachable("Cannot expand DIVFIX!");
4253 case ISD::UADDO_CARRY:
4254 case ISD::USUBO_CARRY: {
4255 SDValue LHS = Node->getOperand(0);
4256 SDValue RHS = Node->getOperand(1);
4257 SDValue Carry = Node->getOperand(2);
4258
4259 bool IsAdd = Node->getOpcode() == ISD::UADDO_CARRY;
4260
4261 // Initial add of the 2 operands.
4262 unsigned Op = IsAdd ? ISD::ADD : ISD::SUB;
4263 EVT VT = LHS.getValueType();
4264 SDValue Sum = DAG.getNode(Op, dl, VT, LHS, RHS);
4265
4266 // Initial check for overflow.
4267 EVT CarryType = Node->getValueType(1);
4268 EVT SetCCType = getSetCCResultType(Node->getValueType(0));
4270 SDValue Overflow = DAG.getSetCC(dl, SetCCType, Sum, LHS, CC);
4271
4272 // Add of the sum and the carry.
4273 SDValue One = DAG.getConstant(1, dl, VT);
4274 SDValue CarryExt =
4275 DAG.getNode(ISD::AND, dl, VT, DAG.getZExtOrTrunc(Carry, dl, VT), One);
4276 SDValue Sum2 = DAG.getNode(Op, dl, VT, Sum, CarryExt);
4277
4278 // Second check for overflow. If we are adding, we can only overflow if the
4279 // initial sum is all 1s ang the carry is set, resulting in a new sum of 0.
4280 // If we are subtracting, we can only overflow if the initial sum is 0 and
4281 // the carry is set, resulting in a new sum of all 1s.
4282 SDValue Zero = DAG.getConstant(0, dl, VT);
4283 SDValue Overflow2 =
4284 IsAdd ? DAG.getSetCC(dl, SetCCType, Sum2, Zero, ISD::SETEQ)
4285 : DAG.getSetCC(dl, SetCCType, Sum, Zero, ISD::SETEQ);
4286 Overflow2 = DAG.getNode(ISD::AND, dl, SetCCType, Overflow2,
4287 DAG.getZExtOrTrunc(Carry, dl, SetCCType));
4288
4289 SDValue ResultCarry =
4290 DAG.getNode(ISD::OR, dl, SetCCType, Overflow, Overflow2);
4291
4292 Results.push_back(Sum2);
4293 Results.push_back(DAG.getBoolExtOrTrunc(ResultCarry, dl, CarryType, VT));
4294 break;
4295 }
4296 case ISD::SADDO:
4297 case ISD::SSUBO: {
4298 SDValue Result, Overflow;
4299 TLI.expandSADDSUBO(Node, Result, Overflow, DAG);
4300 Results.push_back(Result);
4301 Results.push_back(Overflow);
4302 break;
4303 }
4304 case ISD::UADDO:
4305 case ISD::USUBO: {
4306 SDValue Result, Overflow;
4307 TLI.expandUADDSUBO(Node, Result, Overflow, DAG);
4308 Results.push_back(Result);
4309 Results.push_back(Overflow);
4310 break;
4311 }
4312 case ISD::UMULO:
4313 case ISD::SMULO: {
4314 SDValue Result, Overflow;
4315 if (TLI.expandMULO(Node, Result, Overflow, DAG)) {
4316 Results.push_back(Result);
4317 Results.push_back(Overflow);
4318 }
4319 break;
4320 }
4321 case ISD::BUILD_PAIR: {
4322 EVT PairTy = Node->getValueType(0);
4323 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0));
4324 Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1));
4325 Tmp2 = DAG.getNode(
4326 ISD::SHL, dl, PairTy, Tmp2,
4327 DAG.getShiftAmountConstant(PairTy.getSizeInBits() / 2, PairTy, dl));
4328 Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2));
4329 break;
4330 }
4331 case ISD::SELECT:
4332 Tmp1 = Node->getOperand(0);
4333 Tmp2 = Node->getOperand(1);
4334 Tmp3 = Node->getOperand(2);
4335 if (Tmp1.getOpcode() == ISD::SETCC) {
4336 Tmp1 =
4337 DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1), Tmp2,
4338 Tmp3, Tmp1.getOperandCondCode(2), Node->getFlags());
4339 } else {
4340 Tmp1 =
4341 DAG.getSelectCC(dl, Tmp1, DAG.getConstant(0, dl, Tmp1.getValueType()),
4342 Tmp2, Tmp3, ISD::SETNE, Node->getFlags());
4343 }
4344 Results.push_back(Tmp1);
4345 break;
4346 case ISD::BR_JT: {
4347 SDValue Chain = Node->getOperand(0);
4348 SDValue Table = Node->getOperand(1);
4349 SDValue Index = Node->getOperand(2);
4350 int JTI = cast<JumpTableSDNode>(Table.getNode())->getIndex();
4351
4352 const DataLayout &TD = DAG.getDataLayout();
4353 EVT PTy = TLI.getPointerTy(TD);
4354
4355 unsigned EntrySize =
4357
4358 // For power-of-two jumptable entry sizes convert multiplication to a shift.
4359 // This transformation needs to be done here since otherwise the MIPS
4360 // backend will end up emitting a three instruction multiply sequence
4361 // instead of a single shift and MSP430 will call a runtime function.
4362 if (llvm::isPowerOf2_32(EntrySize))
4363 Index = DAG.getNode(
4364 ISD::SHL, dl, Index.getValueType(), Index,
4365 DAG.getConstant(llvm::Log2_32(EntrySize), dl, Index.getValueType()));
4366 else
4367 Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(), Index,
4368 DAG.getConstant(EntrySize, dl, Index.getValueType()));
4369 SDValue Addr = DAG.getMemBasePlusOffset(Table, Index, dl);
4370
4371 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
4372 SDValue LD = DAG.getExtLoad(
4373 ISD::SEXTLOAD, dl, PTy, Chain, Addr,
4375 Addr = LD;
4376 if (TLI.isJumpTableRelative()) {
4377 // For PIC, the sequence is:
4378 // BRIND(RelocBase + load(Jumptable + index))
4379 // RelocBase can be JumpTable, GOT or some sort of global base.
4381 Addr, dl);
4382 }
4383
4384 Tmp1 = TLI.expandIndirectJTBranch(dl, LD.getValue(1), Addr, JTI, DAG);
4385 Results.push_back(Tmp1);
4386 break;
4387 }
4388 case ISD::BRCOND:
4389 // Expand brcond's setcc into its constituent parts and create a BR_CC
4390 // Node.
4391 Tmp1 = Node->getOperand(0);
4392 Tmp2 = Node->getOperand(1);
4393 if (Tmp2.getOpcode() == ISD::SETCC &&
4395 Tmp2.getOperand(0).getValueType())) {
4396 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1, Tmp2.getOperand(2),
4397 Tmp2.getOperand(0), Tmp2.getOperand(1),
4398 Node->getOperand(2));
4399 } else {
4400 // We test only the i1 bit. Skip the AND if UNDEF or another AND.
4401 if (Tmp2.isUndef() ||
4402 (Tmp2.getOpcode() == ISD::AND && isOneConstant(Tmp2.getOperand(1))))
4403 Tmp3 = Tmp2;
4404 else
4405 Tmp3 = DAG.getNode(ISD::AND, dl, Tmp2.getValueType(), Tmp2,
4406 DAG.getConstant(1, dl, Tmp2.getValueType()));
4407 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
4408 DAG.getCondCode(ISD::SETNE), Tmp3,
4409 DAG.getConstant(0, dl, Tmp3.getValueType()),
4410 Node->getOperand(2));
4411 }
4412 Results.push_back(Tmp1);
4413 break;
4414 case ISD::SETCC:
4415 case ISD::STRICT_FSETCC:
4416 case ISD::STRICT_FSETCCS: {
4417 bool IsStrict = Node->getOpcode() == ISD::STRICT_FSETCC ||
4418 Node->getOpcode() == ISD::STRICT_FSETCCS;
4419 bool IsSignaling = Node->getOpcode() == ISD::STRICT_FSETCCS;
4420 SDValue Chain = IsStrict ? Node->getOperand(0) : SDValue();
4421 unsigned Offset = IsStrict ? 1 : 0;
4422 Tmp1 = Node->getOperand(0 + Offset);
4423 Tmp2 = Node->getOperand(1 + Offset);
4424 Tmp3 = Node->getOperand(2 + Offset);
4425 bool Legalized =
4426 TLI.LegalizeSetCCCondCode(DAG, Node->getValueType(0), Tmp1, Tmp2, Tmp3,
4427 NeedInvert, dl, Chain, IsSignaling);
4428
4429 if (Legalized) {
4430 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
4431 // condition code, create a new SETCC node.
4432 if (Tmp3.getNode()) {
4433 if (IsStrict) {
4434 Tmp1 = DAG.getNode(Node->getOpcode(), dl, Node->getVTList(),
4435 {Chain, Tmp1, Tmp2, Tmp3}, Node->getFlags());
4436 Chain = Tmp1.getValue(1);
4437 } else {
4438 Tmp1 = DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0), Tmp1,
4439 Tmp2, Tmp3, Node->getFlags());
4440 }
4441 }
4442
4443 // If we expanded the SETCC by inverting the condition code, then wrap
4444 // the existing SETCC in a NOT to restore the intended condition.
4445 if (NeedInvert) {
4446 Tmp1 = DAG.getLogicalNOT(dl, Tmp1, Tmp1->getValueType(0));
4447 }
4448
4449 Results.push_back(Tmp1);
4450 if (IsStrict)
4451 Results.push_back(Chain);
4452
4453 break;
4454 }
4455
4456 // FIXME: It seems Legalized is false iff CCCode is Legal. I don't
4457 // understand if this code is useful for strict nodes.
4458 assert(!IsStrict && "Don't know how to expand for strict nodes.");
4459
4460 // Otherwise, SETCC for the given comparison type must be completely
4461 // illegal; expand it into a SELECT_CC.
4462 EVT VT = Node->getValueType(0);
4463 EVT Tmp1VT = Tmp1.getValueType();
4464 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
4465 DAG.getBoolConstant(true, dl, VT, Tmp1VT),
4466 DAG.getBoolConstant(false, dl, VT, Tmp1VT), Tmp3,
4467 Node->getFlags());
4468 Results.push_back(Tmp1);
4469 break;
4470 }
4471 case ISD::SELECT_CC: {
4472 // TODO: need to add STRICT_SELECT_CC and STRICT_SELECT_CCS
4473 Tmp1 = Node->getOperand(0); // LHS
4474 Tmp2 = Node->getOperand(1); // RHS
4475 Tmp3 = Node->getOperand(2); // True
4476 Tmp4 = Node->getOperand(3); // False
4477 EVT VT = Node->getValueType(0);
4478 SDValue Chain;
4479 SDValue CC = Node->getOperand(4);
4480 ISD::CondCode CCOp = cast<CondCodeSDNode>(CC)->get();
4481
4483 // If the condition code is legal, then we need to expand this
4484 // node using SETCC and SELECT.
4485 EVT CmpVT = Tmp1.getValueType();
4487 "Cannot expand ISD::SELECT_CC when ISD::SELECT also needs to be "
4488 "expanded.");
4489 EVT CCVT = getSetCCResultType(CmpVT);
4490 SDValue Cond = DAG.getNode(ISD::SETCC, dl, CCVT, Tmp1, Tmp2, CC, Node->getFlags());
4491 Results.push_back(
4492 DAG.getSelect(dl, VT, Cond, Tmp3, Tmp4, Node->getFlags()));
4493 break;
4494 }
4495
4496 // SELECT_CC is legal, so the condition code must not be.
4497 bool Legalized = false;
4498 // Try to legalize by inverting the condition. This is for targets that
4499 // might support an ordered version of a condition, but not the unordered
4500 // version (or vice versa).
4501 ISD::CondCode InvCC = ISD::getSetCCInverse(CCOp, Tmp1.getValueType());
4502 if (TLI.isCondCodeLegalOrCustom(InvCC, Tmp1.getSimpleValueType())) {
4503 // Use the new condition code and swap true and false
4504 Legalized = true;
4505 Tmp1 =
4506 DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp4, Tmp3, InvCC, Node->getFlags());
4507 } else {
4508 // If The inverse is not legal, then try to swap the arguments using
4509 // the inverse condition code.
4511 if (TLI.isCondCodeLegalOrCustom(SwapInvCC, Tmp1.getSimpleValueType())) {
4512 // The swapped inverse condition is legal, so swap true and false,
4513 // lhs and rhs.
4514 Legalized = true;
4515 Tmp1 = DAG.getSelectCC(dl, Tmp2, Tmp1, Tmp4, Tmp3, SwapInvCC,
4516 Node->getFlags());
4517 }
4518 }
4519
4520 if (!Legalized) {
4521 Legalized = TLI.LegalizeSetCCCondCode(
4522 DAG, getSetCCResultType(Tmp1.getValueType()), Tmp1, Tmp2, CC,
4523 NeedInvert, dl, Chain);
4524
4525 assert(Legalized && "Can't legalize SELECT_CC with legal condition!");
4526
4527 // If we expanded the SETCC by inverting the condition code, then swap
4528 // the True/False operands to match.
4529 if (NeedInvert)
4530 std::swap(Tmp3, Tmp4);
4531
4532 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
4533 // condition code, create a new SELECT_CC node.
4534 if (CC.getNode()) {
4535 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1,
4536 Tmp2, Tmp3, Tmp4, CC, Node->getFlags());
4537 } else {
4538 Tmp2 = DAG.getConstant(0, dl, Tmp1.getValueType());
4539 CC = DAG.getCondCode(ISD::SETNE);
4540 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1,
4541 Tmp2, Tmp3, Tmp4, CC, Node->getFlags());
4542 }
4543 }
4544 Results.push_back(Tmp1);
4545 break;
4546 }
4547 case ISD::BR_CC: {
4548 // TODO: need to add STRICT_BR_CC and STRICT_BR_CCS
4549 SDValue Chain;
4550 Tmp1 = Node->getOperand(0); // Chain
4551 Tmp2 = Node->getOperand(2); // LHS
4552 Tmp3 = Node->getOperand(3); // RHS
4553 Tmp4 = Node->getOperand(1); // CC
4554
4555 bool Legalized =
4556 TLI.LegalizeSetCCCondCode(DAG, getSetCCResultType(Tmp2.getValueType()),
4557 Tmp2, Tmp3, Tmp4, NeedInvert, dl, Chain);
4558 (void)Legalized;
4559 assert(Legalized && "Can't legalize BR_CC with legal condition!");
4560
4561 // If we expanded the SETCC by swapping LHS and RHS, create a new BR_CC
4562 // node.
4563 if (Tmp4.getNode()) {
4564 assert(!NeedInvert && "Don't know how to invert BR_CC!");
4565
4566 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1,
4567 Tmp4, Tmp2, Tmp3, Node->getOperand(4));
4568 } else {
4569 Tmp3 = DAG.getConstant(0, dl, Tmp2.getValueType());
4570 Tmp4 = DAG.getCondCode(NeedInvert ? ISD::SETEQ : ISD::SETNE);
4571 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4,
4572 Tmp2, Tmp3, Node->getOperand(4));
4573 }
4574 Results.push_back(Tmp1);
4575 break;
4576 }
4577 case ISD::BUILD_VECTOR:
4578 Results.push_back(ExpandBUILD_VECTOR(Node));
4579 break;
4580 case ISD::SPLAT_VECTOR:
4581 Results.push_back(ExpandSPLAT_VECTOR(Node));
4582 break;
4583 case ISD::SRA:
4584 case ISD::SRL:
4585 case ISD::SHL: {
4586 // Scalarize vector SRA/SRL/SHL.
4587 EVT VT = Node->getValueType(0);
4588 assert(VT.isVector() && "Unable to legalize non-vector shift");
4589 assert(TLI.isTypeLegal(VT.getScalarType())&& "Element type must be legal");
4590 unsigned NumElem = VT.getVectorNumElements();
4591
4593 for (unsigned Idx = 0; Idx < NumElem; Idx++) {
4594 SDValue Ex =
4596 Node->getOperand(0), DAG.getVectorIdxConstant(Idx, dl));
4597 SDValue Sh =
4599 Node->getOperand(1), DAG.getVectorIdxConstant(Idx, dl));
4600 Scalars.push_back(DAG.getNode(Node->getOpcode(), dl,
4601 VT.getScalarType(), Ex, Sh));
4602 }
4603
4604 SDValue Result = DAG.getBuildVector(Node->getValueType(0), dl, Scalars);
4605 Results.push_back(Result);
4606 break;
4607 }
4610 case ISD::VECREDUCE_ADD:
4611 case ISD::VECREDUCE_MUL:
4612 case ISD::VECREDUCE_AND:
4613 case ISD::VECREDUCE_OR:
4614 case ISD::VECREDUCE_XOR:
4625 Results.push_back(TLI.expandVecReduce(Node, DAG));
4626 break;
4627 case ISD::VP_CTTZ_ELTS:
4628 case ISD::VP_CTTZ_ELTS_ZERO_POISON:
4629 Results.push_back(TLI.expandVPCTTZElements(Node, DAG));
4630 break;
4631 case ISD::CLEAR_CACHE:
4632 // The default expansion of llvm.clear_cache is simply a no-op for those
4633 // targets where it is not needed.
4634 Results.push_back(Node->getOperand(0));
4635 break;
4636 case ISD::LRINT:
4637 case ISD::LLRINT: {
4638 SDValue Arg = Node->getOperand(0);
4639 EVT ArgVT = Arg.getValueType();
4640 EVT ResVT = Node->getValueType(0);
4641 SDLoc DL(Node);
4642 SDValue RoundNode = DAG.getNode(ISD::FRINT, DL, ArgVT, Arg);
4643 SDValue ConvertNode = DAG.getNode(ISD::FP_TO_SINT, DL, ResVT, RoundNode);
4644 // Non-deterministic results are equivalent to freeze poison.
4645 Results.push_back(DAG.getFreeze(ConvertNode));
4646 break;
4647 }
4648 case ISD::ADDRSPACECAST:
4649 Results.push_back(DAG.UnrollVectorOp(Node));
4650 break;
4652 case ISD::GlobalAddress:
4655 case ISD::ConstantPool:
4656 case ISD::JumpTable:
4660 // FIXME: Custom lowering for these operations shouldn't return null!
4661 // Return true so that we don't call ConvertNodeToLibcall which also won't
4662 // do anything.
4663 return true;
4664 }
4665
4666 if (!TLI.isStrictFPEnabled() && Results.empty() && Node->isStrictFPOpcode()) {
4667 // FIXME: We were asked to expand a strict floating-point operation,
4668 // but there is currently no expansion implemented that would preserve
4669 // the "strict" properties. For now, we just fall back to the non-strict
4670 // version if that is legal on the target. The actual mutation of the
4671 // operation will happen in SelectionDAGISel::DoInstructionSelection.
4672 switch (Node->getOpcode()) {
4673 default:
4674 if (TLI.getStrictFPOperationAction(Node->getOpcode(),
4675 Node->getValueType(0))
4676 == TargetLowering::Legal)
4677 return true;
4678 break;
4679 case ISD::STRICT_FSUB: {
4681 ISD::STRICT_FSUB, Node->getValueType(0)) == TargetLowering::Legal)
4682 return true;
4684 ISD::STRICT_FADD, Node->getValueType(0)) != TargetLowering::Legal)
4685 break;
4686
4687 EVT VT = Node->getValueType(0);
4688 const SDNodeFlags Flags = Node->getFlags();
4689 SDValue Neg = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(2), Flags);
4690 SDValue Fadd = DAG.getNode(ISD::STRICT_FADD, dl, Node->getVTList(),
4691 {Node->getOperand(0), Node->getOperand(1), Neg},
4692 Flags);
4693
4694 Results.push_back(Fadd);
4695 Results.push_back(Fadd.getValue(1));
4696 break;
4697 }
4700 case ISD::STRICT_LRINT:
4701 case ISD::STRICT_LLRINT:
4702 case ISD::STRICT_LROUND:
4704 // These are registered by the operand type instead of the value
4705 // type. Reflect that here.
4706 if (TLI.getStrictFPOperationAction(Node->getOpcode(),
4707 Node->getOperand(1).getValueType())
4708 == TargetLowering::Legal)
4709 return true;
4710 break;
4711 }
4712 }
4713
4714 // Replace the original node with the legalized result.
4715 if (Results.empty()) {
4716 LLVM_DEBUG(dbgs() << "Cannot expand node\n");
4717 return false;
4718 }
4719
4720 LLVM_DEBUG(dbgs() << "Successfully expanded node\n");
4721 ReplaceNode(Node, Results.data());
4722 return true;
4723}
4724
4725/// Return if we can use the FAST_* variant of a math libcall for the node.
4726/// FIXME: This is just guessing, we probably should have unique specific sets
4727/// flags required per libcall.
4728static bool canUseFastMathLibcall(const SDNode *Node) {
4729 // FIXME: Probably should define fast to respect nan/inf and only be
4730 // approximate functions.
4731
4732 SDNodeFlags Flags = Node->getFlags();
4733 return Flags.hasApproximateFuncs() && Flags.hasNoNaNs() &&
4734 Flags.hasNoInfs() && Flags.hasNoSignedZeros();
4735}
4736
4737void SelectionDAGLegalize::ConvertNodeToLibcall(SDNode *Node) {
4738 LLVM_DEBUG(dbgs() << "Trying to convert node to libcall\n");
4740 SDLoc dl(Node);
4741 TargetLowering::MakeLibCallOptions CallOptions;
4742 CallOptions.IsPostTypeLegalization = true;
4743 // FIXME: Check flags on the node to see if we can use a finite call.
4744 unsigned Opc = Node->getOpcode();
4745 switch (Opc) {
4746 case ISD::ATOMIC_FENCE: {
4747 // If the target didn't lower this, lower it to '__sync_synchronize()' call
4748 // FIXME: handle "fence singlethread" more efficiently.
4749 std::pair<SDValue, SDValue> CallResult =
4750 TLI.makeLibCall(DAG, RTLIB::SYNC_SYNCHRONIZE, MVT::isVoid, {},
4751 CallOptions, dl, Node->getOperand(0));
4752 Results.push_back(CallResult.second);
4753 break;
4754 }
4755 // By default, atomic intrinsics are marked Legal and lowered. Targets
4756 // which don't support them directly, however, may want libcalls, in which
4757 // case they mark them Expand, and we get here.
4758 case ISD::ATOMIC_SWAP:
4770 case ISD::ATOMIC_CMP_SWAP: {
4771 MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
4772 AtomicOrdering Order = cast<AtomicSDNode>(Node)->getMergedOrdering();
4773 RTLIB::AtomicLibcall LC =
4774 RTLIB::selectAtomicLibcall(DAG.getLibcalls(), Opc, Order, VT);
4775 EVT RetVT = Node->getValueType(0);
4777 if (LC.IsOutline) {
4778 // If outline atomic available, prepare its arguments and expand.
4779 Ops.append(Node->op_begin() + 2, Node->op_end());
4780 Ops.push_back(Node->getOperand(1));
4781 } else {
4782 // Arguments for expansion to sync libcall
4783 Ops.append(Node->op_begin() + 1, Node->op_end());
4784 }
4785 std::pair<SDValue, SDValue> Tmp =
4786 TLI.makeLibCall(DAG, LC.Impl, RetVT, Ops, CallOptions, SDLoc(Node),
4787 Node->getOperand(0));
4788 Results.push_back(Tmp.first);
4789 Results.push_back(Tmp.second);
4790 break;
4791 }
4792 case ISD::TRAP: {
4793 // If this operation is not supported, lower it to 'abort()' call
4794 TargetLowering::ArgListTy Args;
4795 TargetLowering::CallLoweringInfo CLI(DAG);
4796 CLI.setDebugLoc(dl)
4797 .setChain(Node->getOperand(0))
4798 .setLibCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
4800 "abort", TLI.getPointerTy(DAG.getDataLayout())),
4801 std::move(Args));
4802 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
4803
4804 Results.push_back(CallResult.second);
4805 break;
4806 }
4807 case ISD::CLEAR_CACHE: {
4808 SDValue InputChain = Node->getOperand(0);
4809 SDValue StartVal = Node->getOperand(1);
4810 SDValue EndVal = Node->getOperand(2);
4811 std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(
4812 DAG, RTLIB::CLEAR_CACHE, MVT::isVoid, {StartVal, EndVal}, CallOptions,
4813 SDLoc(Node), InputChain);
4814 Results.push_back(Tmp.second);
4815 break;
4816 }
4817 case ISD::FMINNUM:
4819 ExpandFPLibCall(Node, RTLIB::getFMIN(Node->getSimpleValueType(0)), Results);
4820 break;
4821 // FIXME: We do not have libcalls for FMAXIMUM and FMINIMUM. So, we cannot use
4822 // libcall legalization for these nodes, but there is no default expasion for
4823 // these nodes either (see PR63267 for example).
4824 case ISD::FMAXNUM:
4826 ExpandFPLibCall(Node, RTLIB::getFMAX(Node->getSimpleValueType(0)), Results);
4827 break;
4828 case ISD::FMINIMUMNUM:
4829 ExpandFPLibCall(Node, RTLIB::getFMINIMUM_NUM(Node->getSimpleValueType(0)),
4830 Results);
4831 break;
4832 case ISD::FMAXIMUMNUM:
4833 ExpandFPLibCall(Node, RTLIB::getFMAXIMUM_NUM(Node->getSimpleValueType(0)),
4834 Results);
4835 break;
4836 case ISD::FSQRT:
4837 case ISD::STRICT_FSQRT: {
4838 // FIXME: Probably should define fast to respect nan/inf and only be
4839 // approximate functions.
4840 ExpandFastFPLibCall(Node, canUseFastMathLibcall(Node),
4841 {RTLIB::FAST_SQRT_F32, RTLIB::SQRT_F32},
4842 {RTLIB::FAST_SQRT_F64, RTLIB::SQRT_F64},
4843 {RTLIB::FAST_SQRT_F80, RTLIB::SQRT_F80},
4844 {RTLIB::FAST_SQRT_F128, RTLIB::SQRT_F128},
4845 {RTLIB::FAST_SQRT_PPCF128, RTLIB::SQRT_PPCF128},
4846 Results);
4847 break;
4848 }
4849 case ISD::FCBRT:
4850 ExpandFPLibCall(Node, RTLIB::getCBRT(Node->getSimpleValueType(0)), Results);
4851 break;
4852 case ISD::FSIN:
4853 case ISD::STRICT_FSIN:
4854 ExpandFPLibCall(Node, RTLIB::getSIN(Node->getSimpleValueType(0)), Results);
4855 break;
4856 case ISD::FCOS:
4857 case ISD::STRICT_FCOS:
4858 ExpandFPLibCall(Node, RTLIB::getCOS(Node->getSimpleValueType(0)), Results);
4859 break;
4860 case ISD::FTAN:
4861 case ISD::STRICT_FTAN:
4862 ExpandFPLibCall(Node, RTLIB::getTAN(Node->getSimpleValueType(0)), Results);
4863 break;
4864 case ISD::FASIN:
4865 case ISD::STRICT_FASIN:
4866 ExpandFPLibCall(Node, RTLIB::getASIN(Node->getSimpleValueType(0)), Results);
4867 break;
4868 case ISD::FACOS:
4869 case ISD::STRICT_FACOS:
4870 ExpandFPLibCall(Node, RTLIB::getACOS(Node->getSimpleValueType(0)), Results);
4871 break;
4872 case ISD::FATAN:
4873 case ISD::STRICT_FATAN:
4874 ExpandFPLibCall(Node, RTLIB::getATAN(Node->getSimpleValueType(0)), Results);
4875 break;
4876 case ISD::FATAN2:
4877 case ISD::STRICT_FATAN2:
4878 ExpandFPLibCall(Node, RTLIB::getATAN2(Node->getSimpleValueType(0)),
4879 Results);
4880 break;
4881 case ISD::FSINH:
4882 case ISD::STRICT_FSINH:
4883 ExpandFPLibCall(Node, RTLIB::getSINH(Node->getSimpleValueType(0)), Results);
4884 break;
4885 case ISD::FCOSH:
4886 case ISD::STRICT_FCOSH:
4887 ExpandFPLibCall(Node, RTLIB::getCOSH(Node->getSimpleValueType(0)), Results);
4888 break;
4889 case ISD::FTANH:
4890 case ISD::STRICT_FTANH:
4891 ExpandFPLibCall(Node, RTLIB::getTANH(Node->getSimpleValueType(0)), Results);
4892 break;
4893 case ISD::FSINCOS:
4894 case ISD::FSINCOSPI: {
4895 EVT VT = Node->getValueType(0);
4896
4897 if (Node->getOpcode() == ISD::FSINCOS) {
4898 RTLIB::Libcall SincosStret = RTLIB::getSINCOS_STRET(VT);
4899 if (SincosStret != RTLIB::UNKNOWN_LIBCALL) {
4900 if (SDValue Expanded = ExpandSincosStretLibCall(Node)) {
4901 Results.push_back(Expanded);
4902 Results.push_back(Expanded.getValue(1));
4903 break;
4904 }
4905 }
4906 }
4907
4908 RTLIB::Libcall LC = Node->getOpcode() == ISD::FSINCOS
4909 ? RTLIB::getSINCOS(VT)
4910 : RTLIB::getSINCOSPI(VT);
4911 bool Expanded = TLI.expandMultipleResultFPLibCall(DAG, LC, Node, Results);
4912 if (!Expanded) {
4913 DAG.getContext()->emitError(Twine("no libcall available for ") +
4914 Node->getOperationName(&DAG));
4915 SDValue Poison = DAG.getPOISON(VT);
4916 Results.push_back(Poison);
4917 Results.push_back(Poison);
4918 }
4919
4920 break;
4921 }
4922 case ISD::FLOG:
4923 case ISD::STRICT_FLOG:
4924 ExpandFPLibCall(Node, RTLIB::getLOG(Node->getSimpleValueType(0)), Results);
4925 break;
4926 case ISD::FLOG2:
4927 case ISD::STRICT_FLOG2:
4928 ExpandFPLibCall(Node, RTLIB::getLOG2(Node->getSimpleValueType(0)), Results);
4929 break;
4930 case ISD::FLOG10:
4931 case ISD::STRICT_FLOG10:
4932 ExpandFPLibCall(Node, RTLIB::getLOG10(Node->getSimpleValueType(0)),
4933 Results);
4934 break;
4935 case ISD::FEXP:
4936 case ISD::STRICT_FEXP:
4937 ExpandFPLibCall(Node, RTLIB::getEXP(Node->getSimpleValueType(0)), Results);
4938 break;
4939 case ISD::FEXP2:
4940 case ISD::STRICT_FEXP2:
4941 ExpandFPLibCall(Node, RTLIB::getEXP2(Node->getSimpleValueType(0)), Results);
4942 break;
4943 case ISD::FEXP10:
4944 ExpandFPLibCall(Node, RTLIB::getEXP10(Node->getSimpleValueType(0)),
4945 Results);
4946 break;
4947 case ISD::FTRUNC:
4948 case ISD::STRICT_FTRUNC:
4949 ExpandFPLibCall(Node, RTLIB::getTRUNC(Node->getSimpleValueType(0)),
4950 Results);
4951 break;
4952 case ISD::FFLOOR:
4953 case ISD::STRICT_FFLOOR:
4954 ExpandFPLibCall(Node, RTLIB::getFLOOR(Node->getSimpleValueType(0)),
4955 Results);
4956 break;
4957 case ISD::FCEIL:
4958 case ISD::STRICT_FCEIL:
4959 ExpandFPLibCall(Node, RTLIB::getCEIL(Node->getSimpleValueType(0)), Results);
4960 break;
4961 case ISD::FRINT:
4962 case ISD::STRICT_FRINT:
4963 ExpandFPLibCall(Node, RTLIB::getRINT(Node->getSimpleValueType(0)), Results);
4964 break;
4965 case ISD::FNEARBYINT:
4967 ExpandFPLibCall(Node, RTLIB::getNEARBYINT(Node->getSimpleValueType(0)),
4968 Results);
4969 break;
4970 case ISD::FROUND:
4971 case ISD::STRICT_FROUND:
4972 ExpandFPLibCall(Node, RTLIB::getROUND(Node->getSimpleValueType(0)),
4973 Results);
4974 break;
4975 case ISD::FROUNDEVEN:
4977 ExpandFPLibCall(Node, RTLIB::getROUNDEVEN(Node->getSimpleValueType(0)),
4978 Results);
4979 break;
4980 case ISD::FLDEXP:
4981 case ISD::STRICT_FLDEXP:
4982 ExpandFPLibCall(Node, RTLIB::getLDEXP(Node->getSimpleValueType(0)),
4983 Results);
4984 break;
4985 case ISD::FMODF:
4986 case ISD::FFREXP: {
4987 EVT VT = Node->getValueType(0);
4988 RTLIB::Libcall LC = Node->getOpcode() == ISD::FMODF ? RTLIB::getMODF(VT)
4989 : RTLIB::getFREXP(VT);
4990 bool Expanded = TLI.expandMultipleResultFPLibCall(DAG, LC, Node, Results,
4991 /*CallRetResNo=*/0);
4992 if (!Expanded) {
4993 DAG.getContext()->emitError(Twine("no libcall available for ") +
4994 Node->getOperationName(&DAG));
4995 for (unsigned I = 0, E = Node->getNumValues(); I != E; ++I)
4996 Results.push_back(DAG.getPOISON(Node->getValueType(I)));
4997 }
4998 break;
4999 }
5000 case ISD::FPOWI:
5001 case ISD::STRICT_FPOWI: {
5002 RTLIB::Libcall LC = RTLIB::getPOWI(Node->getSimpleValueType(0));
5003 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fpowi.");
5004 if (DAG.getLibcalls().getLibcallImpl(LC) == RTLIB::Unsupported) {
5005 // Some targets don't have a powi libcall; use pow instead.
5006 if (Node->isStrictFPOpcode()) {
5008 DAG.getNode(ISD::STRICT_SINT_TO_FP, SDLoc(Node),
5009 {Node->getValueType(0), Node->getValueType(1)},
5010 {Node->getOperand(0), Node->getOperand(2)});
5011 SDValue FPOW =
5012 DAG.getNode(ISD::STRICT_FPOW, SDLoc(Node),
5013 {Node->getValueType(0), Node->getValueType(1)},
5014 {Exponent.getValue(1), Node->getOperand(1), Exponent});
5015 Results.push_back(FPOW);
5016 Results.push_back(FPOW.getValue(1));
5017 } else {
5019 DAG.getNode(ISD::SINT_TO_FP, SDLoc(Node), Node->getValueType(0),
5020 Node->getOperand(1));
5021 Results.push_back(DAG.getNode(ISD::FPOW, SDLoc(Node),
5022 Node->getValueType(0),
5023 Node->getOperand(0), Exponent));
5024 }
5025 break;
5026 }
5027 unsigned Offset = Node->isStrictFPOpcode() ? 1 : 0;
5028 bool ExponentHasSizeOfInt =
5029 DAG.getLibInfo().getIntSize() ==
5030 Node->getOperand(1 + Offset).getValueType().getSizeInBits();
5031 if (!ExponentHasSizeOfInt) {
5032 // If the exponent does not match with sizeof(int) a libcall to
5033 // RTLIB::POWI would use the wrong type for the argument.
5034 DAG.getContext()->emitError("POWI exponent does not match sizeof(int)");
5035 Results.push_back(DAG.getPOISON(Node->getValueType(0)));
5036 break;
5037 }
5038 ExpandFPLibCall(Node, LC, Results);
5039 break;
5040 }
5041 case ISD::FPOW:
5042 case ISD::STRICT_FPOW:
5043 ExpandFPLibCall(Node, RTLIB::getPOW(Node->getSimpleValueType(0)), Results);
5044 break;
5045 case ISD::LROUND:
5046 case ISD::STRICT_LROUND:
5047 ExpandArgFPLibCall(Node, RTLIB::LROUND_F32,
5048 RTLIB::LROUND_F64, RTLIB::LROUND_F80,
5049 RTLIB::LROUND_F128,
5050 RTLIB::LROUND_PPCF128, Results);
5051 break;
5052 case ISD::LLROUND:
5054 ExpandArgFPLibCall(Node, RTLIB::LLROUND_F32,
5055 RTLIB::LLROUND_F64, RTLIB::LLROUND_F80,
5056 RTLIB::LLROUND_F128,
5057 RTLIB::LLROUND_PPCF128, Results);
5058 break;
5059 case ISD::LRINT:
5060 case ISD::STRICT_LRINT:
5061 ExpandArgFPLibCall(Node, RTLIB::LRINT_F32,
5062 RTLIB::LRINT_F64, RTLIB::LRINT_F80,
5063 RTLIB::LRINT_F128,
5064 RTLIB::LRINT_PPCF128, Results);
5065 break;
5066 case ISD::LLRINT:
5067 case ISD::STRICT_LLRINT:
5068 ExpandArgFPLibCall(Node, RTLIB::LLRINT_F32,
5069 RTLIB::LLRINT_F64, RTLIB::LLRINT_F80,
5070 RTLIB::LLRINT_F128,
5071 RTLIB::LLRINT_PPCF128, Results);
5072 break;
5073 case ISD::FDIV:
5074 case ISD::STRICT_FDIV: {
5075 ExpandFastFPLibCall(Node, canUseFastMathLibcall(Node),
5076 {RTLIB::FAST_DIV_F32, RTLIB::DIV_F32},
5077 {RTLIB::FAST_DIV_F64, RTLIB::DIV_F64},
5078 {RTLIB::FAST_DIV_F80, RTLIB::DIV_F80},
5079 {RTLIB::FAST_DIV_F128, RTLIB::DIV_F128},
5080 {RTLIB::FAST_DIV_PPCF128, RTLIB::DIV_PPCF128}, Results);
5081 break;
5082 }
5083 case ISD::FREM:
5084 case ISD::STRICT_FREM:
5085 ExpandFPLibCall(Node, RTLIB::getREM(Node->getSimpleValueType(0)), Results);
5086 break;
5087 case ISD::FMA:
5088 case ISD::STRICT_FMA:
5089 ExpandFPLibCall(Node, RTLIB::getFMA(Node->getSimpleValueType(0)), Results);
5090 break;
5091 case ISD::FADD:
5092 case ISD::STRICT_FADD: {
5093 ExpandFastFPLibCall(Node, canUseFastMathLibcall(Node),
5094 {RTLIB::FAST_ADD_F32, RTLIB::ADD_F32},
5095 {RTLIB::FAST_ADD_F64, RTLIB::ADD_F64},
5096 {RTLIB::FAST_ADD_F80, RTLIB::ADD_F80},
5097 {RTLIB::FAST_ADD_F128, RTLIB::ADD_F128},
5098 {RTLIB::FAST_ADD_PPCF128, RTLIB::ADD_PPCF128}, Results);
5099 break;
5100 }
5101 case ISD::FMUL:
5102 case ISD::STRICT_FMUL: {
5103 ExpandFastFPLibCall(Node, canUseFastMathLibcall(Node),
5104 {RTLIB::FAST_MUL_F32, RTLIB::MUL_F32},
5105 {RTLIB::FAST_MUL_F64, RTLIB::MUL_F64},
5106 {RTLIB::FAST_MUL_F80, RTLIB::MUL_F80},
5107 {RTLIB::FAST_MUL_F128, RTLIB::MUL_F128},
5108 {RTLIB::FAST_MUL_PPCF128, RTLIB::MUL_PPCF128}, Results);
5109 break;
5110 }
5111 case ISD::FP16_TO_FP:
5112 if (Node->getValueType(0) == MVT::f32) {
5113 Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false).first);
5114 }
5115 break;
5117 if (Node->getValueType(0) == MVT::f32) {
5118 std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(
5119 DAG, RTLIB::FPEXT_BF16_F32, MVT::f32, Node->getOperand(1),
5120 CallOptions, SDLoc(Node), Node->getOperand(0));
5121 Results.push_back(Tmp.first);
5122 Results.push_back(Tmp.second);
5123 }
5124 break;
5126 if (Node->getValueType(0) == MVT::f32) {
5127 std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(
5128 DAG, RTLIB::FPEXT_F16_F32, MVT::f32, Node->getOperand(1), CallOptions,
5129 SDLoc(Node), Node->getOperand(0));
5130 Results.push_back(Tmp.first);
5131 Results.push_back(Tmp.second);
5132 }
5133 break;
5134 }
5135 case ISD::FP_TO_FP16: {
5136 RTLIB::Libcall LC =
5137 RTLIB::getFPROUND(Node->getOperand(0).getValueType(), MVT::f16);
5138 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to expand fp_to_fp16");
5139 Results.push_back(ExpandLibCall(LC, Node, false).first);
5140 break;
5141 }
5142 case ISD::FP_TO_BF16: {
5143 RTLIB::Libcall LC =
5144 RTLIB::getFPROUND(Node->getOperand(0).getValueType(), MVT::bf16);
5145 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to expand fp_to_bf16");
5146 Results.push_back(ExpandLibCall(LC, Node, false).first);
5147 break;
5148 }
5151 case ISD::SINT_TO_FP:
5152 case ISD::UINT_TO_FP: {
5153 // TODO - Common the code with DAGTypeLegalizer::SoftenFloatRes_XINT_TO_FP
5154 bool IsStrict = Node->isStrictFPOpcode();
5155 bool Signed = Node->getOpcode() == ISD::SINT_TO_FP ||
5156 Node->getOpcode() == ISD::STRICT_SINT_TO_FP;
5157 EVT SVT = Node->getOperand(IsStrict ? 1 : 0).getValueType();
5158 EVT RVT = Node->getValueType(0);
5159 EVT NVT = EVT();
5160 SDLoc dl(Node);
5161
5162 // Even if the input is legal, no libcall may exactly match, eg. we don't
5163 // have i1 -> fp conversions. So, it needs to be promoted to a larger type,
5164 // eg: i13 -> fp. Then, look for an appropriate libcall.
5165 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
5166 for (unsigned t = MVT::FIRST_INTEGER_VALUETYPE;
5167 t <= MVT::LAST_INTEGER_VALUETYPE && LC == RTLIB::UNKNOWN_LIBCALL;
5168 ++t) {
5169 NVT = (MVT::SimpleValueType)t;
5170 // The source needs to big enough to hold the operand.
5171 if (NVT.bitsGE(SVT))
5172 LC = Signed ? RTLIB::getSINTTOFP(NVT, RVT)
5173 : RTLIB::getUINTTOFP(NVT, RVT);
5174 }
5175 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to legalize as libcall");
5176
5177 SDValue Chain = IsStrict ? Node->getOperand(0) : SDValue();
5178 // Sign/zero extend the argument if the libcall takes a larger type.
5180 NVT, Node->getOperand(IsStrict ? 1 : 0));
5181 CallOptions.setIsSigned(Signed);
5182 std::pair<SDValue, SDValue> Tmp =
5183 TLI.makeLibCall(DAG, LC, RVT, Op, CallOptions, dl, Chain);
5184 Results.push_back(Tmp.first);
5185 if (IsStrict)
5186 Results.push_back(Tmp.second);
5187 break;
5188 }
5189 case ISD::FP_TO_SINT:
5190 case ISD::FP_TO_UINT:
5193 // TODO - Common the code with DAGTypeLegalizer::SoftenFloatOp_FP_TO_XINT.
5194 bool IsStrict = Node->isStrictFPOpcode();
5195 bool Signed = Node->getOpcode() == ISD::FP_TO_SINT ||
5196 Node->getOpcode() == ISD::STRICT_FP_TO_SINT;
5197
5198 SDValue Op = Node->getOperand(IsStrict ? 1 : 0);
5199 EVT SVT = Op.getValueType();
5200 EVT RVT = Node->getValueType(0);
5201 EVT NVT = EVT();
5202 SDLoc dl(Node);
5203
5204 // Even if the result is legal, no libcall may exactly match, eg. we don't
5205 // have fp -> i1 conversions. So, it needs to be promoted to a larger type,
5206 // eg: fp -> i32. Then, look for an appropriate libcall.
5207 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
5208 for (unsigned IntVT = MVT::FIRST_INTEGER_VALUETYPE;
5209 IntVT <= MVT::LAST_INTEGER_VALUETYPE && LC == RTLIB::UNKNOWN_LIBCALL;
5210 ++IntVT) {
5211 NVT = (MVT::SimpleValueType)IntVT;
5212 // The type needs to big enough to hold the result.
5213 if (NVT.bitsGE(RVT))
5214 LC = Signed ? RTLIB::getFPTOSINT(SVT, NVT)
5215 : RTLIB::getFPTOUINT(SVT, NVT);
5216 }
5217 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to legalize as libcall");
5218
5219 SDValue Chain = IsStrict ? Node->getOperand(0) : SDValue();
5220 std::pair<SDValue, SDValue> Tmp =
5221 TLI.makeLibCall(DAG, LC, NVT, Op, CallOptions, dl, Chain);
5222
5223 // Truncate the result if the libcall returns a larger type.
5224 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, RVT, Tmp.first));
5225 if (IsStrict)
5226 Results.push_back(Tmp.second);
5227 break;
5228 }
5229
5230 case ISD::FP_ROUND:
5231 case ISD::STRICT_FP_ROUND: {
5232 // X = FP_ROUND(Y, TRUNC)
5233 // TRUNC is a flag, which is always an integer that is zero or one.
5234 // If TRUNC is 0, this is a normal rounding, if it is 1, this FP_ROUND
5235 // is known to not change the value of Y.
5236 // We can only expand it into libcall if the TRUNC is 0.
5237 bool IsStrict = Node->isStrictFPOpcode();
5238 SDValue Op = Node->getOperand(IsStrict ? 1 : 0);
5239 SDValue Chain = IsStrict ? Node->getOperand(0) : SDValue();
5240 EVT VT = Node->getValueType(0);
5241 assert(cast<ConstantSDNode>(Node->getOperand(IsStrict ? 2 : 1))->isZero() &&
5242 "Unable to expand as libcall if it is not normal rounding");
5243
5244 RTLIB::Libcall LC = RTLIB::getFPROUND(Op.getValueType(), VT);
5245 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to legalize as libcall");
5246
5247 std::pair<SDValue, SDValue> Tmp =
5248 TLI.makeLibCall(DAG, LC, VT, Op, CallOptions, SDLoc(Node), Chain);
5249 Results.push_back(Tmp.first);
5250 if (IsStrict)
5251 Results.push_back(Tmp.second);
5252 break;
5253 }
5254 case ISD::FP_EXTEND: {
5255 Results.push_back(
5256 ExpandLibCall(RTLIB::getFPEXT(Node->getOperand(0).getValueType(),
5257 Node->getValueType(0)),
5258 Node, false).first);
5259 break;
5260 }
5264 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
5265 if (Node->getOpcode() == ISD::STRICT_FP_TO_FP16)
5266 LC = RTLIB::getFPROUND(Node->getOperand(1).getValueType(), MVT::f16);
5267 else if (Node->getOpcode() == ISD::STRICT_FP_TO_BF16)
5268 LC = RTLIB::getFPROUND(Node->getOperand(1).getValueType(), MVT::bf16);
5269 else
5270 LC = RTLIB::getFPEXT(Node->getOperand(1).getValueType(),
5271 Node->getValueType(0));
5272
5273 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to legalize as libcall");
5274
5275 std::pair<SDValue, SDValue> Tmp =
5276 TLI.makeLibCall(DAG, LC, Node->getValueType(0), Node->getOperand(1),
5277 CallOptions, SDLoc(Node), Node->getOperand(0));
5278 Results.push_back(Tmp.first);
5279 Results.push_back(Tmp.second);
5280 break;
5281 }
5282 case ISD::FSUB:
5283 case ISD::STRICT_FSUB: {
5284 ExpandFastFPLibCall(Node, canUseFastMathLibcall(Node),
5285 {RTLIB::FAST_SUB_F32, RTLIB::SUB_F32},
5286 {RTLIB::FAST_SUB_F64, RTLIB::SUB_F64},
5287 {RTLIB::FAST_SUB_F80, RTLIB::SUB_F80},
5288 {RTLIB::FAST_SUB_F128, RTLIB::SUB_F128},
5289 {RTLIB::FAST_SUB_PPCF128, RTLIB::SUB_PPCF128}, Results);
5290 break;
5291 }
5292 case ISD::SREM:
5293 Results.push_back(ExpandIntLibCall(Node, true,
5294 RTLIB::SREM_I8,
5295 RTLIB::SREM_I16, RTLIB::SREM_I32,
5296 RTLIB::SREM_I64, RTLIB::SREM_I128));
5297 break;
5298 case ISD::UREM:
5299 Results.push_back(ExpandIntLibCall(Node, false,
5300 RTLIB::UREM_I8,
5301 RTLIB::UREM_I16, RTLIB::UREM_I32,
5302 RTLIB::UREM_I64, RTLIB::UREM_I128));
5303 break;
5304 case ISD::SDIV:
5305 Results.push_back(ExpandIntLibCall(Node, true,
5306 RTLIB::SDIV_I8,
5307 RTLIB::SDIV_I16, RTLIB::SDIV_I32,
5308 RTLIB::SDIV_I64, RTLIB::SDIV_I128));
5309 break;
5310 case ISD::UDIV:
5311 Results.push_back(ExpandIntLibCall(Node, false,
5312 RTLIB::UDIV_I8,
5313 RTLIB::UDIV_I16, RTLIB::UDIV_I32,
5314 RTLIB::UDIV_I64, RTLIB::UDIV_I128));
5315 break;
5316 case ISD::SDIVREM:
5317 case ISD::UDIVREM:
5318 // Expand into divrem libcall
5319 ExpandDivRemLibCall(Node, Results);
5320 break;
5321 case ISD::MUL:
5322 Results.push_back(ExpandIntLibCall(Node, false,
5323 RTLIB::MUL_I8,
5324 RTLIB::MUL_I16, RTLIB::MUL_I32,
5325 RTLIB::MUL_I64, RTLIB::MUL_I128));
5326 break;
5328 Results.push_back(ExpandBitCountingLibCall(
5329 Node, RTLIB::CTLZ_I32, RTLIB::CTLZ_I64, RTLIB::CTLZ_I128));
5330 break;
5331 case ISD::CTPOP:
5332 Results.push_back(ExpandBitCountingLibCall(
5333 Node, RTLIB::CTPOP_I32, RTLIB::CTPOP_I64, RTLIB::CTPOP_I128));
5334 break;
5335 case ISD::RESET_FPENV: {
5336 // It is legalized to call 'fesetenv(FE_DFL_ENV)'. On most targets
5337 // FE_DFL_ENV is defined as '((const fenv_t *) -1)' in glibc.
5338 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5339 SDValue Ptr = DAG.getAllOnesConstant(dl, PtrTy);
5340 SDValue Chain = Node->getOperand(0);
5341 Results.push_back(
5342 DAG.makeStateFunctionCall(RTLIB::FESETENV, Ptr, Chain, Node));
5343 break;
5344 }
5345 case ISD::GET_FPENV_MEM: {
5346 SDValue Chain = Node->getOperand(0);
5347 SDValue EnvPtr = Node->getOperand(1);
5348 Results.push_back(
5349 DAG.makeStateFunctionCall(RTLIB::FEGETENV, EnvPtr, Chain, Node));
5350 break;
5351 }
5352 case ISD::SET_FPENV_MEM: {
5353 SDValue Chain = Node->getOperand(0);
5354 SDValue EnvPtr = Node->getOperand(1);
5355 Results.push_back(
5356 DAG.makeStateFunctionCall(RTLIB::FESETENV, EnvPtr, Chain, Node));
5357 break;
5358 }
5359 case ISD::GET_FPMODE: {
5360 // Call fegetmode, which saves control modes into a stack slot. Then load
5361 // the value to return from the stack.
5362 EVT ModeVT = Node->getValueType(0);
5364 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
5365 SDValue Chain = DAG.makeStateFunctionCall(RTLIB::FEGETMODE, StackPtr,
5366 Node->getOperand(0), Node);
5367 SDValue LdInst = DAG.getLoad(
5368 ModeVT, dl, Chain, StackPtr,
5370 Results.push_back(LdInst);
5371 Results.push_back(LdInst.getValue(1));
5372 break;
5373 }
5374 case ISD::SET_FPMODE: {
5375 // Move control modes to stack slot and then call fesetmode with the pointer
5376 // to the slot as argument.
5377 SDValue Mode = Node->getOperand(1);
5378 EVT ModeVT = Mode.getValueType();
5380 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
5381 SDValue StInst = DAG.getStore(
5382 Node->getOperand(0), dl, Mode, StackPtr,
5384 Results.push_back(
5385 DAG.makeStateFunctionCall(RTLIB::FESETMODE, StackPtr, StInst, Node));
5386 break;
5387 }
5388 case ISD::RESET_FPMODE: {
5389 // It is legalized to a call 'fesetmode(FE_DFL_MODE)'. On most targets
5390 // FE_DFL_MODE is defined as '((const femode_t *) -1)' in glibc. If not, the
5391 // target must provide custom lowering.
5392 const DataLayout &DL = DAG.getDataLayout();
5393 EVT PtrTy = TLI.getPointerTy(DL);
5394 SDValue Mode = DAG.getAllOnesConstant(dl, PtrTy);
5395 Results.push_back(DAG.makeStateFunctionCall(RTLIB::FESETMODE, Mode,
5396 Node->getOperand(0), Node));
5397 break;
5398 }
5399 }
5400
5401 // Replace the original node with the legalized result.
5402 if (!Results.empty()) {
5403 LLVM_DEBUG(dbgs() << "Successfully converted node to libcall\n");
5404 ReplaceNode(Node, Results.data());
5405 } else
5406 LLVM_DEBUG(dbgs() << "Could not convert node to libcall\n");
5407}
5408
5409// Determine the vector type to use in place of an original scalar element when
5410// promoting equally sized vectors.
5412 MVT EltVT, MVT NewEltVT) {
5413 unsigned OldEltsPerNewElt = EltVT.getSizeInBits() / NewEltVT.getSizeInBits();
5414 MVT MidVT = OldEltsPerNewElt == 1
5415 ? NewEltVT
5416 : MVT::getVectorVT(NewEltVT, OldEltsPerNewElt);
5417 assert(TLI.isTypeLegal(MidVT) && "unexpected");
5418 return MidVT;
5419}
5420
5421void SelectionDAGLegalize::PromoteNode(SDNode *Node) {
5422 LLVM_DEBUG(dbgs() << "Trying to promote node\n");
5424 MVT OVT = Node->getSimpleValueType(0);
5425 if (Node->getOpcode() == ISD::UINT_TO_FP ||
5426 Node->getOpcode() == ISD::SINT_TO_FP || Node->getOpcode() == ISD::SETCC ||
5427 Node->getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
5428 Node->getOpcode() == ISD::INSERT_VECTOR_ELT ||
5429 Node->getOpcode() == ISD::VECREDUCE_FMAX ||
5430 Node->getOpcode() == ISD::VECREDUCE_FMIN ||
5431 Node->getOpcode() == ISD::VECREDUCE_FMAXIMUM ||
5432 Node->getOpcode() == ISD::VECREDUCE_FMINIMUM ||
5433 Node->getOpcode() == ISD::VECREDUCE_FMAXIMUMNUM ||
5434 Node->getOpcode() == ISD::VECREDUCE_FMINIMUMNUM) {
5435 OVT = Node->getOperand(0).getSimpleValueType();
5436 }
5437 if (Node->getOpcode() == ISD::ATOMIC_STORE ||
5438 Node->getOpcode() == ISD::STRICT_UINT_TO_FP ||
5439 Node->getOpcode() == ISD::STRICT_SINT_TO_FP ||
5440 Node->getOpcode() == ISD::STRICT_FSETCC ||
5441 Node->getOpcode() == ISD::STRICT_FSETCCS ||
5442 Node->getOpcode() == ISD::STRICT_LRINT ||
5443 Node->getOpcode() == ISD::STRICT_LLRINT ||
5444 Node->getOpcode() == ISD::STRICT_LROUND ||
5445 Node->getOpcode() == ISD::STRICT_LLROUND ||
5446 Node->getOpcode() == ISD::VP_REDUCE_FADD ||
5447 Node->getOpcode() == ISD::VP_REDUCE_FMUL ||
5448 Node->getOpcode() == ISD::VP_REDUCE_FMAX ||
5449 Node->getOpcode() == ISD::VP_REDUCE_FMIN ||
5450 Node->getOpcode() == ISD::VP_REDUCE_FMAXIMUM ||
5451 Node->getOpcode() == ISD::VP_REDUCE_FMINIMUM ||
5452 Node->getOpcode() == ISD::VP_REDUCE_SEQ_FADD)
5453 OVT = Node->getOperand(1).getSimpleValueType();
5454 if (Node->getOpcode() == ISD::BR_CC ||
5455 Node->getOpcode() == ISD::SELECT_CC)
5456 OVT = Node->getOperand(2).getSimpleValueType();
5457 // Preserve fast math flags
5458 SDNodeFlags FastMathFlags = Node->getFlags() & SDNodeFlags::FastMathFlags;
5459 SelectionDAG::FlagInserter FlagsInserter(DAG, FastMathFlags);
5460 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
5461 SDLoc dl(Node);
5462 SDValue Tmp1, Tmp2, Tmp3, Tmp4;
5463 switch (Node->getOpcode()) {
5464 case ISD::CTTZ:
5466 case ISD::CTLZ:
5467 case ISD::CTPOP: {
5468 // Zero extend the argument unless its cttz, then use any_extend.
5469 if (Node->getOpcode() == ISD::CTTZ ||
5470 Node->getOpcode() == ISD::CTTZ_ZERO_POISON)
5471 Tmp1 = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(0));
5472 else
5473 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
5474
5475 unsigned NewOpc = Node->getOpcode();
5476 if (NewOpc == ISD::CTTZ) {
5477 // The count is the same in the promoted type except if the original
5478 // value was zero. This can be handled by setting the bit just off
5479 // the top of the original type.
5480 auto TopBit = APInt::getOneBitSet(NVT.getSizeInBits(),
5481 OVT.getSizeInBits());
5482 Tmp1 = DAG.getNode(ISD::OR, dl, NVT, Tmp1,
5483 DAG.getConstant(TopBit, dl, NVT));
5484 NewOpc = ISD::CTTZ_ZERO_POISON;
5485 }
5486 // Perform the larger operation. For CTPOP and CTTZ_ZERO_POISON, this is
5487 // already the correct result.
5488 Tmp1 = DAG.getNode(NewOpc, dl, NVT, Tmp1);
5489 if (NewOpc == ISD::CTLZ) {
5490 // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
5491 Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
5492 DAG.getConstant(NVT.getSizeInBits() -
5493 OVT.getSizeInBits(), dl, NVT));
5494 }
5495 Results.push_back(
5496 DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1, SDNodeFlags::NoWrap));
5497 break;
5498 }
5499 case ISD::CTLZ_ZERO_POISON: {
5500 // We know that the argument is unlikely to be zero, hence we can take a
5501 // different approach as compared to ISD::CTLZ
5502
5503 // Any Extend the argument
5504 auto AnyExtendedNode =
5505 DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(0));
5506
5507 // Tmp1 = Tmp1 << (sizeinbits(NVT) - sizeinbits(Old VT))
5508 auto ShiftConstant = DAG.getShiftAmountConstant(
5509 NVT.getSizeInBits() - OVT.getSizeInBits(), NVT, dl);
5510 auto LeftShiftResult =
5511 DAG.getNode(ISD::SHL, dl, NVT, AnyExtendedNode, ShiftConstant);
5512
5513 // Perform the larger operation
5514 auto CTLZResult = DAG.getNode(Node->getOpcode(), dl, NVT, LeftShiftResult);
5515 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, CTLZResult));
5516 break;
5517 }
5518 case ISD::PEXT: {
5519 Tmp1 = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(0));
5520 Tmp2 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(1));
5521 Tmp1 = DAG.getNode(ISD::PEXT, dl, NVT, Tmp1, Tmp2);
5522 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
5523 break;
5524 }
5525 case ISD::PDEP: {
5526 Tmp1 = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(0));
5527 Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(1));
5528 Tmp1 = DAG.getNode(ISD::PDEP, dl, NVT, Tmp1, Tmp2);
5529 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
5530 break;
5531 }
5532 case ISD::BITREVERSE:
5533 case ISD::BSWAP: {
5534 unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
5535 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
5536 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
5537 Tmp1 = DAG.getNode(ISD::SRL, dl, NVT, Tmp1,
5538 DAG.getShiftAmountConstant(DiffBits, NVT, dl));
5539
5540 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
5541 break;
5542 }
5543 case ISD::FP_TO_UINT:
5545 case ISD::FP_TO_SINT:
5547 PromoteLegalFP_TO_INT(Node, dl, Results);
5548 break;
5551 Results.push_back(PromoteLegalFP_TO_INT_SAT(Node, dl));
5552 break;
5553 case ISD::UINT_TO_FP:
5555 case ISD::SINT_TO_FP:
5557 PromoteLegalINT_TO_FP(Node, dl, Results);
5558 break;
5559 case ISD::VAARG: {
5560 SDValue Chain = Node->getOperand(0); // Get the chain.
5561 SDValue Ptr = Node->getOperand(1); // Get the pointer.
5562
5563 unsigned TruncOp;
5564 if (OVT.isVector()) {
5565 TruncOp = ISD::BITCAST;
5566 } else {
5567 assert(OVT.isInteger()
5568 && "VAARG promotion is supported only for vectors or integer types");
5569 TruncOp = ISD::TRUNCATE;
5570 }
5571
5572 // Perform the larger operation, then convert back
5573 Tmp1 = DAG.getVAArg(NVT, dl, Chain, Ptr, Node->getOperand(2),
5574 Node->getConstantOperandVal(3));
5575 Chain = Tmp1.getValue(1);
5576
5577 Tmp2 = DAG.getNode(TruncOp, dl, OVT, Tmp1);
5578
5579 // Modified the chain result - switch anything that used the old chain to
5580 // use the new one.
5581 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Tmp2);
5582 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
5583 if (UpdatedNodes) {
5584 UpdatedNodes->insert(Tmp2.getNode());
5585 UpdatedNodes->insert(Chain.getNode());
5586 }
5587 ReplacedNode(Node);
5588 break;
5589 }
5590 case ISD::MUL:
5591 case ISD::SDIV:
5592 case ISD::SREM:
5593 case ISD::UDIV:
5594 case ISD::UREM:
5595 case ISD::SMIN:
5596 case ISD::SMAX:
5597 case ISD::UMIN:
5598 case ISD::UMAX:
5599 case ISD::AND:
5600 case ISD::OR:
5601 case ISD::XOR: {
5602 unsigned ExtOp, TruncOp;
5603 if (OVT.isVector()) {
5604 ExtOp = ISD::BITCAST;
5605 TruncOp = ISD::BITCAST;
5606 } else {
5607 assert(OVT.isInteger() && "Cannot promote logic operation");
5608
5609 switch (Node->getOpcode()) {
5610 default:
5611 ExtOp = ISD::ANY_EXTEND;
5612 break;
5613 case ISD::SDIV:
5614 case ISD::SREM:
5615 case ISD::SMIN:
5616 case ISD::SMAX:
5617 ExtOp = ISD::SIGN_EXTEND;
5618 break;
5619 case ISD::UDIV:
5620 case ISD::UREM:
5621 ExtOp = ISD::ZERO_EXTEND;
5622 break;
5623 case ISD::UMIN:
5624 case ISD::UMAX:
5625 if (TLI.isSExtCheaperThanZExt(OVT, NVT))
5626 ExtOp = ISD::SIGN_EXTEND;
5627 else
5628 ExtOp = ISD::ZERO_EXTEND;
5629 break;
5630 }
5631 TruncOp = ISD::TRUNCATE;
5632 }
5633 // Promote each of the values to the new type.
5634 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
5635 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
5636 // Perform the larger operation, then convert back
5637 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
5638 Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1));
5639 break;
5640 }
5641 case ISD::UMUL_LOHI:
5642 case ISD::SMUL_LOHI: {
5643 // Promote to a multiply in a wider integer type.
5644 unsigned ExtOp = Node->getOpcode() == ISD::UMUL_LOHI ? ISD::ZERO_EXTEND
5646 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
5647 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
5648 Tmp1 = DAG.getNode(ISD::MUL, dl, NVT, Tmp1, Tmp2);
5649
5650 unsigned OriginalSize = OVT.getScalarSizeInBits();
5651 Tmp2 = DAG.getNode(ISD::SRL, dl, NVT, Tmp1,
5652 DAG.getShiftAmountConstant(OriginalSize, NVT, dl));
5653 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
5654 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp2));
5655 break;
5656 }
5657 case ISD::SELECT: {
5658 unsigned ExtOp, TruncOp;
5659 if (Node->getValueType(0).isVector() ||
5660 Node->getValueType(0).getSizeInBits() == NVT.getSizeInBits()) {
5661 ExtOp = ISD::BITCAST;
5662 TruncOp = ISD::BITCAST;
5663 } else if (Node->getValueType(0).isInteger()) {
5664 ExtOp = ISD::ANY_EXTEND;
5665 TruncOp = ISD::TRUNCATE;
5666 } else {
5667 ExtOp = ISD::FP_EXTEND;
5668 TruncOp = ISD::FP_ROUND;
5669 }
5670 Tmp1 = Node->getOperand(0);
5671 // Promote each of the values to the new type.
5672 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
5673 Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
5674 // Perform the larger operation, then round down.
5675 Tmp1 = DAG.getSelect(dl, NVT, Tmp1, Tmp2, Tmp3);
5676 if (TruncOp != ISD::FP_ROUND)
5677 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1);
5678 else
5679 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1,
5680 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
5681 Results.push_back(Tmp1);
5682 break;
5683 }
5684 case ISD::VECTOR_SHUFFLE: {
5685 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
5686
5687 // Cast the two input vectors.
5688 Tmp1 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0));
5689 Tmp2 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(1));
5690
5691 // Convert the shuffle mask to the right # elements.
5692 Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
5693 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OVT, Tmp1);
5694 Results.push_back(Tmp1);
5695 break;
5696 }
5699 Tmp1 = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(0));
5700 Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(1));
5701 Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2,
5702 Node->getOperand(2));
5703 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp3));
5704 break;
5705 }
5706 case ISD::SELECT_CC: {
5707 SDValue Cond = Node->getOperand(4);
5708 ISD::CondCode CCCode = cast<CondCodeSDNode>(Cond)->get();
5709 // Type of the comparison operands.
5710 MVT CVT = Node->getSimpleValueType(0);
5711 assert(CVT == OVT && "not handled");
5712
5713 unsigned ExtOp = ISD::FP_EXTEND;
5714 if (NVT.isInteger()) {
5716 }
5717
5718 // Promote the comparison operands, if needed.
5719 if (TLI.isCondCodeLegal(CCCode, CVT)) {
5720 Tmp1 = Node->getOperand(0);
5721 Tmp2 = Node->getOperand(1);
5722 } else {
5723 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
5724 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
5725 }
5726 // Cast the true/false operands.
5727 Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
5728 Tmp4 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(3));
5729
5730 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, NVT, {Tmp1, Tmp2, Tmp3, Tmp4, Cond},
5731 Node->getFlags());
5732
5733 // Cast the result back to the original type.
5734 if (ExtOp != ISD::FP_EXTEND)
5735 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1);
5736 else
5737 Tmp1 = DAG.getNode(ISD::FP_ROUND, dl, OVT, Tmp1,
5738 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
5739
5740 Results.push_back(Tmp1);
5741 break;
5742 }
5743 case ISD::SETCC:
5744 case ISD::STRICT_FSETCC:
5745 case ISD::STRICT_FSETCCS: {
5746 unsigned ExtOp = ISD::FP_EXTEND;
5747 if (NVT.isInteger()) {
5748 ISD::CondCode CCCode = Node->getOperandCondCode(2);
5749 if (isSignedIntSetCC(CCCode) ||
5750 TLI.isSExtCheaperThanZExt(Node->getOperand(0).getValueType(), NVT))
5751 ExtOp = ISD::SIGN_EXTEND;
5752 else
5753 ExtOp = ISD::ZERO_EXTEND;
5754 }
5755 if (Node->isStrictFPOpcode()) {
5756 SDValue InChain = Node->getOperand(0);
5757 std::tie(Tmp1, std::ignore) =
5758 DAG.getStrictFPExtendOrRound(Node->getOperand(1), InChain, dl, NVT);
5759 std::tie(Tmp2, std::ignore) =
5760 DAG.getStrictFPExtendOrRound(Node->getOperand(2), InChain, dl, NVT);
5761 SmallVector<SDValue, 2> TmpChains = {Tmp1.getValue(1), Tmp2.getValue(1)};
5762 SDValue OutChain = DAG.getTokenFactor(dl, TmpChains);
5763 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
5764 Results.push_back(DAG.getNode(Node->getOpcode(), dl, VTs,
5765 {OutChain, Tmp1, Tmp2, Node->getOperand(3)},
5766 Node->getFlags()));
5767 Results.push_back(Results.back().getValue(1));
5768 break;
5769 }
5770 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
5771 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
5772 Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0), Tmp1,
5773 Tmp2, Node->getOperand(2), Node->getFlags()));
5774 break;
5775 }
5776 case ISD::BR_CC: {
5777 unsigned ExtOp = ISD::FP_EXTEND;
5778 if (NVT.isInteger()) {
5779 ISD::CondCode CCCode = Node->getOperandCondCode(1);
5781 }
5782 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
5783 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(3));
5784 Results.push_back(DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0),
5785 Node->getOperand(0), Node->getOperand(1),
5786 Tmp1, Tmp2, Node->getOperand(4)));
5787 break;
5788 }
5789 case ISD::FADD:
5790 case ISD::FSUB:
5791 case ISD::FMUL:
5792 case ISD::FDIV:
5793 case ISD::FREM:
5794 case ISD::FMINNUM:
5795 case ISD::FMAXNUM:
5796 case ISD::FMINIMUM:
5797 case ISD::FMAXIMUM:
5798 case ISD::FMINIMUMNUM:
5799 case ISD::FMAXIMUMNUM:
5800 case ISD::FPOW:
5801 case ISD::FATAN2:
5802 // Promote scalar operations to vector using SCALAR_TO_VECTOR
5803 if (!OVT.isVector() && NVT.isVector() &&
5804 NVT.getVectorElementType() == OVT) {
5805 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Node->getOperand(0));
5806 Tmp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Node->getOperand(1));
5807 Tmp3 =
5808 DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2, Node->getFlags());
5809 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, OVT, Tmp3,
5810 DAG.getConstant(0, dl, MVT::i32)));
5811 break;
5812 }
5813 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
5814 Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
5815 Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
5816 Results.push_back(
5817 DAG.getNode(ISD::FP_ROUND, dl, OVT, Tmp3,
5818 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)));
5819 break;
5820
5822 case ISD::STRICT_FMAXIMUM: {
5823 SDValue InChain = Node->getOperand(0);
5824 SDVTList VTs = DAG.getVTList(NVT, MVT::Other);
5825 Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, VTs, InChain,
5826 Node->getOperand(1));
5827 Tmp2 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, VTs, InChain,
5828 Node->getOperand(2));
5829 SmallVector<SDValue, 4> Ops = {InChain, Tmp1, Tmp2};
5830 Tmp3 = DAG.getNode(Node->getOpcode(), dl, VTs, Ops, Node->getFlags());
5831 Tmp4 = DAG.getNode(ISD::STRICT_FP_ROUND, dl, DAG.getVTList(OVT, MVT::Other),
5832 InChain, Tmp3,
5833 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
5834 Results.push_back(Tmp4);
5835 Results.push_back(Tmp4.getValue(1));
5836 break;
5837 }
5838
5839 case ISD::STRICT_FADD:
5840 case ISD::STRICT_FSUB:
5841 case ISD::STRICT_FMUL:
5842 case ISD::STRICT_FDIV:
5845 case ISD::STRICT_FREM:
5846 case ISD::STRICT_FPOW:
5847 case ISD::STRICT_FATAN2:
5848 Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
5849 {Node->getOperand(0), Node->getOperand(1)});
5850 Tmp2 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
5851 {Node->getOperand(0), Node->getOperand(2)});
5852 Tmp3 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Tmp1.getValue(1),
5853 Tmp2.getValue(1));
5854 Tmp1 = DAG.getNode(Node->getOpcode(), dl, {NVT, MVT::Other},
5855 {Tmp3, Tmp1, Tmp2});
5856 Tmp1 = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {OVT, MVT::Other},
5857 {Tmp1.getValue(1), Tmp1,
5858 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)});
5859 Results.push_back(Tmp1);
5860 Results.push_back(Tmp1.getValue(1));
5861 break;
5862 case ISD::FMA:
5863 // Promote scalar operations to vector using SCALAR_TO_VECTOR
5864 if (!OVT.isVector() && NVT.isVector() &&
5865 NVT.getVectorElementType() == OVT) {
5866 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Node->getOperand(0));
5867 Tmp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Node->getOperand(1));
5868 Tmp3 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Node->getOperand(2));
5869 SDValue Result = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2, Tmp3,
5870 Node->getFlags());
5871 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, OVT, Result,
5872 DAG.getConstant(0, dl, MVT::i32)));
5873 break;
5874 }
5875 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
5876 Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
5877 Tmp3 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(2));
5878 Results.push_back(
5879 DAG.getNode(ISD::FP_ROUND, dl, OVT,
5880 DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2, Tmp3),
5881 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)));
5882 break;
5883 case ISD::STRICT_FMA:
5884 Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
5885 {Node->getOperand(0), Node->getOperand(1)});
5886 Tmp2 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
5887 {Node->getOperand(0), Node->getOperand(2)});
5888 Tmp3 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
5889 {Node->getOperand(0), Node->getOperand(3)});
5890 Tmp4 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Tmp1.getValue(1),
5891 Tmp2.getValue(1), Tmp3.getValue(1));
5892 Tmp4 = DAG.getNode(Node->getOpcode(), dl, {NVT, MVT::Other},
5893 {Tmp4, Tmp1, Tmp2, Tmp3});
5894 Tmp4 = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {OVT, MVT::Other},
5895 {Tmp4.getValue(1), Tmp4,
5896 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)});
5897 Results.push_back(Tmp4);
5898 Results.push_back(Tmp4.getValue(1));
5899 break;
5900 case ISD::FCOPYSIGN:
5901 case ISD::FLDEXP:
5902 case ISD::FPOWI: {
5903 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
5904 Tmp2 = Node->getOperand(1);
5905 Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
5906
5907 // fcopysign doesn't change anything but the sign bit, so
5908 // (fp_round (fcopysign (fpext a), b))
5909 // is as precise as
5910 // (fp_round (fpext a))
5911 // which is a no-op. Mark it as a TRUNCating FP_ROUND.
5912 const bool isTrunc = (Node->getOpcode() == ISD::FCOPYSIGN);
5913 Results.push_back(
5914 DAG.getNode(ISD::FP_ROUND, dl, OVT, Tmp3,
5915 DAG.getIntPtrConstant(isTrunc, dl, /*isTarget=*/true)));
5916 break;
5917 }
5918 case ISD::STRICT_FLDEXP: {
5919 Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
5920 {Node->getOperand(0), Node->getOperand(1)});
5921 Tmp2 = Node->getOperand(2);
5922 Tmp3 = DAG.getNode(ISD::STRICT_FLDEXP, dl, {NVT, MVT::Other},
5923 {Tmp1.getValue(1), Tmp1, Tmp2});
5924 Tmp4 = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {OVT, MVT::Other},
5925 {Tmp3.getValue(1), Tmp3,
5926 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)});
5927 Results.push_back(Tmp4);
5928 Results.push_back(Tmp4.getValue(1));
5929 break;
5930 }
5931 case ISD::STRICT_FPOWI:
5932 Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
5933 {Node->getOperand(0), Node->getOperand(1)});
5934 Tmp2 = DAG.getNode(Node->getOpcode(), dl, {NVT, MVT::Other},
5935 {Tmp1.getValue(1), Tmp1, Node->getOperand(2)});
5936 Tmp3 = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {OVT, MVT::Other},
5937 {Tmp2.getValue(1), Tmp2,
5938 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)});
5939 Results.push_back(Tmp3);
5940 Results.push_back(Tmp3.getValue(1));
5941 break;
5942 case ISD::FFREXP: {
5943 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
5944 Tmp2 = DAG.getNode(ISD::FFREXP, dl, {NVT, Node->getValueType(1)}, Tmp1);
5945
5946 Results.push_back(
5947 DAG.getNode(ISD::FP_ROUND, dl, OVT, Tmp2,
5948 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)));
5949
5950 Results.push_back(Tmp2.getValue(1));
5951 break;
5952 }
5953 case ISD::FMODF:
5954 case ISD::FSINCOS:
5955 case ISD::FSINCOSPI: {
5956 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
5957 Tmp2 = DAG.getNode(Node->getOpcode(), dl, DAG.getVTList(NVT, NVT), Tmp1);
5958 Tmp3 = DAG.getIntPtrConstant(0, dl, /*isTarget=*/true);
5959 for (unsigned ResNum = 0; ResNum < Node->getNumValues(); ResNum++)
5960 Results.push_back(
5961 DAG.getNode(ISD::FP_ROUND, dl, OVT, Tmp2.getValue(ResNum), Tmp3));
5962 break;
5963 }
5964 case ISD::FFLOOR:
5965 case ISD::FCEIL:
5966 case ISD::FRINT:
5967 case ISD::FNEARBYINT:
5968 case ISD::FROUND:
5969 case ISD::FROUNDEVEN:
5970 case ISD::FTRUNC:
5971 case ISD::FNEG:
5972 case ISD::FSQRT:
5973 case ISD::FSIN:
5974 case ISD::FCOS:
5975 case ISD::FTAN:
5976 case ISD::FASIN:
5977 case ISD::FACOS:
5978 case ISD::FATAN:
5979 case ISD::FSINH:
5980 case ISD::FCOSH:
5981 case ISD::FTANH:
5982 case ISD::FLOG:
5983 case ISD::FLOG2:
5984 case ISD::FLOG10:
5985 case ISD::FABS:
5986 case ISD::FEXP:
5987 case ISD::FEXP2:
5988 case ISD::FEXP10:
5989 case ISD::FCANONICALIZE:
5990 // Promote scalar operations to vector using SCALAR_TO_VECTOR
5991 if (!OVT.isVector() && NVT.isVector() &&
5992 NVT.getVectorElementType() == OVT) {
5993 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Node->getOperand(0));
5994 Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Node->getFlags());
5995 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, OVT, Tmp2,
5996 DAG.getConstant(0, dl, MVT::i32)));
5997 break;
5998 }
5999 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
6000 Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
6001 Results.push_back(
6002 DAG.getNode(ISD::FP_ROUND, dl, OVT, Tmp2,
6003 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)));
6004 break;
6005 case ISD::STRICT_FFLOOR:
6006 case ISD::STRICT_FCEIL:
6007 case ISD::STRICT_FRINT:
6009 case ISD::STRICT_FROUND:
6011 case ISD::STRICT_FTRUNC:
6012 case ISD::STRICT_FSQRT:
6013 case ISD::STRICT_FSIN:
6014 case ISD::STRICT_FCOS:
6015 case ISD::STRICT_FTAN:
6016 case ISD::STRICT_FASIN:
6017 case ISD::STRICT_FACOS:
6018 case ISD::STRICT_FATAN:
6019 case ISD::STRICT_FSINH:
6020 case ISD::STRICT_FCOSH:
6021 case ISD::STRICT_FTANH:
6022 case ISD::STRICT_FLOG:
6023 case ISD::STRICT_FLOG2:
6024 case ISD::STRICT_FLOG10:
6025 case ISD::STRICT_FEXP:
6026 case ISD::STRICT_FEXP2:
6027 Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
6028 {Node->getOperand(0), Node->getOperand(1)});
6029 Tmp2 = DAG.getNode(Node->getOpcode(), dl, {NVT, MVT::Other},
6030 {Tmp1.getValue(1), Tmp1});
6031 Tmp3 = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {OVT, MVT::Other},
6032 {Tmp2.getValue(1), Tmp2,
6033 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)});
6034 Results.push_back(Tmp3);
6035 Results.push_back(Tmp3.getValue(1));
6036 break;
6037 case ISD::LLROUND:
6038 case ISD::LROUND:
6039 case ISD::LRINT:
6040 case ISD::LLRINT:
6041 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
6042 Tmp2 = DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0), Tmp1);
6043 Results.push_back(Tmp2);
6044 break;
6046 case ISD::STRICT_LROUND:
6047 case ISD::STRICT_LRINT:
6048 case ISD::STRICT_LLRINT:
6049 Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
6050 {Node->getOperand(0), Node->getOperand(1)});
6051 Tmp2 = DAG.getNode(Node->getOpcode(), dl, {NVT, MVT::Other},
6052 {Tmp1.getValue(1), Tmp1});
6053 Results.push_back(Tmp2);
6054 Results.push_back(Tmp2.getValue(1));
6055 break;
6056 case ISD::BUILD_VECTOR: {
6057 MVT EltVT = OVT.getVectorElementType();
6058 MVT NewEltVT = NVT.getVectorElementType();
6059
6060 // Handle bitcasts to a different vector type with the same total bit size
6061 //
6062 // e.g. v2i64 = build_vector i64:x, i64:y => v4i32
6063 // =>
6064 // v4i32 = concat_vectors (v2i32 (bitcast i64:x)), (v2i32 (bitcast i64:y))
6065
6066 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
6067 "Invalid promote type for build_vector");
6068 assert(NewEltVT.bitsLE(EltVT) && "not handled");
6069
6070 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
6071
6073 for (const SDValue &Op : Node->op_values())
6074 NewOps.push_back(DAG.getNode(ISD::BITCAST, SDLoc(Op), MidVT, Op));
6075
6076 SDLoc SL(Node);
6077 SDValue Concat =
6078 DAG.getNode(MidVT == NewEltVT ? ISD::BUILD_VECTOR : ISD::CONCAT_VECTORS,
6079 SL, NVT, NewOps);
6080 SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat);
6081 Results.push_back(CvtVec);
6082 break;
6083 }
6085 MVT EltVT = OVT.getVectorElementType();
6086 MVT NewEltVT = NVT.getVectorElementType();
6087
6088 // Handle bitcasts to a different vector type with the same total bit size.
6089 //
6090 // e.g. v2i64 = extract_vector_elt x:v2i64, y:i32
6091 // =>
6092 // v4i32:castx = bitcast x:v2i64
6093 //
6094 // i64 = bitcast
6095 // (v2i32 build_vector (i32 (extract_vector_elt castx, (2 * y))),
6096 // (i32 (extract_vector_elt castx, (2 * y + 1)))
6097 //
6098
6099 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
6100 "Invalid promote type for extract_vector_elt");
6101 assert(NewEltVT.bitsLT(EltVT) && "not handled");
6102
6103 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
6104 unsigned NewEltsPerOldElt = MidVT.getVectorNumElements();
6105
6106 SDValue Idx = Node->getOperand(1);
6107 EVT IdxVT = Idx.getValueType();
6108 SDLoc SL(Node);
6109 SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SL, IdxVT);
6110 SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor);
6111
6112 SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0));
6113
6115 for (unsigned I = 0; I < NewEltsPerOldElt; ++I) {
6116 SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT);
6117 SDValue TmpIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset);
6118
6119 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT,
6120 CastVec, TmpIdx);
6121 NewOps.push_back(Elt);
6122 }
6123
6124 SDValue NewVec = DAG.getBuildVector(MidVT, SL, NewOps);
6125 Results.push_back(DAG.getNode(ISD::BITCAST, SL, EltVT, NewVec));
6126 break;
6127 }
6129 MVT EltVT = OVT.getVectorElementType();
6130 MVT NewEltVT = NVT.getVectorElementType();
6131
6132 // Handle bitcasts to a different vector type with the same total bit size
6133 //
6134 // e.g. v2i64 = insert_vector_elt x:v2i64, y:i64, z:i32
6135 // =>
6136 // v4i32:castx = bitcast x:v2i64
6137 // v2i32:casty = bitcast y:i64
6138 //
6139 // v2i64 = bitcast
6140 // (v4i32 insert_vector_elt
6141 // (v4i32 insert_vector_elt v4i32:castx,
6142 // (extract_vector_elt casty, 0), 2 * z),
6143 // (extract_vector_elt casty, 1), (2 * z + 1))
6144
6145 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
6146 "Invalid promote type for insert_vector_elt");
6147 assert(NewEltVT.bitsLT(EltVT) && "not handled");
6148
6149 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
6150 unsigned NewEltsPerOldElt = MidVT.getVectorNumElements();
6151
6152 SDValue Val = Node->getOperand(1);
6153 SDValue Idx = Node->getOperand(2);
6154 EVT IdxVT = Idx.getValueType();
6155 SDLoc SL(Node);
6156
6157 SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SDLoc(), IdxVT);
6158 SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor);
6159
6160 SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0));
6161 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val);
6162
6163 SDValue NewVec = CastVec;
6164 for (unsigned I = 0; I < NewEltsPerOldElt; ++I) {
6165 SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT);
6166 SDValue InEltIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset);
6167
6168 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT,
6169 CastVal, IdxOffset);
6170
6171 NewVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, NVT,
6172 NewVec, Elt, InEltIdx);
6173 }
6174
6175 Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewVec));
6176 break;
6177 }
6178 case ISD::SCALAR_TO_VECTOR: {
6179 MVT EltVT = OVT.getVectorElementType();
6180 MVT NewEltVT = NVT.getVectorElementType();
6181
6182 // Handle bitcasts to different vector type with the same total bit size.
6183 //
6184 // e.g. v2i64 = scalar_to_vector x:i64
6185 // =>
6186 // concat_vectors (v2i32 bitcast x:i64), (v2i32 undef)
6187 //
6188
6189 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
6190 SDValue Val = Node->getOperand(0);
6191 SDLoc SL(Node);
6192
6193 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val);
6194 SDValue Undef = DAG.getUNDEF(MidVT);
6195
6197 NewElts.push_back(CastVal);
6198 for (unsigned I = 1, NElts = OVT.getVectorNumElements(); I != NElts; ++I)
6199 NewElts.push_back(Undef);
6200
6201 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewElts);
6202 SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat);
6203 Results.push_back(CvtVec);
6204 break;
6205 }
6206 case ISD::ATOMIC_SWAP:
6207 case ISD::ATOMIC_STORE: {
6208 AtomicSDNode *AM = cast<AtomicSDNode>(Node);
6209 SDLoc SL(Node);
6210 if (AM->getOpcode() == ISD::ATOMIC_STORE && NVT.bitsGT(OVT)) {
6211 assert(NVT.isInteger() && "unexpected promotion type");
6212 MVT IntVT = MVT::getIntegerVT(OVT.getSizeInBits());
6213 EVT MemVT = AM->getMemoryVT().changeTypeToInteger();
6214 SDValue IntVal = DAG.getNode(ISD::BITCAST, SL, IntVT, AM->getVal());
6215 SDValue ExtVal = DAG.getNode(ISD::ANY_EXTEND, SL, NVT, IntVal);
6216 Results.push_back(DAG.getAtomic(ISD::ATOMIC_STORE, SL, MemVT,
6217 AM->getChain(), ExtVal, AM->getBasePtr(),
6218 AM->getMemOperand()));
6219 break;
6220 }
6221
6222 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, NVT, AM->getVal());
6223 assert(NVT.getSizeInBits() == OVT.getSizeInBits() &&
6224 "unexpected promotion type");
6225 assert(AM->getMemoryVT().getSizeInBits() == NVT.getSizeInBits() &&
6226 "unexpected atomic_swap with illegal type");
6227
6228 SDValue Op0 = AM->getBasePtr();
6229 SDValue Op1 = CastVal;
6230
6231 // ATOMIC_STORE uses a swapped operand order from every other AtomicSDNode,
6232 // but really it should merge with ISD::STORE.
6233 if (AM->getOpcode() == ISD::ATOMIC_STORE)
6234 std::swap(Op0, Op1);
6235
6236 SDValue NewAtomic = DAG.getAtomic(AM->getOpcode(), SL, NVT, AM->getChain(),
6237 Op0, Op1, AM->getMemOperand());
6238
6239 if (AM->getOpcode() != ISD::ATOMIC_STORE) {
6240 Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewAtomic));
6241 Results.push_back(NewAtomic.getValue(1));
6242 } else
6243 Results.push_back(NewAtomic);
6244 break;
6245 }
6246 case ISD::ATOMIC_LOAD: {
6247 AtomicSDNode *AM = cast<AtomicSDNode>(Node);
6248 SDLoc SL(Node);
6249 if (NVT.bitsGT(OVT)) {
6250 assert(NVT.isInteger() && "unexpected promotion type");
6251 MVT IntVT = MVT::getIntegerVT(OVT.getSizeInBits());
6252 EVT MemVT = AM->getMemoryVT().changeTypeToInteger();
6253 ISD::LoadExtType ExtType = AM->getExtensionType();
6254 if (ExtType == ISD::NON_EXTLOAD)
6255 ExtType = ISD::EXTLOAD;
6256 SDValue NewAtomic =
6257 DAG.getAtomicLoad(ExtType, SL, MemVT, NVT, AM->getChain(),
6258 AM->getBasePtr(), AM->getMemOperand());
6259 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, IntVT, NewAtomic);
6260 Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, Trunc));
6261 Results.push_back(NewAtomic.getValue(1));
6262 break;
6263 }
6264
6265 assert(NVT.getSizeInBits() == OVT.getSizeInBits() &&
6266 "unexpected promotion type");
6267 assert(AM->getMemoryVT().getSizeInBits() == NVT.getSizeInBits() &&
6268 "unexpected atomic_load with illegal type");
6269
6270 SDValue NewAtomic =
6271 DAG.getAtomic(ISD::ATOMIC_LOAD, SL, NVT, DAG.getVTList(NVT, MVT::Other),
6272 {AM->getChain(), AM->getBasePtr()}, AM->getMemOperand());
6273 Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewAtomic));
6274 Results.push_back(NewAtomic.getValue(1));
6275 break;
6276 }
6277 case ISD::SPLAT_VECTOR: {
6278 SDValue Scalar = Node->getOperand(0);
6279 MVT ScalarType = Scalar.getSimpleValueType();
6280 MVT NewScalarType = NVT.getVectorElementType();
6281 if (ScalarType.isInteger()) {
6282 Tmp1 = DAG.getNode(ISD::ANY_EXTEND, dl, NewScalarType, Scalar);
6283 Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
6284 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp2));
6285 break;
6286 }
6287 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NewScalarType, Scalar);
6288 Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
6289 Results.push_back(
6290 DAG.getNode(ISD::FP_ROUND, dl, OVT, Tmp2,
6291 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)));
6292 break;
6293 }
6300 case ISD::VP_REDUCE_FMAX:
6301 case ISD::VP_REDUCE_FMIN:
6302 case ISD::VP_REDUCE_FMAXIMUM:
6303 case ISD::VP_REDUCE_FMINIMUM:
6304 Results.push_back(PromoteReduction(Node));
6305 break;
6306 }
6307
6308 // Replace the original node with the legalized result.
6309 if (!Results.empty()) {
6310 LLVM_DEBUG(dbgs() << "Successfully promoted node\n");
6311 ReplaceNode(Node, Results.data());
6312 } else
6313 LLVM_DEBUG(dbgs() << "Could not promote node\n");
6314}
6315
6316/// This is the entry point for the file.
6319
6320 SmallPtrSet<SDNode *, 16> LegalizedNodes;
6321 // Use a delete listener to remove nodes which were deleted during
6322 // legalization from LegalizeNodes. This is needed to handle the situation
6323 // where a new node is allocated by the object pool to the same address of a
6324 // previously deleted node.
6325 DAGNodeDeletedListener DeleteListener(
6326 *this,
6327 [&LegalizedNodes](SDNode *N, SDNode *E) { LegalizedNodes.erase(N); });
6328
6329 SelectionDAGLegalize Legalizer(*this, LegalizedNodes);
6330
6331 // Visit all the nodes. We start in topological order, so that we see
6332 // nodes with their original operands intact. Legalization can produce
6333 // new nodes which may themselves need to be legalized. Iterate until all
6334 // nodes have been legalized.
6335 while (true) {
6336 bool AnyLegalized = false;
6337 for (auto NI = allnodes_end(); NI != allnodes_begin();) {
6338 --NI;
6339
6340 SDNode *N = &*NI;
6341 if (N->use_empty() && N != getRoot().getNode()) {
6342 ++NI;
6343 DeleteNode(N);
6344 continue;
6345 }
6346
6347 if (LegalizedNodes.insert(N).second) {
6348 AnyLegalized = true;
6349 Legalizer.LegalizeOp(N);
6350
6351 if (N->use_empty() && N != getRoot().getNode()) {
6352 ++NI;
6353 DeleteNode(N);
6354 }
6355 }
6356 }
6357 if (!AnyLegalized)
6358 break;
6359
6360 }
6361
6362 // Remove dead nodes now.
6364}
6365
6367 SmallSetVector<SDNode *, 16> &UpdatedNodes) {
6368 SmallPtrSet<SDNode *, 16> LegalizedNodes;
6369 SelectionDAGLegalize Legalizer(*this, LegalizedNodes, &UpdatedNodes);
6370
6371 // Directly insert the node in question, and legalize it. This will recurse
6372 // as needed through operands.
6373 LegalizedNodes.insert(N);
6374 Legalizer.LegalizeOp(N);
6375
6376 return LegalizedNodes.count(N);
6377}
#define Success
aarch64 falkor hwpf fix Falkor HW Prefetch Fix Late Phase
return SDValue()
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
uint64_t uint64_t
static bool isConstant(const MachineInstr &MI)
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
bpf unwind BPF Unwind Lower
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Legalizer
dxil translate DXIL Translate Metadata
static bool isSigned(unsigned Opcode)
Utilities for dealing with flags related to floating point properties and mode controls.
static MaybeAlign getAlign(Value *Ptr)
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool ExpandBVWithShuffles(SDNode *Node, SelectionDAG &DAG, const TargetLowering &TLI, SDValue &Res)
static bool isSinCosLibcallAvailable(SDNode *Node, const LibcallLoweringInfo &Libcalls)
Return true if sincos or __sincos_stret libcall is available.
static bool useSinCos(SDNode *Node)
Only issue sincos libcall if both sin and cos are needed.
static bool canUseFastMathLibcall(const SDNode *Node)
Return if we can use the FAST_* variant of a math libcall for the node.
static bool hasAtomicLibcallLowering(unsigned Opc)
static MachineMemOperand * getStackAlignedMMO(SDValue StackPtr, MachineFunction &MF, bool isObjectScalable)
static MVT getPromotedVectorElementType(const TargetLowering &TLI, MVT EltVT, MVT NewEltVT)
SmallVector< MachineOperand, 4 > Cond
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
std::pair< MCSymbol *, MachineModuleInfoImpl::StubValueTy > PairTy
Promote Memory to Register
Definition Mem2Reg.cpp:110
This file contains the declarations for metadata subclasses.
PowerPC Reduce CR logical Operation
static constexpr MCPhysReg SPReg
RISCVCC::CondCode CC
MachineInstr *& Lo
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
SI Fold Operands
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
This file describes how to lower LLVM code to machine code.
static constexpr int Concat[]
Value * RHS
Value * LHS
BinaryOperator * Mul
bool isSignaling() const
Definition APFloat.h:1618
static APFloat getSmallestNormalized(const fltSemantics &Sem, bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
Definition APFloat.h:1295
APInt bitcastToAPInt() const
Definition APFloat.h:1508
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1235
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:225
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition APInt.h:254
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const SDValue & getBasePtr() const
ISD::LoadExtType getExtensionType() const
const SDValue & getVal() const
LLVM_ABI Type * getStructRetType() const
static LLVM_ABI bool isValueValidForType(EVT VT, const APFloat &Val)
const APFloat & getValueAPF() const
const ConstantFP * getConstantFPValue() const
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const ConstantInt * getConstantIntValue() const
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:219
bool isBigEndian() const
Definition DataLayout.h:220
unsigned getAllocaAddrSpace() const
Definition DataLayout.h:254
LLVM_ABI Align getPrefTypeAlign(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
bool empty() const
Definition Function.h:853
const BasicBlock & back() const
Definition Function.h:856
LLVM_ABI void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
Tracks which library functions to use for a particular subtarget or function.
const RTLIB::RuntimeLibcallsInfo & getRuntimeLibcallsInfo() const
CallingConv::ID getLibcallImplCallingConv(RTLIB::LibcallImpl Call) const
Get the CallingConv that should be used for the specified libcall.
RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const
Return the lowering's selection of implementation call for Call.
static LocationSize precise(uint64_t Value)
static constexpr LocationSize beforeOrAfterPointer()
Any location before or after the base pointer (but still within the underlying object).
Machine Value Type.
SimpleValueType SimpleTy
uint64_t getScalarSizeInBits() const
bool bitsLE(MVT VT) const
Return true if this has no more bits than VT.
unsigned getVectorNumElements() const
bool isVector() const
Return true if this is a vector value type.
bool isInteger() const
Return true if this is an integer or a vector integer type.
bool bitsLT(MVT VT) const
Return true if this has less bits than VT.
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
bool bitsGT(MVT VT) const
Return true if this has more bits than VT.
static MVT getVectorVT(MVT VT, unsigned NumElements)
MVT getVectorElementType() const
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
static MVT getIntegerVT(unsigned BitWidth)
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
Function & getFunction()
Return the LLVM function that this machine code represents.
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
const MachineJumpTableInfo * getJumpTableInfo() const
getJumpTableInfo - Return the jump table info object for the current function.
LLVM_ABI unsigned getEntrySize(const DataLayout &TD) const
getEntrySize - Return the size of each entry in the jump table.
A description of a memory reference used in the backend.
Flags
Flags values. These may be or'd together.
@ MOStore
The memory access writes data.
MachineMemOperand * getMemOperand() const
Return the unique MachineMemOperand object describing the memory reference performed by operation.
const SDValue & getChain() const
EVT getMemoryVT() const
Return the type of the in-memory value.
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
const DebugLoc & getDebugLoc() const
Represents one node in the SelectionDAG.
bool isStrictFPOpcode()
Test if this node is a strict floating point pseudo-op.
ArrayRef< SDUse > ops() const
LLVM_ABI void dump() const
Dump this node, for debugging.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
static bool hasPredecessorHelper(const SDNode *N, SmallPtrSetImpl< const SDNode * > &Visited, SmallVectorImpl< const SDNode * > &Worklist, unsigned int MaxSteps=0, bool TopologicalPrune=false)
Returns true if N is a predecessor of any node in Worklist.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
const SDValue & getOperand(unsigned Num) const
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
iterator_range< user_iterator > users()
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isUndef() const
SDNode * getNode() const
get the SDNode which holds the desired result
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
const SDValue & getOperand(unsigned i) const
ISD::CondCode getOperandCondCode(unsigned i) const
uint64_t getScalarValueSizeInBits() const
unsigned getResNo() const
get the index which selects a specific result in the SDNode
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
unsigned getOpcode() const
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
LLVM_ABI SDValue getShiftAmountOperand(EVT LHSTy, SDValue Op)
Return the specified value casted to the target's desired shift amount type.
LLVM_ABI SDValue emitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT, const SDLoc &DL, SDValue Chain)
Emit a store/load combination to the stack.
const SDValue & getRoot() const
Return the root tag of the SelectionDAG.
bool isKnownNeverSNaN(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
LLVM_ABI SDValue makeStateFunctionCall(unsigned LibFunc, SDValue Ptr, SDValue InChain, SDNode *Node)
Helper used to make a call to a library function that has one argument of pointer type.
const TargetSubtargetInfo & getSubtarget() const
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, Register Reg, SDValue N)
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getShiftAmountConstant(uint64_t Val, EVT VT, const SDLoc &DL)
LLVM_ABI SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget=false, bool IsOpaque=false)
LLVM_ABI SDValue getAtomicLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT MemVT, EVT VT, SDValue Chain, SDValue Ptr, MachineMemOperand *MMO)
LLVM_ABI SDValue getConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offs=0, bool isT=false, unsigned TargetFlags=0)
LLVM_ABI SDValue getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDVTList VTs, SDValue Chain, SDValue Ptr, SDValue Cmp, SDValue Swp, MachineMemOperand *MMO)
Gets a node for an atomic cmpxchg op.
LLVM_ABI SDValue UnrollVectorOp(SDNode *N, unsigned ResNE=0)
Utility function used by legalize and lowering to "unroll" a vector operation by splitting out the sc...
LLVM_ABI SDValue getConstantFP(double Val, const SDLoc &DL, EVT VT, bool isTarget=false)
Create a ConstantFPSDNode wrapping a constant value.
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false, SDNodeFlags Flags={})
Helper function to make it easier to build SetCC's if you just have an ISD::CondCode instead of an SD...
LLVM_ABI SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDValue Chain, SDValue Ptr, SDValue Val, MachineMemOperand *MMO)
Gets a node for an atomic op, produces result (if relevant) and chain and takes 2 operands.
LLVM_ABI bool shouldOptForSize() const
LLVM_ABI bool hasSwiftErrorArg() const
LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
const TargetLowering & getTargetLoweringInfo() const
LLVM_ABI SDValue expandVACopy(SDNode *Node)
Expand the specified ISD::VACOPY node as the Legalize pass would.
allnodes_const_iterator allnodes_begin() const
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2, SDValue InGlue, const SDLoc &DL)
Return a new CALLSEQ_END node, which always must have a glue result (to ensure it's not CSE'd).
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
allnodes_const_iterator allnodes_end() const
LLVM_ABI void DeleteNode(SDNode *N)
Remove the specified node from the system.
LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT)
SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS, SDValue RHS, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build Select's if you just have operands and don't want to check...
LLVM_ABI SDValue getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT)
Return the expression required to zero extend the Op value assuming it was the smaller SrcTy value.
const DataLayout & getDataLayout() const
LLVM_ABI SDValue expandVAArg(SDNode *Node)
Expand the specified ISD::VAARG node as the Legalize pass would.
LLVM_ABI void Legalize()
This transforms the SelectionDAG into a SelectionDAG that is compatible with the target instruction s...
LLVM_ABI SDValue getTokenFactor(const SDLoc &DL, SmallVectorImpl< SDValue > &Vals)
Creates a new TokenFactor containing Vals.
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
LLVM_ABI bool LegalizeOp(SDNode *N, SmallSetVector< SDNode *, 16 > &UpdatedNodes)
Transforms a SelectionDAG node and any operands to it into a node that is compatible with the target ...
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
LLVM_ABI SDValue getMemBasePlusOffset(SDValue Base, TypeSize Offset, const SDLoc &DL, const SDNodeFlags Flags=SDNodeFlags())
Returns sum of the base pointer and offset.
LLVM_ABI SDValue getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, SDValue SV, unsigned Align)
VAArg produces a result and token chain, and takes a pointer and a source value as input.
LLVM_ABI void ReplaceAllUsesWith(SDValue From, SDValue To)
Modify anything using 'From' to use 'To' instead.
LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
SDValue getCALLSEQ_START(SDValue Chain, uint64_t InSize, uint64_t OutSize, const SDLoc &DL)
Return a new CALLSEQ_START node, that starts new call frame, in which InSize bytes are set up inside ...
LLVM_ABI void RemoveDeadNodes()
This method deletes all unreachable nodes in the SelectionDAG.
SDValue getSelectCC(const SDLoc &DL, SDValue LHS, SDValue RHS, SDValue True, SDValue False, ISD::CondCode Cond, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build SelectCC's if you just have an ISD::CondCode instead of an...
LLVM_ABI SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either sign-extending or trunca...
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI SDValue getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, EVT OpVT)
Convert Op, which must be of integer type, to the integer type VT, by using an extension appropriate ...
LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT)
const TargetMachine & getTarget() const
LLVM_ABI std::pair< SDValue, SDValue > getStrictFPExtendOrRound(SDValue Op, SDValue Chain, const SDLoc &DL, EVT VT)
Convert Op, which must be a STRICT operation of float type, to the float type VT, by either extending...
LLVM_ABI SDValue getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either any-extending or truncat...
const LibcallLoweringInfo & getLibcalls() const
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI SDValue getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of float type, to the float type VT, by either extending or rounding (by tr...
LLVM_ABI unsigned AssignTopologicalOrder()
Topological-sort the AllNodes list and a assign a unique node id for each node in the DAG based on th...
const TargetLibraryInfo & getLibInfo() const
LLVM_ABI SDValue getBoolConstant(bool V, const SDLoc &DL, EVT VT, EVT OpVT)
Create a true or false constant of type VT using the target's BooleanContent for type OpVT.
LLVM_ABI SDValue getVectorIdxConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
MachineFunction & getMachineFunction() const
LLVM_ABI SDValue getFreeze(SDValue V, UndefPoisonKind Kind=UndefPoisonKind::UndefOrPoison)
Return a freeze of V using the SDLoc of the value operand.
SDValue getPOISON(EVT VT)
Return a POISON node. POISON does not have a useful SDLoc.
SDValue getSplatBuildVector(EVT VT, const SDLoc &DL, SDValue Op)
Return a splat ISD::BUILD_VECTOR node, consisting of Op splatted to all elements.
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
LLVM_ABI SDValue getCondCode(ISD::CondCode Cond)
SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Ptr, TypeSize Offset)
Create an add instruction with appropriate flags when used for addressing some offset of an object.
LLVMContext * getContext() const
LLVM_ABI SDValue CreateStackTemporary(TypeSize Bytes, Align Alignment)
Create a stack temporary based on the size in bytes and the alignment.
LLVM_ABI SDNode * UpdateNodeOperands(SDNode *N, SDValue Op)
Mutate the specified node in-place to have the specified operands.
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
LLVM_ABI SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, ArrayRef< int > Mask)
Return an ISD::VECTOR_SHUFFLE node.
LLVM_ABI SDValue getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a logical NOT operation as (XOR Val, BooleanOne).
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
size_type size() const
Definition SmallSet.h:171
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void swap(SmallVectorImpl &RHS)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class is used to represent ISD::STORE nodes.
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
StackDirection getStackGrowthDirection() const
getStackGrowthDirection - Return the direction the stack grows
unsigned getIntSize() const
Get size of a C-level int or unsigned int, in bits.
bool isOperationExpand(unsigned Op, EVT VT) const
Return true if the specified operation is illegal on this target or unlikely to be made legal with cu...
virtual bool isShuffleMaskLegal(ArrayRef< int >, EVT) const
Targets can use this to indicate that they only support some VECTOR_SHUFFLE operations,...
virtual bool shouldExpandBuildVectorWithShuffles(EVT, unsigned DefinedValues) const
virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const
Return true if sign-extension from FromTy to ToTy is cheaper than zero-extension.
MVT getVectorIdxTy(const DataLayout &DL) const
Returns the type to be used for the index operand of: ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT...
bool isFPImmLegal(const APFloat &Imm, EVT VT, bool ForCodeSize=false) const
Returns true if the specified FP immediate can be materialized without a load from the constant pool.
bool isOperationLegalOrPromote(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal using promotion.
MVT getRegisterType(LLVMContext &Context, EVT VT) const
Return the type of registers that this ValueType will eventually require.
LegalizeAction getCondCodeAction(ISD::CondCode CC, MVT VT) const
Return how the condition code should be treated: either it is legal, needs to be expanded to some oth...
LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace) const
Return how this store with truncation should be treated: either it is legal, needs to be promoted to ...
Register getStackPointerRegisterToSaveRestore() const
If a physical register, this specifies the register that llvm.savestack/llvm.restorestack should save...
LegalizeAction getFixedPointOperationAction(unsigned Op, EVT VT, unsigned Scale) const
Some fixed point operations may be natively supported by the target but only for specific scales.
virtual ISD::NodeType getExtendForAtomicOps() const
Returns how the platform's atomic operations are extended (ZERO_EXTEND, SIGN_EXTEND,...
EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL) const
Returns the type for the shift amount of a shift opcode.
bool isStrictFPEnabled() const
Return true if the target support strict float operation.
virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const
Return the ValueType of the result of SETCC operations.
virtual EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
LegalizeAction getVectorInterleaveAction(unsigned Opc, unsigned Factor, EVT VT) const
Return how a VECTOR_INTERLEAVE or VECTOR_DEINTERLEAVE node with the given interleave factor and VT sh...
bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const
Return true if the specified condition code is legal for a comparison of the specified types on this ...
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
MVT getProgramPointerTy(const DataLayout &DL) const
Return the type for code pointers, which is determined by the program address space specified through...
virtual bool isJumpTableRelative() const
virtual bool ShouldShrinkFPConstant(EVT) const
If true, then instruction selection should seek to shrink the FP constant of the specified type to a ...
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
bool isOperationLegal(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target.
bool isOperationLegalOrCustom(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
virtual bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *Fast=nullptr) const
Return true if the target supports a memory access of this type for the given address space and align...
virtual LegalizeAction getCustomOperationAction(SDNode &Op) const
How to legalize this custom operation?
LegalizeAction getLoadAction(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace, unsigned ExtType, bool Atomic) const
Return how this load with extension should be treated: either it is legal, needs to be promoted to a ...
virtual FPImmAction getFPImmAction(const APFloat &, EVT, bool ForCodeSize=false) const
Returns how the legalizer should materialize the specified FP immediate.
LegalizeAction getStrictFPOperationAction(unsigned Op, EVT VT) const
virtual bool useSoftFloat() const
LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const
Return how we should legalize values of this type, either it is already legal (return 'Legal') or we ...
virtual bool shouldSignExtendTypeInLibCall(Type *Ty, bool IsSigned) const
Returns true if arguments should be sign-extended in lib calls.
std::vector< ArgListEntry > ArgListTy
bool allowsMemoryAccessForAlignment(LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *Fast=nullptr) const
This function returns true if the memory access is aligned or if the target allows this specific unal...
bool isTruncStoreLegalOrCustom(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace) const
Return true if the specified store with truncation has solution on this target.
bool isCondCodeLegalOrCustom(ISD::CondCode CC, MVT VT) const
Return true if the specified condition code is legal or custom for a comparison of the specified type...
MVT getFrameIndexTy(const DataLayout &DL) const
Return the type for frame index, which is determined by the alloca address space specified through th...
bool isLoadLegal(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace, unsigned ExtType, bool Atomic) const
Return true if the specified load with extension is legal on this target.
bool isLoadLegalOrCustom(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace, unsigned ExtType, bool Atomic) const
Return true if the specified load with extension is legal or custom on this target.
LegalizeAction getOperationAction(unsigned Op, EVT VT) const
Return how this operation should be treated: either it is legal, needs to be promoted to a larger siz...
MVT getTypeToPromoteTo(unsigned Op, MVT VT) const
If the action for this operation is to promote, this method returns the ValueType to promote to.
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
SDValue expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[US][ADD|SUB]SAT.
void expandVectorDeinterleave(SDNode *Node, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const
Expand a VECTOR_DEINTERLEAVE without introducing wider vector types.
bool expandMultipleResultFPLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, SDNode *Node, SmallVectorImpl< SDValue > &Results, std::optional< unsigned > CallRetResNo={}) const
Expands a node with multiple results to an FP or vector libcall.
bool expandMULO(SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[US]MULO.
bool expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT, SelectionDAG &DAG, MulExpansionKind Kind, SDValue LL=SDValue(), SDValue LH=SDValue(), SDValue RL=SDValue(), SDValue RH=SDValue()) const
Expand a MUL into two nodes.
bool LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC, bool &NeedInvert, const SDLoc &dl, SDValue &Chain, bool IsSignaling=false) const
Legalize a SETCC with given LHS and RHS and condition code CC on the current target.
SDValue scalarizeVectorStore(StoreSDNode *ST, SelectionDAG &DAG) const
void forceExpandWideMUL(SelectionDAG &DAG, const SDLoc &dl, bool Signed, const SDValue LHS, const SDValue RHS, SDValue &Lo, SDValue &Hi) const
Calculate full product of LHS and RHS either via a libcall or through brute force expansion of the mu...
SDValue expandFCANONICALIZE(SDNode *Node, SelectionDAG &DAG) const
Expand FCANONICALIZE to FMUL with 1.
SDValue expandCTLZ(SDNode *N, SelectionDAG &DAG) const
Expand CTLZ/CTLZ_ZERO_POISON nodes.
SDValue expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const
Expand BITREVERSE nodes.
SDValue expandCTTZ(SDNode *N, SelectionDAG &DAG) const
Expand CTTZ/CTTZ_ZERO_POISON nodes.
virtual SDValue expandIndirectJTBranch(const SDLoc &dl, SDValue Value, SDValue Addr, int JTI, SelectionDAG &DAG) const
Expands target specific indirect branch for the case of JumpTable expansion.
SDValue expandABD(SDNode *N, SelectionDAG &DAG) const
Expand ABDS/ABDU nodes.
SDValue expandCLMUL(SDNode *N, SelectionDAG &DAG) const
Expand carryless multiply.
SDValue expandShlSat(SDNode *Node, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[US]SHLSAT.
SDValue expandIS_FPCLASS(EVT ResultVT, SDValue Op, FPClassTest Test, SDNodeFlags Flags, const SDLoc &DL, SelectionDAG &DAG) const
Expand check for floating point class.
SDValue expandFP_TO_INT_SAT(SDNode *N, SelectionDAG &DAG) const
Expand FP_TO_[US]INT_SAT into FP_TO_[US]INT and selects or min/max.
SDValue expandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG) const
Expands an unaligned store to 2 half-size stores for integer values, and possibly more for vectors.
void expandSADDSUBO(SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::S(ADD|SUB)O.
SDValue expandABS(SDNode *N, SelectionDAG &DAG, bool IsNegative=false) const
Expand ABS nodes.
SDValue expandVecReduce(SDNode *Node, SelectionDAG &DAG) const
Expand a VECREDUCE_* into an explicit calculation.
SDValue expandVPCTTZElements(SDNode *N, SelectionDAG &DAG) const
Expand VP_CTTZ_ELTS/VP_CTTZ_ELTS_ZERO_POISON nodes.
bool expandFP_TO_UINT(SDNode *N, SDValue &Result, SDValue &Chain, SelectionDAG &DAG) const
Expand float to UINT conversion.
bool expandREM(SDNode *Node, SDValue &Result, SelectionDAG &DAG) const
Expand an SREM or UREM using SDIV/UDIV or SDIVREM/UDIVREM, if legal.
std::pair< SDValue, SDValue > expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const
Expands an unaligned load to 2 half-size loads for an integer, and possibly more for vectors.
SDValue expandFMINIMUMNUM_FMAXIMUMNUM(SDNode *N, SelectionDAG &DAG) const
Expand fminimumnum/fmaximumnum into multiple comparison with selects.
void expandVectorInterleave(SDNode *Node, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const
Expand a VECTOR_INTERLEAVE without introducing wider vector types.
SDValue expandVectorSplice(SDNode *Node, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::VECTOR_SPLICE.
SDValue getVectorSubVecPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT, EVT SubVecVT, SDValue Index, const SDNodeFlags PtrArithFlags=SDNodeFlags()) const
Get a pointer to a sub-vector of type SubVecVT at index Idx located in memory for a vector of type Ve...
SDValue expandCTPOP(SDNode *N, SelectionDAG &DAG) const
Expand CTPOP nodes.
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
SDValue expandBSWAP(SDNode *N, SelectionDAG &DAG) const
Expand BSWAP nodes.
SDValue expandFMINIMUM_FMAXIMUM(SDNode *N, SelectionDAG &DAG) const
Expand fminimum/fmaximum into multiple comparison with selects.
bool expandFP_TO_SINT(SDNode *N, SDValue &Result, SelectionDAG &DAG) const
Expand float(f32) to SINT(i64) conversion.
virtual SDValue getPICJumpTableRelocBase(SDValue Table, SelectionDAG &DAG) const
Returns relocation base for the given PIC jumptable.
std::pair< SDValue, SDValue > scalarizeVectorLoad(LoadSDNode *LD, SelectionDAG &DAG) const
Turn load of vector type into a load of the individual elements.
bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node, SDValue &Chain) const
Check whether a given call node is in tail position within its function.
SDValue expandCONVERT_TO_ARBITRARY_FP(SDNode *Node, SelectionDAG &DAG) const
Expand CONVERT_TO_ARBITRARY_FP using bit manipulation.
SDValue expandFunnelShift(SDNode *N, SelectionDAG &DAG) const
Expand funnel shift.
virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const
This callback is invoked for operations that are unsupported by the target, which are registered to u...
SDValue expandFixedPointDiv(unsigned Opcode, const SDLoc &dl, SDValue LHS, SDValue RHS, unsigned Scale, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[US]DIVFIX[SAT].
SDValue expandPEXT(SDNode *N, SelectionDAG &DAG) const
Expand parallel bit extract (compress).
bool expandMODF(SDNode *N, SelectionDAG &DAG, SmallVectorImpl< SDValue > &Results) const
Expand MODF node into fractional and integer parts.
SDValue expandFP_ROUND(SDNode *Node, SelectionDAG &DAG) const
Expand round(fp) to fp conversion.
SDValue expandCONVERT_FROM_ARBITRARY_FP(SDNode *Node, SelectionDAG &DAG) const
Expand CONVERT_FROM_ARBITRARY_FP using bit manipulation.
SDValue expandROT(SDNode *N, bool AllowVectorOps, SelectionDAG &DAG) const
Expand rotations.
SDValue getVectorElementPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT, SDValue Index, const SDNodeFlags PtrArithFlags=SDNodeFlags()) const
Get a pointer to vector element Idx located in memory for a vector of type VecVT starting at a base a...
SDValue expandFMINNUM_FMAXNUM(SDNode *N, SelectionDAG &DAG) const
Expand fminnum/fmaxnum into fminnum_ieee/fmaxnum_ieee with quieted inputs.
std::pair< SDValue, SDValue > makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl, EVT RetVT, ArrayRef< SDValue > Ops, MakeLibCallOptions CallOptions, const SDLoc &dl, SDValue Chain=SDValue()) const
Returns a pair of (return value, chain).
SDValue expandCMP(SDNode *Node, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[US]CMP.
SDValue expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[U|S]MULFIX[SAT].
void expandUADDSUBO(SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::U(ADD|SUB)O.
SDValue expandPDEP(SDNode *N, SelectionDAG &DAG) const
Expand parallel bit deposit (expand).
bool expandUINT_TO_FP(SDNode *N, SDValue &Result, SDValue &Chain, SelectionDAG &DAG) const
Expand UINT(i64) to double(f64) conversion.
bool expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl, SDValue LHS, SDValue RHS, SmallVectorImpl< SDValue > &Result, EVT HiLoVT, SelectionDAG &DAG, MulExpansionKind Kind, SDValue LL=SDValue(), SDValue LH=SDValue(), SDValue RL=SDValue(), SDValue RH=SDValue()) const
Expand a MUL or [US]MUL_LOHI of n-bit values into two or four nodes, respectively,...
SDValue expandAVG(SDNode *N, SelectionDAG &DAG) const
Expand vector/scalar AVGCEILS/AVGCEILU/AVGFLOORS/AVGFLOORU nodes.
SDValue expandCTLS(SDNode *N, SelectionDAG &DAG) const
Expand CTLS (count leading sign bits) nodes.
Primary interface to the complete machine description for the target machine.
const Triple & getTargetTriple() const
virtual const TargetFrameLowering * getFrameLowering() const
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
LLVM Value Representation.
Definition Value.h:75
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Entry
Definition COFF.h:862
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:851
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:263
@ STACKRESTORE
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain.
@ STACKSAVE
STACKSAVE - STACKSAVE has one operand, an input chain.
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition ISDOpcodes.h:516
@ POISON
POISON - A poison node.
Definition ISDOpcodes.h:238
@ SET_FPENV
Sets the current floating-point environment.
@ VECREDUCE_SEQ_FADD
Generic reduction nodes.
@ EH_SJLJ_LONGJMP
OUTCHAIN = EH_SJLJ_LONGJMP(INCHAIN, buffer) This corresponds to the eh.sjlj.longjmp intrinsic.
Definition ISDOpcodes.h:170
@ VECREDUCE_FMINIMUMNUM
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:277
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:605
@ STACKADDRESS
STACKADDRESS - Represents the llvm.stackaddress intrinsic.
Definition ISDOpcodes.h:129
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:811
@ SMULFIX
RESULT = [US]MULFIX(LHS, RHS, SCALE) - Perform fixed point multiplication on 2 integers with the same...
Definition ISDOpcodes.h:397
@ VAEND
VAEND, VASTART - VAEND and VASTART have three operands: an input chain, pointer, and a SRCVALUE.
@ ATOMIC_STORE
OUTCHAIN = ATOMIC_STORE(INCHAIN, val, ptr) This corresponds to "store atomic" instruction.
@ FRAME_TO_ARGS_OFFSET
FRAME_TO_ARGS_OFFSET - This node represents offset from frame pointer to first (possible) on-stack ar...
Definition ISDOpcodes.h:147
@ RESET_FPENV
Set floating-point environment to default state.
@ FMAD
FMAD - Perform a * b + c, while getting the same result as the separately rounded operations.
Definition ISDOpcodes.h:527
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ SMULFIXSAT
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition ISDOpcodes.h:403
@ SET_FPMODE
Sets the current dynamic floating-point control modes.
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:885
@ CTTZ_ELTS
Returns the number of number of trailing (least significant) zero elements in a vector.
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:523
@ FMODF
FMODF - Decomposes the operand into integral and fractional parts, each having the same type and sign...
@ FATAN2
FATAN2 - atan2, inspired by libm.
@ FSINCOSPI
FSINCOSPI - Compute both the sine and cosine times pi more accurately than FSINCOS(pi*x),...
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:222
@ EH_SJLJ_SETUP_DISPATCH
OUTCHAIN = EH_SJLJ_SETUP_DISPATCH(INCHAIN) The target initializes the dispatch table here.
Definition ISDOpcodes.h:174
@ GlobalAddress
Definition ISDOpcodes.h:90
@ ATOMIC_CMP_SWAP_WITH_SUCCESS
Val, Success, OUTCHAIN = ATOMIC_CMP_SWAP_WITH_SUCCESS(INCHAIN, ptr, cmp, swap) N.b.
@ STRICT_FMINIMUM
Definition ISDOpcodes.h:476
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:912
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:589
@ VECREDUCE_FMAX
FMIN/FMAX nodes can have flags, for NaN/NoNaN variants.
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ VECREDUCE_FMAXIMUM
FMINIMUM/FMAXIMUM nodes propatate NaNs and signed zeroes using the llvm.minimum and llvm....
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:771
@ ATOMIC_FENCE
OUTCHAIN = ATOMIC_FENCE(INCHAIN, ordering, scope) This corresponds to the fence instruction.
@ RESET_FPMODE
Sets default dynamic floating-point control modes.
@ SDIVREM
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition ISDOpcodes.h:282
@ FP16_TO_FP
FP16_TO_FP, FP_TO_FP16 - These operators are used to perform promotions and truncation for half-preci...
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:256
@ CLMUL
Carry-less multiplication operations.
Definition ISDOpcodes.h:802
@ INIT_TRAMPOLINE
INIT_TRAMPOLINE - This corresponds to the init_trampoline intrinsic.
@ FLDEXP
FLDEXP - ldexp, inspired by libm (op0 * 2**op1).
@ SDIVFIX
RESULT = [US]DIVFIX(LHS, RHS, SCALE) - Perform fixed point division on 2 integers with the same width...
Definition ISDOpcodes.h:410
@ STRICT_FSQRT
Constrained versions of libm-equivalent floating point intrinsics.
Definition ISDOpcodes.h:441
@ BUILTIN_OP_END
BUILTIN_OP_END - This must be the last enum value in this list.
@ GlobalTLSAddress
Definition ISDOpcodes.h:91
@ CONVERT_FROM_ARBITRARY_FP
CONVERT_FROM_ARBITRARY_FP - This operator converts from an arbitrary floating-point represented as an...
@ CTLZ_ZERO_POISON
Definition ISDOpcodes.h:820
@ EH_RETURN
OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER) - This node represents 'eh_return' gcc dwarf builtin,...
Definition ISDOpcodes.h:158
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:876
@ AVGCEILS
AVGCEILS/AVGCEILU - Rounding averaging add - Add two integers using an integer of type i[N+2],...
Definition ISDOpcodes.h:731
@ STRICT_UINT_TO_FP
Definition ISDOpcodes.h:490
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:681
@ READSTEADYCOUNTER
READSTEADYCOUNTER - This corresponds to the readfixedcounter intrinsic.
@ ADDROFRETURNADDR
ADDROFRETURNADDR - Represents the llvm.addressofreturnaddress intrinsic.
Definition ISDOpcodes.h:119
@ VECREDUCE_FADD
These reductions have relaxed evaluation order semantics, and have a single vector operand.
@ PREFETCH
PREFETCH - This corresponds to a prefetch intrinsic.
@ VECREDUCE_FMAXIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM nodes do not propagate NaNs and order signed zeroes using the llvm....
@ FSINCOS
FSINCOS - Compute both fsin and fcos as a single operation.
@ SETCCCARRY
Like SetCC, ops #0 and #1 are the LHS and RHS operands to compare, but op #2 is a boolean indicating ...
Definition ISDOpcodes.h:859
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ BR_CC
BR_CC - Conditional branch.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:355
@ BR_JT
BR_JT - Jumptable branch.
@ VECTOR_INTERLEAVE
VECTOR_INTERLEAVE(VEC1, VEC2, ...) - Returns N vectors from N input vectors, where N is the factor to...
Definition ISDOpcodes.h:640
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:546
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:553
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:377
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:828
@ ATOMIC_LOAD
Val, OUTCHAIN = ATOMIC_LOAD(INCHAIN, ptr) This corresponds to "load atomic" instruction.
@ UNDEF
UNDEF - An undefined node.
Definition ISDOpcodes.h:235
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:249
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:688
@ VACOPY
VACOPY - VACOPY has 5 operands: an input chain, a destination pointer, a source pointer,...
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:351
@ CTLS
Count leading redundant sign bits.
Definition ISDOpcodes.h:824
@ VECREDUCE_ADD
Integer reductions may have a result type larger than the vector element type.
@ GET_ROUNDING
Returns current rounding mode: -1 Undefined 0 Round to 0 1 Round to nearest, ties to even 2 Round to ...
@ STRICT_FP_TO_FP16
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:720
@ GET_FPMODE
Reads the current dynamic floating-point control modes.
@ STRICT_FP16_TO_FP
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:793
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:659
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:619
@ STRICT_FMAXIMUM
Definition ISDOpcodes.h:475
@ READ_REGISTER
READ_REGISTER, WRITE_REGISTER - This node represents llvm.register on the DAG, which implements the n...
Definition ISDOpcodes.h:141
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:581
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:882
@ TargetConstantFP
Definition ISDOpcodes.h:182
@ DEBUGTRAP
DEBUGTRAP - Trap intended to get the attention of a debugger.
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:843
@ ATOMIC_CMP_SWAP
Val, OUTCHAIN = ATOMIC_CMP_SWAP(INCHAIN, ptr, cmp, swap) For double-word atomic operations: ValLo,...
@ FMINNUM
FMINNUM/FMAXNUM - Same semantics as the llvm.minnum/maxnum intrinsics.
@ UBSANTRAP
UBSANTRAP - Trap with an immediate describing the kind of sanitizer failure.
@ SSHLSAT
RESULT = [US]SHLSAT(LHS, RHS) - Perform saturation left shift.
Definition ISDOpcodes.h:389
@ SMULO
Same for multiplication.
Definition ISDOpcodes.h:359
@ DYNAMIC_STACKALLOC
DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned to a specified boundary.
@ VECTOR_SPLICE_LEFT
VECTOR_SPLICE_LEFT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1, VEC2) left by OFFSET elements an...
Definition ISDOpcodes.h:669
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:920
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:751
@ SDIVFIXSAT
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition ISDOpcodes.h:416
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
@ GLOBAL_OFFSET_TABLE
The address of the GOT.
Definition ISDOpcodes.h:105
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:331
@ STRICT_SINT_TO_FP
STRICT_[US]INT_TO_FP - Convert a signed or unsigned integer to a floating point value.
Definition ISDOpcodes.h:489
@ STRICT_BF16_TO_FP
@ STRICT_FROUNDEVEN
Definition ISDOpcodes.h:469
@ EH_DWARF_CFA
EH_DWARF_CFA - This node represents the pointer to the DWARF Canonical Frame Address (CFA),...
Definition ISDOpcodes.h:152
@ BF16_TO_FP
BF16_TO_FP, FP_TO_BF16 - These operators are used to perform promotions and truncation for bfloat16.
@ FRAMEADDR
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG.
Definition ISDOpcodes.h:112
@ STRICT_FP_TO_UINT
Definition ISDOpcodes.h:483
@ PEXT
Parallel bit extract (compress) and parallel bit deposit (expand).
Definition ISDOpcodes.h:807
@ STRICT_FP_ROUND
X = STRICT_FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision ...
Definition ISDOpcodes.h:505
@ STRICT_FP_TO_SINT
STRICT_FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:482
@ FMINIMUM
FMINIMUM/FMAXIMUM - Same semantics as the llvm.minimum/maximum intrinsics.
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:958
@ READCYCLECOUNTER
READCYCLECOUNTER - This corresponds to the readcyclecounter intrinsic.
@ TargetConstant
TargetConstant* - Like Constant*, but the DAG does not do any folding, simplification,...
Definition ISDOpcodes.h:181
@ STRICT_FP_EXTEND
X = STRICT_FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:510
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:763
@ TRAP
TRAP - Trapping instruction.
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:207
@ GET_FPENV_MEM
Gets the current floating-point environment.
@ STRICT_FP_TO_BF16
@ SCMP
[US]CMP - 3-way comparison of signed or unsigned integers.
Definition ISDOpcodes.h:759
@ AVGFLOORS
AVGFLOORS/AVGFLOORU - Averaging add - Add two integers using an integer of type i[N+1],...
Definition ISDOpcodes.h:726
@ VECTOR_SPLICE_RIGHT
VECTOR_SPLICE_RIGHT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1,VEC2) right by OFFSET elements a...
Definition ISDOpcodes.h:673
@ STRICT_FADD
Constrained versions of the binary floating point operators.
Definition ISDOpcodes.h:430
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:570
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
@ ATOMIC_SWAP
Val, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amt) Val, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN,...
@ CTTZ_ZERO_POISON
Bit counting operators with a poisoned result for zero inputs.
Definition ISDOpcodes.h:819
@ ExternalSymbol
Definition ISDOpcodes.h:95
@ FFREXP
FFREXP - frexp, extract fractional and exponent component of a floating-point value.
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:991
@ SPONENTRY
SPONENTRY - Represents the llvm.sponentry intrinsic.
Definition ISDOpcodes.h:124
@ CLEAR_CACHE
llvm.clear_cache intrinsic Operands: Input Chain, Start Addres, End Address Outputs: Output Chain
@ ADDRSPACECAST
ADDRSPACECAST - This operator converts between pointers of different address spaces.
@ EXPERIMENTAL_VECTOR_HISTOGRAM
Experimental vector histogram intrinsic Operands: Input Chain, Inc, Mask, Base, Index,...
@ STRICT_FNEARBYINT
Definition ISDOpcodes.h:461
@ FP_TO_SINT_SAT
FP_TO_[US]INT_SAT - Convert floating point value in operand 0 to a signed or unsigned scalar integer ...
Definition ISDOpcodes.h:977
@ VECREDUCE_FMINIMUM
@ EH_SJLJ_SETJMP
RESULT, OUTCHAIN = EH_SJLJ_SETJMP(INCHAIN, buffer) This corresponds to the eh.sjlj....
Definition ISDOpcodes.h:164
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:888
@ VAARG
VAARG - VAARG has four operands: an input chain, a pointer, a SRCVALUE, and the alignment.
@ BRCOND
BRCOND - Conditional branch.
@ VECREDUCE_SEQ_FMUL
@ CONVERT_TO_ARBITRARY_FP
CONVERT_TO_ARBITRARY_FP - Converts a native FP value to an arbitrary floating-point format,...
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:865
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:64
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:539
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:368
@ CALLSEQ_START
CALLSEQ_START/CALLSEQ_END - These operators mark the beginning and end of a call sequence,...
@ VECTOR_DEINTERLEAVE
VECTOR_DEINTERLEAVE(VEC1, VEC2, ...) - Returns N vectors from N input vectors, where N is the factor ...
Definition ISDOpcodes.h:629
@ GET_DYNAMIC_AREA_OFFSET
GET_DYNAMIC_AREA_OFFSET - get offset from native SP to the address of the most recent dynamic alloca.
@ CTTZ_ELTS_ZERO_POISON
@ SET_FPENV_MEM
Sets the current floating point environment.
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - Same semantics as the llvm.minimumnum/maximumnum intrinsics.
@ ABDS
ABDS/ABDU - Absolute difference - Return the absolute difference between two numbers interpreted as s...
Definition ISDOpcodes.h:746
@ ADJUST_TRAMPOLINE
ADJUST_TRAMPOLINE - This corresponds to the adjust_trampoline intrinsic.
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:215
@ ABS_MIN_POISON
ABS with a poison result for INT_MIN.
Definition ISDOpcodes.h:775
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:561
LLVM_ABI NodeType getExtForLoadExtType(bool IsFP, LoadExtType)
bool isNormalStore(const SDNode *N)
Returns true if the specified node is a non-truncating and unindexed store.
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, EVT Type)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
LLVM_ABI std::optional< unsigned > getVPMaskIdx(unsigned Opcode)
The operand position of the vector mask.
LLVM_ABI CondCode getSetCCSwappedOperands(CondCode Operation)
Return the operation corresponding to (Y op X) when given the operation for (X op Y).
bool isSignedIntSetCC(CondCode Code)
Return true if this is a setcc instruction that performs a signed comparison when used with integer o...
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
LLVM_ABI bool isVPOpcode(unsigned Opcode)
Whether this is a vector-predicated Opcode.
constexpr MCPhysReg SP
LLVM_ABI Libcall getSINTTOFP(EVT OpVT, EVT RetVT)
getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getUINTTOFP(EVT OpVT, EVT RetVT)
getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getFPLibCall(EVT VT, Libcall Call_F32, Libcall Call_F64, Libcall Call_F80, Libcall Call_F128, Libcall Call_PPCF128)
GetFPLibCall - Helper to return the right libcall for the given floating point type,...
LLVM_ABI Libcall getFPTOUINT(EVT OpVT, EVT RetVT)
getFPTOUINT - Return the FPTOUINT_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getFPTOSINT(EVT OpVT, EVT RetVT)
getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getFPEXT(EVT OpVT, EVT RetVT)
getFPEXT - Return the FPEXT_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getFPROUND(EVT OpVT, EVT RetVT)
getFPROUND - Return the FPROUND_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI AtomicLibcall selectAtomicLibcall(const LibcallLoweringInfo &Libcalls, unsigned Opc, AtomicOrdering Order, MVT VT)
Lower to outline atomic libcall if outline atomics enabled, or to sync libcall otherwise.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:680
constexpr double e
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:339
@ Offset
Definition DWP.cpp:577
@ Undef
Value of the register doesn't matter.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Load
The value being inserted comes from a load (InsertElement only).
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
APFloat scalbn(APFloat X, int Exp, APFloat::roundingMode RM)
Returns: X * 2^Exp for integral exponents.
Definition APFloat.h:1749
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
AtomicOrdering
Atomic ordering for LLVM's memory model.
To bit_cast(const From &from) noexcept
Definition bit.h:90
@ Or
Bitwise or logical OR of integers.
@ And
Bitwise or logical AND of integers.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ Fast
Assign the register banks as fast as possible (default).
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isOneConstant(SDValue V)
Returns true if V is a constant integer one.
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
Extended Value Type.
Definition ValueTypes.h:35
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h:433
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
EVT changeTypeToInteger() const
Return the type converted to an equivalently sized integer or vector with integer element type.
Definition ValueTypes.h:144
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:322
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:338
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:170
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:411
bool isByteSized() const
Return true if the bit size is a multiple of 8.
Definition ValueTypes.h:281
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:423
EVT getHalfSizedIntegerVT(LLVMContext &Context) const
Finds the smallest simple value type that is greater than or equal to half the width of this EVT.
Definition ValueTypes.h:468
TypeSize getStoreSizeInBits() const
Return the number of bits overwritten by a store of the specified value type.
Definition ValueTypes.h:450
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:354
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:61
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:191
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:361
bool bitsGE(EVT VT) const
Return true if this has no less bits than VT.
Definition ValueTypes.h:330
bool bitsEq(EVT VT) const
Return true if this has the same number of bits as VT.
Definition ValueTypes.h:294
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
bool isScalableVector() const
Return true if this is a vector type where the runtime length is machine dependent.
Definition ValueTypes.h:202
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:366
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:180
LLVM_ABI const fltSemantics & getFltSemantics() const
Returns an APFloat semantics tag appropriate for the value type.
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:374
bool bitsLE(EVT VT) const
Return true if this has no more bits than VT.
Definition ValueTypes.h:346
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:175
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getJumpTable(MachineFunction &MF)
Return a MachinePointerInfo record that refers to a jump table entry.
LLVM_ABI unsigned getAddrSpace() const
Return the LLVM IR address space number that this pointer points into.
static LLVM_ABI MachinePointerInfo getConstantPool(MachineFunction &MF)
Return a MachinePointerInfo record that refers to the constant pool.
MachinePointerInfo getWithOffset(int64_t O) const
static LLVM_ABI MachinePointerInfo getUnknownStack(MachineFunction &MF)
Stack memory without other information.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
CallingConv::ID getLibcallImplCallingConv(RTLIB::LibcallImpl Call) const
Get the CallingConv that should be used for the specified libcall.
LLVM_ABI std::pair< FunctionType *, AttributeList > getFunctionTy(LLVMContext &Ctx, const Triple &TT, const DataLayout &DL, RTLIB::LibcallImpl LibcallImpl) const
These are IR-level optimization flags that may be propagated to SDNodes.
void setNoUnsignedWrap(bool b)
void setNoSignedWrap(bool b)
MakeLibCallOptions & setIsSigned(bool Value=true)