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