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