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