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