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